repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/config/ignored_fields.rs
pageserver/src/config/ignored_fields.rs
//! Check for fields in the on-disk config file that were ignored when //! deserializing [`pageserver_api::config::ConfigToml`]. //! //! This could have been part of the [`pageserver_api::config`] module, //! but the way we identify unused fields in this module //! is specific to the format (TOML) and the implementation of the //! deserialization for that format ([`toml_edit`]). use std::collections::HashSet; use itertools::Itertools; /// Pass in the user-specified config and the re-serialized [`pageserver_api::config::ConfigToml`]. /// The returned [`Paths`] contains the paths to the fields that were ignored by deserialization /// of the [`pageserver_api::config::ConfigToml`]. pub fn find(user_specified: toml_edit::DocumentMut, reserialized: toml_edit::DocumentMut) -> Paths { let user_specified = paths(user_specified); let reserialized = paths(reserialized); fn paths(doc: toml_edit::DocumentMut) -> HashSet<String> { let mut out = Vec::new(); let mut visitor = PathsVisitor::new(&mut out); visitor.visit_table_like(doc.as_table()); HashSet::from_iter(out) } let mut ignored = HashSet::new(); // O(n) because of HashSet for path in user_specified { if !reserialized.contains(&path) { ignored.insert(path); } } Paths { paths: ignored .into_iter() // sort lexicographically for deterministic output .sorted() .collect(), } } pub struct Paths { pub paths: Vec<String>, } struct PathsVisitor<'a> { stack: Vec<String>, out: &'a mut Vec<String>, } impl<'a> PathsVisitor<'a> { fn new(out: &'a mut Vec<String>) -> Self { Self { stack: Vec::new(), out, } } fn visit_table_like(&mut self, table_like: &dyn toml_edit::TableLike) { for (entry, item) in table_like.iter() { self.stack.push(entry.to_string()); self.visit_item(item); self.stack.pop(); } } fn visit_item(&mut self, item: &toml_edit::Item) { match item { toml_edit::Item::None => (), toml_edit::Item::Value(value) => self.visit_value(value), toml_edit::Item::Table(table) => { self.visit_table_like(table); } toml_edit::Item::ArrayOfTables(array_of_tables) => { for (i, table) in array_of_tables.iter().enumerate() { self.stack.push(format!("[{i}]")); self.visit_table_like(table); self.stack.pop(); } } } } fn visit_value(&mut self, value: &toml_edit::Value) { match value { toml_edit::Value::String(_) | toml_edit::Value::Integer(_) | toml_edit::Value::Float(_) | toml_edit::Value::Boolean(_) | toml_edit::Value::Datetime(_) => self.out.push(self.stack.join(".")), toml_edit::Value::Array(array) => { for (i, value) in array.iter().enumerate() { self.stack.push(format!("[{i}]")); self.visit_value(value); self.stack.pop(); } } toml_edit::Value::InlineTable(inline_table) => self.visit_table_like(inline_table), } } } #[cfg(test)] pub(crate) mod tests { fn test_impl(original: &str, parsed: &str, expect: [&str; 1]) { let original: toml_edit::DocumentMut = original.parse().expect("parse original config"); let parsed: toml_edit::DocumentMut = parsed.parse().expect("parse re-serialized config"); let super::Paths { paths: actual } = super::find(original, parsed); assert_eq!(actual, &expect); } #[test] fn top_level() { test_impl( r#" [a] b = 1 c = 2 d = 3 "#, r#" [a] b = 1 c = 2 "#, ["a.d"], ); } #[test] fn nested() { test_impl( r#" [a.b.c] d = 23 "#, r#" [a] e = 42 "#, ["a.b.c.d"], ); } #[test] fn array_of_tables() { test_impl( r#" [[a]] b = 1 c = 2 d = 3 "#, r#" [[a]] b = 1 c = 2 "#, ["a.[0].d"], ); } #[test] fn array() { test_impl( r#" foo = [ {bar = 23} ] "#, r#" foo = [ { blup = 42 }] "#, ["foo.[0].bar"], ); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/walredo/process.rs
pageserver/src/walredo/process.rs
mod no_leak_child; /// The IPC protocol that pageserver and walredo process speak over their shared pipe. mod protocol; use std::collections::VecDeque; use std::process::{Command, Stdio}; #[cfg(feature = "testing")] use std::sync::atomic::AtomicUsize; use std::time::Duration; use anyhow::Context; use bytes::Bytes; use pageserver_api::reltag::RelTag; use pageserver_api::shard::TenantShardId; use postgres_ffi::{BLCKSZ, PgMajorVersion}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tracing::{Instrument, debug, error, instrument}; use utils::lsn::Lsn; use utils::poison::Poison; use wal_decoder::models::record::NeonWalRecord; use self::no_leak_child::NoLeakChild; use crate::config::PageServerConf; use crate::metrics::{WAL_REDO_PROCESS_COUNTERS, WAL_REDO_RECORD_COUNTER, WalRedoKillCause}; use crate::page_cache::PAGE_SZ; use crate::span::debug_assert_current_span_has_tenant_id; pub struct WalRedoProcess { #[allow(dead_code)] conf: &'static PageServerConf, #[cfg(feature = "testing")] tenant_shard_id: TenantShardId, // Some() on construction, only becomes None on Drop. child: Option<NoLeakChild>, stdout: tokio::sync::Mutex<Poison<ProcessOutput>>, stdin: tokio::sync::Mutex<Poison<ProcessInput>>, /// Counter to separate same sized walredo inputs failing at the same millisecond. #[cfg(feature = "testing")] dump_sequence: AtomicUsize, } struct ProcessInput { stdin: tokio::process::ChildStdin, n_requests: usize, } struct ProcessOutput { stdout: tokio::process::ChildStdout, pending_responses: VecDeque<Option<Bytes>>, n_processed_responses: usize, } impl WalRedoProcess { // // Start postgres binary in special WAL redo mode. // #[instrument(skip_all,fields(pg_version=pg_version.major_version_num()))] pub(crate) fn launch( conf: &'static PageServerConf, tenant_shard_id: TenantShardId, pg_version: PgMajorVersion, ) -> anyhow::Result<Self> { crate::span::debug_assert_current_span_has_tenant_id(); let pg_bin_dir_path = conf.pg_bin_dir(pg_version).context("pg_bin_dir")?; // TODO these should be infallible. let pg_lib_dir_path = conf.pg_lib_dir(pg_version).context("pg_lib_dir")?; use no_leak_child::NoLeakChildCommandExt; // Start postgres itself let child = Command::new(pg_bin_dir_path.join("postgres")) // the first arg must be --wal-redo so the child process enters into walredo mode .arg("--wal-redo") // the child doesn't process this arg, but, having it in the argv helps indentify the // walredo process for a particular tenant when debugging a pagserver .args(["--tenant-shard-id", &format!("{tenant_shard_id}")]) .stdin(Stdio::piped()) .stderr(Stdio::piped()) .stdout(Stdio::piped()) .env_clear() .env("LD_LIBRARY_PATH", &pg_lib_dir_path) .env("DYLD_LIBRARY_PATH", &pg_lib_dir_path) .env( "ASAN_OPTIONS", std::env::var("ASAN_OPTIONS").unwrap_or_default(), ) .env( "UBSAN_OPTIONS", std::env::var("UBSAN_OPTIONS").unwrap_or_default(), ) // NB: The redo process is not trusted after we sent it the first // walredo work. Before that, it is trusted. Specifically, we trust // it to // 1. close all file descriptors except stdin, stdout, stderr because // pageserver might not be 100% diligent in setting FD_CLOEXEC on all // the files it opens, and // 2. to use seccomp to sandbox itself before processing the first // walredo request. .spawn_no_leak_child(tenant_shard_id) .context("spawn process")?; WAL_REDO_PROCESS_COUNTERS.started.inc(); let mut child = scopeguard::guard(child, |child| { error!("killing wal-redo-postgres process due to a problem during launch"); child.kill_and_wait(WalRedoKillCause::Startup); }); let stdin = child.stdin.take().unwrap(); let stdout = child.stdout.take().unwrap(); let stderr = child.stderr.take().unwrap(); let stderr = tokio::process::ChildStderr::from_std(stderr) .context("convert to tokio::ChildStderr")?; let stdin = tokio::process::ChildStdin::from_std(stdin).context("convert to tokio::ChildStdin")?; let stdout = tokio::process::ChildStdout::from_std(stdout) .context("convert to tokio::ChildStdout")?; // all fallible operations post-spawn are complete, so get rid of the guard let child = scopeguard::ScopeGuard::into_inner(child); tokio::spawn( async move { scopeguard::defer! { debug!("wal-redo-postgres stderr_logger_task finished"); crate::metrics::WAL_REDO_PROCESS_COUNTERS.active_stderr_logger_tasks_finished.inc(); } debug!("wal-redo-postgres stderr_logger_task started"); crate::metrics::WAL_REDO_PROCESS_COUNTERS.active_stderr_logger_tasks_started.inc(); use tokio::io::AsyncBufReadExt; let mut stderr_lines = tokio::io::BufReader::new(stderr); let mut buf = Vec::new(); let res = loop { buf.clear(); // TODO we don't trust the process to cap its stderr length. // Currently it can do unbounded Vec allocation. match stderr_lines.read_until(b'\n', &mut buf).await { Ok(0) => break Ok(()), // eof Ok(num_bytes) => { let output = String::from_utf8_lossy(&buf[..num_bytes]); if !output.contains("LOG:") { error!(%output, "received output"); } } Err(e) => { break Err(e); } } }; match res { Ok(()) => (), Err(e) => { error!(error=?e, "failed to read from walredo stderr"); } } }.instrument(tracing::info_span!(parent: None, "wal-redo-postgres-stderr", pid = child.id(), tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %pg_version)) ); Ok(Self { conf, #[cfg(feature = "testing")] tenant_shard_id, child: Some(child), stdin: tokio::sync::Mutex::new(Poison::new( "stdin", ProcessInput { stdin, n_requests: 0, }, )), stdout: tokio::sync::Mutex::new(Poison::new( "stdout", ProcessOutput { stdout, pending_responses: VecDeque::new(), n_processed_responses: 0, }, )), #[cfg(feature = "testing")] dump_sequence: AtomicUsize::default(), }) } pub(crate) fn id(&self) -> u32 { self.child .as_ref() .expect("must not call this during Drop") .id() } /// Apply given WAL records ('records') over an old page image. Returns /// new page image. /// /// # Cancel-Safety /// /// Cancellation safe. #[instrument(skip_all, fields(pid=%self.id()))] pub(crate) async fn apply_wal_records( &self, rel: RelTag, blknum: u32, base_img: &Option<Bytes>, records: &[(Lsn, NeonWalRecord)], wal_redo_timeout: Duration, ) -> anyhow::Result<Bytes> { debug_assert_current_span_has_tenant_id(); let tag = protocol::BufferTag { rel, blknum }; // Serialize all the messages to send the WAL redo process first. // // This could be problematic if there are millions of records to replay, // but in practice the number of records is usually so small that it doesn't // matter, and it's better to keep this code simple. // // Most requests start with a before-image with BLCKSZ bytes, followed by // by some other WAL records. Start with a buffer that can hold that // comfortably. let mut writebuf: Vec<u8> = Vec::with_capacity((BLCKSZ as usize) * 3); protocol::build_begin_redo_for_block_msg(tag, &mut writebuf); if let Some(img) = base_img { protocol::build_push_page_msg(tag, img, &mut writebuf); } for (lsn, rec) in records.iter() { if let NeonWalRecord::Postgres { will_init: _, rec: postgres_rec, } = rec { protocol::build_apply_record_msg(*lsn, postgres_rec, &mut writebuf); } else { anyhow::bail!("tried to pass neon wal record to postgres WAL redo"); } } protocol::build_get_page_msg(tag, &mut writebuf); WAL_REDO_RECORD_COUNTER.inc_by(records.len() as u64); let Ok(res) = tokio::time::timeout(wal_redo_timeout, self.apply_wal_records0(&writebuf)).await else { anyhow::bail!("WAL redo timed out"); }; if res.is_err() { // not all of these can be caused by this particular input, however these are so rare // in tests so capture all. self.record_and_log(&writebuf); } res } /// Do a ping request-response roundtrip. /// /// Not used in production, but by Rust benchmarks. pub(crate) async fn ping(&self, timeout: Duration) -> anyhow::Result<()> { let mut writebuf: Vec<u8> = Vec::with_capacity(4); protocol::build_ping_msg(&mut writebuf); let Ok(res) = tokio::time::timeout(timeout, self.apply_wal_records0(&writebuf)).await else { anyhow::bail!("WAL redo ping timed out"); }; let response = res?; if response.len() != PAGE_SZ { anyhow::bail!( "WAL redo ping response should respond with page-sized response: {}", response.len() ); } Ok(()) } /// # Cancel-Safety /// /// When not polled to completion (e.g. because in `tokio::select!` another /// branch becomes ready before this future), concurrent and subsequent /// calls may fail due to [`utils::poison::Poison::check_and_arm`] calls. /// Dispose of this process instance and create a new one. async fn apply_wal_records0(&self, writebuf: &[u8]) -> anyhow::Result<Bytes> { let request_no = { let mut lock_guard = self.stdin.lock().await; let mut poison_guard = lock_guard.check_and_arm()?; let input = poison_guard.data_mut(); input .stdin .write_all(writebuf) .await .context("write to walredo stdin")?; let request_no = input.n_requests; input.n_requests += 1; poison_guard.disarm(); request_no }; // To improve walredo performance we separate sending requests and receiving // responses. Them are protected by different mutexes (output and input). // If thread T1, T2, T3 send requests D1, D2, D3 to walredo process // then there is not warranty that T1 will first granted output mutex lock. // To address this issue we maintain number of sent requests, number of processed // responses and ring buffer with pending responses. After sending response // (under input mutex), threads remembers request number. Then it releases // input mutex, locks output mutex and fetch in ring buffer all responses until // its stored request number. The it takes correspondent element from // pending responses ring buffer and truncate all empty elements from the front, // advancing processed responses number. let mut lock_guard = self.stdout.lock().await; let mut poison_guard = lock_guard.check_and_arm()?; let output = poison_guard.data_mut(); let n_processed_responses = output.n_processed_responses; while n_processed_responses + output.pending_responses.len() <= request_no { // We expect the WAL redo process to respond with an 8k page image. We read it // into this buffer. let mut resultbuf = vec![0; BLCKSZ.into()]; output .stdout .read_exact(&mut resultbuf) .await .context("read walredo stdout")?; output .pending_responses .push_back(Some(Bytes::from(resultbuf))); } // Replace our request's response with None in `pending_responses`. // Then make space in the ring buffer by clearing out any seqence of contiguous // `None`'s from the front of `pending_responses`. // NB: We can't pop_front() because other requests' responses because another // requester might have grabbed the output mutex before us: // T1: grab input mutex // T1: send request_no 23 // T1: release input mutex // T2: grab input mutex // T2: send request_no 24 // T2: release input mutex // T2: grab output mutex // T2: n_processed_responses + output.pending_responses.len() <= request_no // 23 0 24 // T2: enters poll loop that reads stdout // T2: put response for 23 into pending_responses // T2: put response for 24 into pending_resposnes // pending_responses now looks like this: Front Some(response_23) Some(response_24) Back // T2: takes its response_24 // pending_responses now looks like this: Front Some(response_23) None Back // T2: does the while loop below // pending_responses now looks like this: Front Some(response_23) None Back // T2: releases output mutex // T1: grabs output mutex // T1: n_processed_responses + output.pending_responses.len() > request_no // 23 2 23 // T1: skips poll loop that reads stdout // T1: takes its response_23 // pending_responses now looks like this: Front None None Back // T2: does the while loop below // pending_responses now looks like this: Front Back // n_processed_responses now has value 25 let res = output.pending_responses[request_no - n_processed_responses] .take() .expect("we own this request_no, nobody else is supposed to take it"); while let Some(front) = output.pending_responses.front() { if front.is_none() { output.pending_responses.pop_front(); output.n_processed_responses += 1; } else { break; } } poison_guard.disarm(); Ok(res) } #[cfg(feature = "testing")] fn record_and_log(&self, writebuf: &[u8]) { use std::sync::atomic::Ordering; let millis = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) .unwrap() .as_millis(); let seq = self.dump_sequence.fetch_add(1, Ordering::Relaxed); // these files will be collected to an allure report let filename = format!("walredo-{millis}-{}-{seq}.walredo", writebuf.len()); let path = self.conf.tenant_path(&self.tenant_shard_id).join(&filename); use std::io::Write; let res = std::fs::OpenOptions::new() .write(true) .create_new(true) .read(true) .open(path) .and_then(|mut f| f.write_all(writebuf)); // trip up allowed_errors if let Err(e) = res { tracing::error!(target=%filename, length=writebuf.len(), "failed to write out the walredo errored input: {e}"); } else { tracing::error!(filename, "erroring walredo input saved"); } } #[cfg(not(feature = "testing"))] fn record_and_log(&self, _: &[u8]) {} } impl Drop for WalRedoProcess { fn drop(&mut self) { self.child .take() .expect("we only do this once") .kill_and_wait(WalRedoKillCause::WalRedoProcessDrop); // no way to wait for stderr_logger_task from Drop because that is async only } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/walredo/apply_neon.rs
pageserver/src/walredo/apply_neon.rs
use anyhow::Context; use byteorder::{ByteOrder, LittleEndian}; use bytes::BytesMut; use pageserver_api::key::Key; use pageserver_api::reltag::SlruKind; use postgres_ffi::v14::nonrelfile_utils::{ mx_offset_to_flags_bitshift, mx_offset_to_flags_offset, mx_offset_to_member_offset, transaction_id_set_status, }; use postgres_ffi::{BLCKSZ, pg_constants}; use postgres_ffi_types::forknum::VISIBILITYMAP_FORKNUM; use tracing::*; use utils::lsn::Lsn; use wal_decoder::models::record::NeonWalRecord; /// Can this request be served by neon redo functions /// or we need to pass it to wal-redo postgres process? pub(crate) fn can_apply_in_neon(rec: &NeonWalRecord) -> bool { // Currently, we don't have bespoken Rust code to replay any // Postgres WAL records. But everything else is handled in neon. #[allow(clippy::match_like_matches_macro)] match rec { NeonWalRecord::Postgres { will_init: _, rec: _, } => false, _ => true, } } pub(crate) fn apply_in_neon( record: &NeonWalRecord, lsn: Lsn, key: Key, page: &mut BytesMut, ) -> Result<(), anyhow::Error> { match record { NeonWalRecord::Postgres { will_init: _, rec: _, } => { anyhow::bail!("tried to pass postgres wal record to neon WAL redo"); } // // Code copied from PostgreSQL `visibilitymap_prepare_truncate` function in `visibilitymap.c` // NeonWalRecord::TruncateVisibilityMap { trunc_byte, trunc_offs, } => { // sanity check that this is modifying the correct relation let (rel, _) = key.to_rel_block().context("invalid record")?; assert!( rel.forknum == VISIBILITYMAP_FORKNUM, "TruncateVisibilityMap record on unexpected rel {rel}" ); let map = &mut page[pg_constants::MAXALIGN_SIZE_OF_PAGE_HEADER_DATA..]; map[*trunc_byte + 1..].fill(0u8); /*---- * Mask out the unwanted bits of the last remaining byte. * * ((1 << 0) - 1) = 00000000 * ((1 << 1) - 1) = 00000001 * ... * ((1 << 6) - 1) = 00111111 * ((1 << 7) - 1) = 01111111 *---- */ map[*trunc_byte] &= (1 << *trunc_offs) - 1; } NeonWalRecord::ClearVisibilityMapFlags { new_heap_blkno, old_heap_blkno, flags, } => { // sanity check that this is modifying the correct relation let (rel, blknum) = key.to_rel_block().context("invalid record")?; assert!( rel.forknum == VISIBILITYMAP_FORKNUM, "ClearVisibilityMapFlags record on unexpected rel {rel}" ); if let Some(heap_blkno) = *new_heap_blkno { // Calculate the VM block and offset that corresponds to the heap block. let map_block = pg_constants::HEAPBLK_TO_MAPBLOCK(heap_blkno); let map_byte = pg_constants::HEAPBLK_TO_MAPBYTE(heap_blkno); let map_offset = pg_constants::HEAPBLK_TO_OFFSET(heap_blkno); // Check that we're modifying the correct VM block. assert!(map_block == blknum); // equivalent to PageGetContents(page) let map = &mut page[pg_constants::MAXALIGN_SIZE_OF_PAGE_HEADER_DATA..]; map[map_byte as usize] &= !(flags << map_offset); // The page should never be empty, but we're checking it anyway as a precaution, so that if it is empty for some reason anyway, we don't make matters worse by setting the LSN on it. if !postgres_ffi::page_is_new(page) { postgres_ffi::page_set_lsn(page, lsn); } } // Repeat for 'old_heap_blkno', if any if let Some(heap_blkno) = *old_heap_blkno { let map_block = pg_constants::HEAPBLK_TO_MAPBLOCK(heap_blkno); let map_byte = pg_constants::HEAPBLK_TO_MAPBYTE(heap_blkno); let map_offset = pg_constants::HEAPBLK_TO_OFFSET(heap_blkno); assert!(map_block == blknum); let map = &mut page[pg_constants::MAXALIGN_SIZE_OF_PAGE_HEADER_DATA..]; map[map_byte as usize] &= !(flags << map_offset); // The page should never be empty, but we're checking it anyway as a precaution, so that if it is empty for some reason anyway, we don't make matters worse by setting the LSN on it. if !postgres_ffi::page_is_new(page) { postgres_ffi::page_set_lsn(page, lsn); } } } // Non-relational WAL records are handled here, with custom code that has the // same effects as the corresponding Postgres WAL redo function. NeonWalRecord::ClogSetCommitted { xids, timestamp } => { let (slru_kind, segno, blknum) = key.to_slru_block().context("invalid record")?; assert_eq!( slru_kind, SlruKind::Clog, "ClogSetCommitted record with unexpected key {key}" ); for &xid in xids { let pageno = xid / pg_constants::CLOG_XACTS_PER_PAGE; let expected_segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT; let expected_blknum = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT; // Check that we're modifying the correct CLOG block. assert!( segno == expected_segno, "ClogSetCommitted record for XID {xid} with unexpected key {key}" ); assert!( blknum == expected_blknum, "ClogSetCommitted record for XID {xid} with unexpected key {key}" ); transaction_id_set_status(xid, pg_constants::TRANSACTION_STATUS_COMMITTED, page); } // Append the timestamp if page.len() == BLCKSZ as usize + 8 { page.truncate(BLCKSZ as usize); } if page.len() == BLCKSZ as usize { page.extend_from_slice(&timestamp.to_be_bytes()); } else { warn!( "CLOG blk {} in seg {} has invalid size {}", blknum, segno, page.len() ); } } NeonWalRecord::ClogSetAborted { xids } => { let (slru_kind, segno, blknum) = key.to_slru_block().context("invalid record")?; assert_eq!( slru_kind, SlruKind::Clog, "ClogSetAborted record with unexpected key {key}" ); for &xid in xids { let pageno = xid / pg_constants::CLOG_XACTS_PER_PAGE; let expected_segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT; let expected_blknum = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT; // Check that we're modifying the correct CLOG block. assert!( segno == expected_segno, "ClogSetAborted record for XID {xid} with unexpected key {key}" ); assert!( blknum == expected_blknum, "ClogSetAborted record for XID {xid} with unexpected key {key}" ); transaction_id_set_status(xid, pg_constants::TRANSACTION_STATUS_ABORTED, page); } } NeonWalRecord::MultixactOffsetCreate { mid, moff } => { let (slru_kind, segno, blknum) = key.to_slru_block().context("invalid record")?; assert_eq!( slru_kind, SlruKind::MultiXactOffsets, "MultixactOffsetCreate record with unexpected key {key}" ); // Compute the block and offset to modify. // See RecordNewMultiXact in PostgreSQL sources. let pageno = mid / pg_constants::MULTIXACT_OFFSETS_PER_PAGE as u32; let entryno = mid % pg_constants::MULTIXACT_OFFSETS_PER_PAGE as u32; let offset = (entryno * 4) as usize; // Check that we're modifying the correct multixact-offsets block. let expected_segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT; let expected_blknum = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT; assert!( segno == expected_segno, "MultiXactOffsetsCreate record for multi-xid {mid} with unexpected key {key}" ); assert!( blknum == expected_blknum, "MultiXactOffsetsCreate record for multi-xid {mid} with unexpected key {key}" ); LittleEndian::write_u32(&mut page[offset..offset + 4], *moff); } NeonWalRecord::MultixactMembersCreate { moff, members } => { let (slru_kind, segno, blknum) = key.to_slru_block().context("invalid record")?; assert_eq!( slru_kind, SlruKind::MultiXactMembers, "MultixactMembersCreate record with unexpected key {key}" ); for (i, member) in members.iter().enumerate() { let offset = moff + i as u32; // Compute the block and offset to modify. // See RecordNewMultiXact in PostgreSQL sources. let pageno = offset / pg_constants::MULTIXACT_MEMBERS_PER_PAGE as u32; let memberoff = mx_offset_to_member_offset(offset); let flagsoff = mx_offset_to_flags_offset(offset); let bshift = mx_offset_to_flags_bitshift(offset); // Check that we're modifying the correct multixact-members block. let expected_segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT; let expected_blknum = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT; assert!( segno == expected_segno, "MultiXactMembersCreate record for offset {moff} with unexpected key {key}" ); assert!( blknum == expected_blknum, "MultiXactMembersCreate record for offset {moff} with unexpected key {key}" ); let mut flagsval = LittleEndian::read_u32(&page[flagsoff..flagsoff + 4]); flagsval &= !(((1 << pg_constants::MXACT_MEMBER_BITS_PER_XACT) - 1) << bshift); flagsval |= member.status << bshift; LittleEndian::write_u32(&mut page[flagsoff..flagsoff + 4], flagsval); LittleEndian::write_u32(&mut page[memberoff..memberoff + 4], member.xid); } } NeonWalRecord::AuxFile { .. } => { // No-op: this record will never be created in aux v2. warn!("AuxFile record should not be created in aux v2"); } #[cfg(feature = "testing")] NeonWalRecord::Test { append, clear, will_init, only_if, } => { use bytes::BufMut; if *will_init { assert!(*clear, "init record must be clear to ensure correctness"); assert!( page.is_empty(), "init record must be the first entry to ensure correctness" ); } if *clear { page.clear(); } if let Some(only_if) = only_if { if page != only_if.as_bytes() { return Err(anyhow::anyhow!( "the current image does not match the expected image, cannot append" )); } } page.put_slice(append.as_bytes()); } } Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/walredo/process/no_leak_child.rs
pageserver/src/walredo/process/no_leak_child.rs
use std::io; use std::ops::{Deref, DerefMut}; use std::process::{Child, Command}; use pageserver_api::shard::TenantShardId; use tracing::{error, info, instrument}; use crate::metrics::{WAL_REDO_PROCESS_COUNTERS, WalRedoKillCause}; /// Wrapper type around `std::process::Child` which guarantees that the child /// will be killed and waited-for by this process before being dropped. pub(crate) struct NoLeakChild { pub(crate) tenant_id: TenantShardId, pub(crate) child: Option<Child>, } impl Deref for NoLeakChild { type Target = Child; fn deref(&self) -> &Self::Target { self.child.as_ref().expect("must not use from drop") } } impl DerefMut for NoLeakChild { fn deref_mut(&mut self) -> &mut Self::Target { self.child.as_mut().expect("must not use from drop") } } impl NoLeakChild { pub(crate) fn spawn(tenant_id: TenantShardId, command: &mut Command) -> io::Result<Self> { let child = command.spawn()?; Ok(NoLeakChild { tenant_id, child: Some(child), }) } pub(crate) fn kill_and_wait(mut self, cause: WalRedoKillCause) { let child = match self.child.take() { Some(child) => child, None => return, }; Self::kill_and_wait_impl(child, cause); } #[instrument(skip_all, fields(pid=child.id(), ?cause))] pub(crate) fn kill_and_wait_impl(mut child: Child, cause: WalRedoKillCause) { scopeguard::defer! { WAL_REDO_PROCESS_COUNTERS.killed_by_cause[cause].inc(); } let res = child.kill(); if let Err(e) = res { // This branch is very unlikely because: // - We (= pageserver) spawned this process successfully, so, we're allowed to kill it. // - This is the only place that calls .kill() // - We consume `self`, so, .kill() can't be called twice. // - If the process exited by itself or was killed by someone else, // .kill() will still succeed because we haven't wait()'ed yet. // // So, if we arrive here, we have really no idea what happened, // whether the PID stored in self.child is still valid, etc. // If this function were fallible, we'd return an error, but // since it isn't, all we can do is log an error and proceed // with the wait(). error!(error = %e, "failed to SIGKILL; subsequent wait() might fail or wait for wrong process"); } match child.wait() { Ok(exit_status) => { info!(exit_status = %exit_status, "wait successful"); } Err(e) => { error!(error = %e, "wait error; might leak the child process; it will show as zombie (defunct)"); } } } } impl Drop for NoLeakChild { fn drop(&mut self) { let child = match self.child.take() { Some(child) => child, None => return, }; let tenant_shard_id = self.tenant_id; // Offload the kill+wait of the child process into the background. // If someone stops the runtime, we'll leak the child process. // We can ignore that case because we only stop the runtime on pageserver exit. tokio::runtime::Handle::current().spawn(async move { tokio::task::spawn_blocking(move || { // Intentionally don't inherit the tracing context from whoever is dropping us. // This thread here is going to outlive of our dropper. let span = tracing::info_span!( "walredo", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug() ); let _entered = span.enter(); Self::kill_and_wait_impl(child, WalRedoKillCause::NoLeakChildDrop); }) .await }); } } pub(crate) trait NoLeakChildCommandExt { fn spawn_no_leak_child(&mut self, tenant_id: TenantShardId) -> io::Result<NoLeakChild>; } impl NoLeakChildCommandExt for Command { fn spawn_no_leak_child(&mut self, tenant_id: TenantShardId) -> io::Result<NoLeakChild> { NoLeakChild::spawn(tenant_id, self) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/walredo/process/protocol.rs
pageserver/src/walredo/process/protocol.rs
use bytes::BufMut; use pageserver_api::reltag::RelTag; use serde::Serialize; use utils::bin_ser::BeSer; use utils::lsn::Lsn; /// /// `RelTag` + block number (`blknum`) gives us a unique id of the page in the cluster. /// /// In Postgres `BufferTag` structure is used for exactly the same purpose. /// [See more related comments here](https://github.com/postgres/postgres/blob/99c5852e20a0987eca1c38ba0c09329d4076b6a0/src/include/storage/buf_internals.h#L91). /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Serialize)] pub(crate) struct BufferTag { pub rel: RelTag, pub blknum: u32, } pub(crate) fn build_begin_redo_for_block_msg(tag: BufferTag, buf: &mut Vec<u8>) { let len = 4 + 1 + 4 * 4; buf.put_u8(b'B'); buf.put_u32(len as u32); tag.ser_into(buf) .expect("serialize BufferTag should always succeed"); } pub(crate) fn build_push_page_msg(tag: BufferTag, base_img: &[u8], buf: &mut Vec<u8>) { assert!(base_img.len() == 8192); let len = 4 + 1 + 4 * 4 + base_img.len(); buf.put_u8(b'P'); buf.put_u32(len as u32); tag.ser_into(buf) .expect("serialize BufferTag should always succeed"); buf.put(base_img); } pub(crate) fn build_apply_record_msg(endlsn: Lsn, rec: &[u8], buf: &mut Vec<u8>) { let len = 4 + 8 + rec.len(); buf.put_u8(b'A'); buf.put_u32(len as u32); buf.put_u64(endlsn.0); buf.put(rec); } pub(crate) fn build_get_page_msg(tag: BufferTag, buf: &mut Vec<u8>) { let len = 4 + 1 + 4 * 4; buf.put_u8(b'G'); buf.put_u32(len as u32); tag.ser_into(buf) .expect("serialize BufferTag should always succeed"); } pub(crate) fn build_ping_msg(buf: &mut Vec<u8>) { buf.put_u8(b'H'); buf.put_u32(4); }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/http/mod.rs
pageserver/src/http/mod.rs
pub mod routes; pub use routes::make_router;
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/src/http/routes.rs
pageserver/src/http/routes.rs
//! //! Management HTTP API //! use std::cmp::Reverse; use std::collections::BTreeMap; use std::collections::BinaryHeap; use std::collections::HashMap; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result, anyhow}; use bytes::Bytes; use enumset::EnumSet; use futures::future::join_all; use futures::{StreamExt, TryFutureExt}; use http_utils::endpoint::{ self, attach_openapi_ui, auth_middleware, check_permission_with, profile_cpu_handler, profile_heap_handler, prometheus_metrics_handler, request_span, }; use http_utils::error::{ApiError, HttpErrorBody}; use http_utils::failpoints::failpoints_handler; use http_utils::json::{json_request, json_request_maybe, json_response}; use http_utils::request::{ get_request_param, must_get_query_param, must_parse_query_param, parse_query_param, parse_request_param, }; use http_utils::{RequestExt, RouterBuilder}; use humantime::format_rfc3339; use hyper::{Body, Request, Response, StatusCode, Uri, header}; use metrics::launch_timestamp::LaunchTimestamp; use pageserver_api::models::virtual_file::IoMode; use pageserver_api::models::{ DetachBehavior, DownloadRemoteLayersTaskSpawnRequest, IngestAuxFilesRequest, ListAuxFilesRequest, LocationConfig, LocationConfigListResponse, LocationConfigMode, LsnLease, LsnLeaseRequest, OffloadedTimelineInfo, PageTraceEvent, ShardParameters, StatusResponse, TenantConfigPatchRequest, TenantConfigRequest, TenantDetails, TenantInfo, TenantLocationConfigRequest, TenantLocationConfigResponse, TenantScanRemoteStorageResponse, TenantScanRemoteStorageShard, TenantShardLocation, TenantShardSplitRequest, TenantShardSplitResponse, TenantSorting, TenantState, TenantWaitLsnRequest, TimelineArchivalConfigRequest, TimelineCreateRequest, TimelineCreateRequestMode, TimelineCreateRequestModeImportPgdata, TimelineGcRequest, TimelineInfo, TimelinePatchIndexPartRequest, TimelineVisibilityState, TimelinesInfoAndOffloaded, TopTenantShardItem, TopTenantShardsRequest, TopTenantShardsResponse, }; use pageserver_api::shard::{ShardCount, TenantShardId}; use postgres_ffi::PgMajorVersion; use remote_storage::{DownloadError, GenericRemoteStorage, TimeTravelError}; use scopeguard::defer; use serde::{Deserialize, Serialize}; use serde_json::json; use tenant_size_model::svg::SvgBranchKind; use tenant_size_model::{SizeResult, StorageModel}; use tokio::time::Instant; use tokio_util::io::StreamReader; use tokio_util::sync::CancellationToken; use tracing::*; use utils::auth::SwappableJwtAuth; use utils::generation::Generation; use utils::id::{TenantId, TimelineId}; use utils::lsn::Lsn; use wal_decoder::models::record::NeonWalRecord; use crate::config::PageServerConf; use crate::context; use crate::context::{DownloadBehavior, RequestContext, RequestContextBuilder}; use crate::deletion_queue::DeletionQueueClient; use crate::feature_resolver::FeatureResolver; use crate::metrics::LOCAL_DATA_LOSS_SUSPECTED; use crate::pgdatadir_mapping::LsnForTimestamp; use crate::task_mgr::TaskKind; use crate::tenant::config::LocationConf; use crate::tenant::mgr::{ GetActiveTenantError, GetTenantError, TenantManager, TenantMapError, TenantMapInsertError, TenantSlot, TenantSlotError, TenantSlotUpsertError, TenantStateError, UpsertLocationError, }; use crate::tenant::remote_timeline_client::index::GcCompactionState; use crate::tenant::remote_timeline_client::{ download_index_part, download_tenant_manifest, list_remote_tenant_shards, list_remote_timelines, }; use crate::tenant::secondary::SecondaryController; use crate::tenant::size::ModelInputs; use crate::tenant::storage_layer::ValuesReconstructState; use crate::tenant::storage_layer::{IoConcurrency, LayerAccessStatsReset, LayerName}; use crate::tenant::timeline::layer_manager::LayerManagerLockHolder; use crate::tenant::timeline::offload::{OffloadError, offload_timeline}; use crate::tenant::timeline::{ CompactFlags, CompactOptions, CompactRequest, MarkInvisibleRequest, Timeline, WaitLsnTimeout, WaitLsnWaiter, import_pgdata, }; use crate::tenant::{ GetTimelineError, LogicalSizeCalculationCause, OffloadedTimeline, PageReconstructError, remote_timeline_client, }; use crate::{DEFAULT_PG_VERSION, disk_usage_eviction_task, tenant}; // For APIs that require an Active tenant, how long should we block waiting for that state? // This is not functionally necessary (clients will retry), but avoids generating a lot of // failed API calls while tenants are activating. #[cfg(not(feature = "testing"))] pub(crate) const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(5000); // Tests run on slow/oversubscribed nodes, and may need to wait much longer for tenants to // finish attaching, if calls to remote storage are slow. #[cfg(feature = "testing")] pub(crate) const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(30000); pub struct State { conf: &'static PageServerConf, tenant_manager: Arc<TenantManager>, auth: Option<Arc<SwappableJwtAuth>>, allowlist_routes: &'static [&'static str], remote_storage: GenericRemoteStorage, broker_client: storage_broker::BrokerClientChannel, disk_usage_eviction_state: Arc<disk_usage_eviction_task::State>, deletion_queue_client: DeletionQueueClient, secondary_controller: SecondaryController, latest_utilization: tokio::sync::Mutex<Option<(std::time::Instant, bytes::Bytes)>>, feature_resolver: FeatureResolver, } impl State { #[allow(clippy::too_many_arguments)] pub fn new( conf: &'static PageServerConf, tenant_manager: Arc<TenantManager>, auth: Option<Arc<SwappableJwtAuth>>, remote_storage: GenericRemoteStorage, broker_client: storage_broker::BrokerClientChannel, disk_usage_eviction_state: Arc<disk_usage_eviction_task::State>, deletion_queue_client: DeletionQueueClient, secondary_controller: SecondaryController, feature_resolver: FeatureResolver, ) -> anyhow::Result<Self> { let allowlist_routes = &[ "/v1/status", "/v1/doc", "/swagger.yml", "/metrics", "/profile/cpu", "/profile/heap", ]; Ok(Self { conf, tenant_manager, auth, allowlist_routes, remote_storage, broker_client, disk_usage_eviction_state, deletion_queue_client, secondary_controller, latest_utilization: Default::default(), feature_resolver, }) } } #[inline(always)] fn get_state(request: &Request<Body>) -> &State { request .data::<Arc<State>>() .expect("unknown state type") .as_ref() } #[inline(always)] fn get_config(request: &Request<Body>) -> &'static PageServerConf { get_state(request).conf } /// Check that the requester is authorized to operate on given tenant fn check_permission(request: &Request<Body>, tenant_id: Option<TenantId>) -> Result<(), ApiError> { check_permission_with(request, |claims| { crate::auth::check_permission(claims, tenant_id) }) } impl From<PageReconstructError> for ApiError { fn from(pre: PageReconstructError) -> ApiError { match pre { PageReconstructError::Other(other) => ApiError::InternalServerError(other), PageReconstructError::MissingKey(e) => ApiError::InternalServerError(e.into()), PageReconstructError::Cancelled => ApiError::Cancelled, PageReconstructError::AncestorLsnTimeout(e) => ApiError::Timeout(format!("{e}").into()), PageReconstructError::WalRedo(pre) => ApiError::InternalServerError(pre), } } } impl From<TenantMapInsertError> for ApiError { fn from(tmie: TenantMapInsertError) -> ApiError { match tmie { TenantMapInsertError::SlotError(e) => e.into(), TenantMapInsertError::SlotUpsertError(e) => e.into(), TenantMapInsertError::Other(e) => ApiError::InternalServerError(e), } } } impl From<TenantSlotError> for ApiError { fn from(e: TenantSlotError) -> ApiError { use TenantSlotError::*; match e { NotFound(tenant_id) => { ApiError::NotFound(anyhow::anyhow!("NotFound: tenant {tenant_id}").into()) } InProgress => { ApiError::ResourceUnavailable("Tenant is being modified concurrently".into()) } MapState(e) => e.into(), } } } impl From<TenantSlotUpsertError> for ApiError { fn from(e: TenantSlotUpsertError) -> ApiError { use TenantSlotUpsertError::*; match e { InternalError(e) => ApiError::InternalServerError(anyhow::anyhow!("{e}")), MapState(e) => e.into(), ShuttingDown(_) => ApiError::ShuttingDown, } } } impl From<UpsertLocationError> for ApiError { fn from(e: UpsertLocationError) -> ApiError { use UpsertLocationError::*; match e { BadRequest(e) => ApiError::BadRequest(e), Unavailable(_) => ApiError::ShuttingDown, e @ InProgress => ApiError::Conflict(format!("{e}")), Flush(e) | InternalError(e) => ApiError::InternalServerError(e), } } } impl From<TenantMapError> for ApiError { fn from(e: TenantMapError) -> ApiError { use TenantMapError::*; match e { StillInitializing | ShuttingDown => { ApiError::ResourceUnavailable(format!("{e}").into()) } } } } impl From<TenantStateError> for ApiError { fn from(tse: TenantStateError) -> ApiError { match tse { TenantStateError::IsStopping(_) => { ApiError::ResourceUnavailable("Tenant is stopping".into()) } TenantStateError::SlotError(e) => e.into(), TenantStateError::SlotUpsertError(e) => e.into(), TenantStateError::Other(e) => ApiError::InternalServerError(anyhow!(e)), } } } impl From<GetTenantError> for ApiError { fn from(tse: GetTenantError) -> ApiError { match tse { GetTenantError::NotFound(tid) => ApiError::NotFound(anyhow!("tenant {tid}").into()), GetTenantError::ShardNotFound(tid) => { ApiError::NotFound(anyhow!("tenant {tid}").into()) } GetTenantError::NotActive(_) => { // Why is this not `ApiError::NotFound`? // Because we must be careful to never return 404 for a tenant if it does // in fact exist locally. If we did, the caller could draw the conclusion // that it can attach the tenant to another PS and we'd be in split-brain. ApiError::ResourceUnavailable("Tenant not yet active".into()) } GetTenantError::MapState(e) => ApiError::ResourceUnavailable(format!("{e}").into()), } } } impl From<GetTimelineError> for ApiError { fn from(gte: GetTimelineError) -> Self { // Rationale: tenant is activated only after eligble timelines activate ApiError::NotFound(gte.into()) } } impl From<GetActiveTenantError> for ApiError { fn from(e: GetActiveTenantError) -> ApiError { match e { GetActiveTenantError::Broken(reason) => { ApiError::InternalServerError(anyhow!("tenant is broken: {}", reason)) } GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => { ApiError::ShuttingDown } GetActiveTenantError::WillNotBecomeActive(_) => ApiError::Conflict(format!("{e}")), GetActiveTenantError::Cancelled => ApiError::ShuttingDown, GetActiveTenantError::NotFound(gte) => gte.into(), GetActiveTenantError::WaitForActiveTimeout { .. } => { ApiError::ResourceUnavailable(format!("{e}").into()) } GetActiveTenantError::SwitchedTenant => { // in our HTTP handlers, this error doesn't happen // TODO: separate error types ApiError::ResourceUnavailable("switched tenant".into()) } } } } impl From<crate::tenant::DeleteTimelineError> for ApiError { fn from(value: crate::tenant::DeleteTimelineError) -> Self { use crate::tenant::DeleteTimelineError::*; match value { NotFound => ApiError::NotFound(anyhow::anyhow!("timeline not found").into()), HasChildren(children) => ApiError::PreconditionFailed( format!("Cannot delete timeline which has child timelines: {children:?}") .into_boxed_str(), ), a @ AlreadyInProgress(_) => ApiError::Conflict(a.to_string()), Cancelled => ApiError::ResourceUnavailable("shutting down".into()), Other(e) => ApiError::InternalServerError(e), } } } impl From<crate::tenant::TimelineArchivalError> for ApiError { fn from(value: crate::tenant::TimelineArchivalError) -> Self { use crate::tenant::TimelineArchivalError::*; match value { NotFound => ApiError::NotFound(anyhow::anyhow!("timeline not found").into()), Timeout => ApiError::Timeout("hit pageserver internal timeout".into()), Cancelled => ApiError::ShuttingDown, e @ HasArchivedParent(_) => { ApiError::PreconditionFailed(e.to_string().into_boxed_str()) } HasUnarchivedChildren(children) => ApiError::PreconditionFailed( format!( "Cannot archive timeline which has non-archived child timelines: {children:?}" ) .into_boxed_str(), ), a @ AlreadyInProgress => ApiError::Conflict(a.to_string()), Other(e) => ApiError::InternalServerError(e), } } } impl From<crate::tenant::mgr::DeleteTimelineError> for ApiError { fn from(value: crate::tenant::mgr::DeleteTimelineError) -> Self { use crate::tenant::mgr::DeleteTimelineError::*; match value { // Report Precondition failed so client can distinguish between // "tenant is missing" case from "timeline is missing" Tenant(GetTenantError::NotFound(..)) => ApiError::PreconditionFailed( "Requested tenant is missing".to_owned().into_boxed_str(), ), Tenant(t) => ApiError::from(t), Timeline(t) => ApiError::from(t), } } } impl From<crate::tenant::mgr::DeleteTenantError> for ApiError { fn from(value: crate::tenant::mgr::DeleteTenantError) -> Self { use crate::tenant::mgr::DeleteTenantError::*; match value { SlotError(e) => e.into(), Other(o) => ApiError::InternalServerError(o), Cancelled => ApiError::ShuttingDown, } } } impl From<crate::tenant::secondary::SecondaryTenantError> for ApiError { fn from(ste: crate::tenant::secondary::SecondaryTenantError) -> ApiError { use crate::tenant::secondary::SecondaryTenantError; match ste { SecondaryTenantError::GetTenant(gte) => gte.into(), SecondaryTenantError::ShuttingDown => ApiError::ShuttingDown, } } } impl From<crate::tenant::FinalizeTimelineImportError> for ApiError { fn from(err: crate::tenant::FinalizeTimelineImportError) -> ApiError { use crate::tenant::FinalizeTimelineImportError::*; match err { ImportTaskStillRunning => { ApiError::ResourceUnavailable("Import task still running".into()) } ShuttingDown => ApiError::ShuttingDown, } } } // Helper function to construct a TimelineInfo struct for a timeline async fn build_timeline_info( timeline: &Arc<Timeline>, include_non_incremental_logical_size: bool, force_await_initial_logical_size: bool, include_image_consistent_lsn: bool, ctx: &RequestContext, ) -> anyhow::Result<TimelineInfo> { crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id(); if force_await_initial_logical_size { timeline.clone().await_initial_logical_size().await } let mut info = build_timeline_info_common( timeline, ctx, tenant::timeline::GetLogicalSizePriority::Background, ) .await?; if include_non_incremental_logical_size { // XXX we should be using spawn_ondemand_logical_size_calculation here. // Otherwise, if someone deletes the timeline / detaches the tenant while // we're executing this function, we will outlive the timeline on-disk state. info.current_logical_size_non_incremental = Some( timeline .get_current_logical_size_non_incremental(info.last_record_lsn, ctx) .await?, ); } // HADRON if include_image_consistent_lsn { info.image_consistent_lsn = Some(timeline.compute_image_consistent_lsn().await?); } Ok(info) } async fn build_timeline_info_common( timeline: &Arc<Timeline>, ctx: &RequestContext, logical_size_task_priority: tenant::timeline::GetLogicalSizePriority, ) -> anyhow::Result<TimelineInfo> { crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id(); let initdb_lsn = timeline.initdb_lsn; let last_record_lsn = timeline.get_last_record_lsn(); let (wal_source_connstr, last_received_msg_lsn, last_received_msg_ts) = { let guard = timeline.last_received_wal.lock().unwrap(); if let Some(info) = guard.as_ref() { ( Some(format!("{}", info.wal_source_connconf)), // Password is hidden, but it's for statistics only. Some(info.last_received_msg_lsn), Some(info.last_received_msg_ts), ) } else { (None, None, None) } }; let ancestor_timeline_id = timeline.get_ancestor_timeline_id(); let ancestor_lsn = match timeline.get_ancestor_lsn() { Lsn(0) => None, lsn @ Lsn(_) => Some(lsn), }; let current_logical_size = timeline.get_current_logical_size(logical_size_task_priority, ctx); let current_physical_size = Some(timeline.layer_size_sum().await); let state = timeline.current_state(); // Report is_archived = false if the timeline is still loading let is_archived = timeline.is_archived().unwrap_or(false); let remote_consistent_lsn_projected = timeline .get_remote_consistent_lsn_projected() .unwrap_or(Lsn(0)); let remote_consistent_lsn_visible = timeline .get_remote_consistent_lsn_visible() .unwrap_or(Lsn(0)); let is_invisible = timeline.remote_client.is_invisible().unwrap_or(false); let walreceiver_status = timeline.walreceiver_status(); let (pitr_history_size, within_ancestor_pitr) = timeline.get_pitr_history_stats(); // Externally, expose the lowest LSN that can be used to create a branch. // Internally we distinguish between the planned GC cutoff (PITR point) and the "applied" GC cutoff (where we // actually trimmed data to), which can pass each other when PITR is changed. let min_readable_lsn = std::cmp::max( timeline.get_gc_cutoff_lsn().unwrap_or_default(), *timeline.get_applied_gc_cutoff_lsn(), ); let (rel_size_migration, rel_size_migrated_at) = timeline.get_rel_size_v2_status(); let info = TimelineInfo { tenant_id: timeline.tenant_shard_id, timeline_id: timeline.timeline_id, ancestor_timeline_id, ancestor_lsn, disk_consistent_lsn: timeline.get_disk_consistent_lsn(), remote_consistent_lsn: remote_consistent_lsn_projected, remote_consistent_lsn_visible, initdb_lsn, last_record_lsn, prev_record_lsn: Some(timeline.get_prev_record_lsn()), min_readable_lsn, applied_gc_cutoff_lsn: *timeline.get_applied_gc_cutoff_lsn(), current_logical_size: current_logical_size.size_dont_care_about_accuracy(), current_logical_size_is_accurate: match current_logical_size.accuracy() { tenant::timeline::logical_size::Accuracy::Approximate => false, tenant::timeline::logical_size::Accuracy::Exact => true, }, directory_entries_counts: timeline.get_directory_metrics().to_vec(), current_physical_size, current_logical_size_non_incremental: None, pitr_history_size, within_ancestor_pitr, timeline_dir_layer_file_size_sum: None, wal_source_connstr, last_received_msg_lsn, last_received_msg_ts, pg_version: timeline.pg_version, state, is_archived: Some(is_archived), rel_size_migration: Some(rel_size_migration), rel_size_migrated_at, is_invisible: Some(is_invisible), walreceiver_status, // HADRON image_consistent_lsn: None, }; Ok(info) } fn build_timeline_offloaded_info(offloaded: &Arc<OffloadedTimeline>) -> OffloadedTimelineInfo { let &OffloadedTimeline { tenant_shard_id, timeline_id, ancestor_retain_lsn, ancestor_timeline_id, archived_at, .. } = offloaded.as_ref(); OffloadedTimelineInfo { tenant_id: tenant_shard_id, timeline_id, ancestor_retain_lsn, ancestor_timeline_id, archived_at: archived_at.and_utc(), } } // healthcheck handler async fn status_handler( request: Request<Body>, _cancel: CancellationToken, ) -> Result<Response<Body>, ApiError> { check_permission(&request, None)?; let config = get_config(&request); json_response(StatusCode::OK, StatusResponse { id: config.id }) } async fn reload_auth_validation_keys_handler( request: Request<Body>, _cancel: CancellationToken, ) -> Result<Response<Body>, ApiError> { check_permission(&request, None)?; let config = get_config(&request); let state = get_state(&request); let Some(shared_auth) = &state.auth else { return json_response(StatusCode::BAD_REQUEST, ()); }; // unwrap is ok because check is performed when creating config, so path is set and exists let key_path = config.auth_validation_public_key_path.as_ref().unwrap(); info!("Reloading public key(s) for verifying JWT tokens from {key_path:?}"); match utils::auth::JwtAuth::from_key_path(key_path) { Ok(new_auth) => { shared_auth.swap(new_auth); json_response(StatusCode::OK, ()) } Err(e) => { let err_msg = "Error reloading public keys"; warn!("Error reloading public keys from {key_path:?}: {e:}"); json_response( StatusCode::INTERNAL_SERVER_ERROR, HttpErrorBody::from_msg(err_msg.to_string()), ) } } } async fn timeline_create_handler( mut request: Request<Body>, _cancel: CancellationToken, ) -> Result<Response<Body>, ApiError> { let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?; let request_data: TimelineCreateRequest = json_request(&mut request).await?; check_permission(&request, Some(tenant_shard_id.tenant_id))?; let new_timeline_id = request_data.new_timeline_id; // fill in the default pg_version if not provided & convert request into domain model let params: tenant::CreateTimelineParams = match request_data.mode { TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, pg_version, } => tenant::CreateTimelineParams::Bootstrap(tenant::CreateTimelineParamsBootstrap { new_timeline_id, existing_initdb_timeline_id, pg_version: pg_version.unwrap_or(DEFAULT_PG_VERSION), }), TimelineCreateRequestMode::Branch { ancestor_timeline_id, ancestor_start_lsn, read_only: _, pg_version: _, } => tenant::CreateTimelineParams::Branch(tenant::CreateTimelineParamsBranch { new_timeline_id, ancestor_timeline_id, ancestor_start_lsn, }), TimelineCreateRequestMode::ImportPgdata { import_pgdata: TimelineCreateRequestModeImportPgdata { location, idempotency_key, }, } => tenant::CreateTimelineParams::ImportPgdata(tenant::CreateTimelineParamsImportPgdata { idempotency_key: import_pgdata::index_part_format::IdempotencyKey::new( idempotency_key.0, ), new_timeline_id, location: { use import_pgdata::index_part_format::Location; use pageserver_api::models::ImportPgdataLocation; match location { #[cfg(feature = "testing")] ImportPgdataLocation::LocalFs { path } => Location::LocalFs { path }, ImportPgdataLocation::AwsS3 { region, bucket, key, } => Location::AwsS3 { region, bucket, key, }, } }, }), }; let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Error); let state = get_state(&request); async { let tenant = state .tenant_manager .get_attached_tenant_shard(tenant_shard_id)?; tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?; // earlier versions of the code had pg_version and ancestor_lsn in the span // => continue to provide that information, but, through a log message that doesn't require us to destructure tracing::info!(?params, "creating timeline"); match tenant .create_timeline(params, state.broker_client.clone(), &ctx) .await { Ok(new_timeline) => { // Created. Construct a TimelineInfo for it. let timeline_info = build_timeline_info_common( &new_timeline, &ctx, tenant::timeline::GetLogicalSizePriority::User, ) .await .map_err(ApiError::InternalServerError)?; json_response(StatusCode::CREATED, timeline_info) } Err(_) if tenant.cancel.is_cancelled() => { // In case we get some ugly error type during shutdown, cast it into a clean 503. json_response( StatusCode::SERVICE_UNAVAILABLE, HttpErrorBody::from_msg("Tenant shutting down".to_string()), ) } Err(e @ tenant::CreateTimelineError::Conflict) => { json_response(StatusCode::CONFLICT, HttpErrorBody::from_msg(e.to_string())) } Err(e @ tenant::CreateTimelineError::AlreadyCreating) => json_response( StatusCode::TOO_MANY_REQUESTS, HttpErrorBody::from_msg(e.to_string()), ), Err(tenant::CreateTimelineError::AncestorLsn(err)) => json_response( StatusCode::NOT_ACCEPTABLE, HttpErrorBody::from_msg(format!("{err:#}")), ), Err(e @ tenant::CreateTimelineError::AncestorNotActive) => json_response( StatusCode::SERVICE_UNAVAILABLE, HttpErrorBody::from_msg(e.to_string()), ), Err(e @ tenant::CreateTimelineError::AncestorArchived) => json_response( StatusCode::NOT_ACCEPTABLE, HttpErrorBody::from_msg(e.to_string()), ), Err(tenant::CreateTimelineError::ShuttingDown) => json_response( StatusCode::SERVICE_UNAVAILABLE, HttpErrorBody::from_msg("tenant shutting down".to_string()), ), Err(tenant::CreateTimelineError::Other(err)) => Err(ApiError::InternalServerError(err)), } } .instrument(info_span!("timeline_create", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), timeline_id = %new_timeline_id, )) .await } async fn timeline_list_handler( request: Request<Body>, _cancel: CancellationToken, ) -> Result<Response<Body>, ApiError> { let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?; let include_non_incremental_logical_size: Option<bool> = parse_query_param(&request, "include-non-incremental-logical-size")?; let force_await_initial_logical_size: Option<bool> = parse_query_param(&request, "force-await-initial-logical-size")?; let include_image_consistent_lsn: Option<bool> = parse_query_param(&request, "include-image-consistent-lsn")?; check_permission(&request, Some(tenant_shard_id.tenant_id))?; let state = get_state(&request); let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download); let response_data = async { let tenant = state .tenant_manager .get_attached_tenant_shard(tenant_shard_id)?; tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?; let timelines = tenant.list_timelines(); let mut response_data = Vec::with_capacity(timelines.len()); for timeline in timelines { let timeline_info = build_timeline_info( &timeline, include_non_incremental_logical_size.unwrap_or(false), force_await_initial_logical_size.unwrap_or(false), include_image_consistent_lsn.unwrap_or(false), &ctx, ) .instrument(info_span!("build_timeline_info", timeline_id = %timeline.timeline_id)) .await .context("Failed to build timeline info") .map_err(ApiError::InternalServerError)?; response_data.push(timeline_info); } Ok::<Vec<TimelineInfo>, ApiError>(response_data) } .instrument(info_span!("timeline_list", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug())) .await?; json_response(StatusCode::OK, response_data) } async fn timeline_and_offloaded_list_handler( request: Request<Body>, _cancel: CancellationToken, ) -> Result<Response<Body>, ApiError> { let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?; let include_non_incremental_logical_size: Option<bool> = parse_query_param(&request, "include-non-incremental-logical-size")?; let force_await_initial_logical_size: Option<bool> = parse_query_param(&request, "force-await-initial-logical-size")?; let include_image_consistent_lsn: Option<bool> = parse_query_param(&request, "include-image-consistent-lsn")?; check_permission(&request, Some(tenant_shard_id.tenant_id))?; let state = get_state(&request); let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download); let response_data = async { let tenant = state .tenant_manager .get_attached_tenant_shard(tenant_shard_id)?; tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?; let (timelines, offloadeds) = tenant.list_timelines_and_offloaded(); let mut timeline_infos = Vec::with_capacity(timelines.len()); for timeline in timelines { let timeline_info = build_timeline_info( &timeline, include_non_incremental_logical_size.unwrap_or(false), force_await_initial_logical_size.unwrap_or(false), include_image_consistent_lsn.unwrap_or(false), &ctx, ) .instrument(info_span!("build_timeline_info", timeline_id = %timeline.timeline_id)) .await .context("Failed to build timeline info") .map_err(ApiError::InternalServerError)?; timeline_infos.push(timeline_info); } let offloaded_infos = offloadeds .into_iter() .map(|offloaded| build_timeline_offloaded_info(&offloaded)) .collect::<Vec<_>>(); let res = TimelinesInfoAndOffloaded { timelines: timeline_infos, offloaded: offloaded_infos, };
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/benches/bench_ingest.rs
pageserver/benches/bench_ingest.rs
use std::env; use std::num::NonZeroUsize; use std::sync::Arc; use bytes::Bytes; use camino::Utf8PathBuf; use criterion::{Criterion, criterion_group, criterion_main}; use futures::stream::FuturesUnordered; use pageserver::config::PageServerConf; use pageserver::context::{DownloadBehavior, RequestContext}; use pageserver::keyspace::KeySpace; use pageserver::l0_flush::{L0FlushConfig, L0FlushGlobalState}; use pageserver::task_mgr::TaskKind; use pageserver::tenant::storage_layer::IoConcurrency; use pageserver::tenant::storage_layer::{InMemoryLayer, ValuesReconstructState}; use pageserver::{page_cache, virtual_file}; use pageserver_api::config::GetVectoredConcurrentIo; use pageserver_api::key::Key; use pageserver_api::models::virtual_file::IoMode; use pageserver_api::shard::TenantShardId; use tokio_stream::StreamExt; use tokio_util::sync::CancellationToken; use utils::bin_ser::BeSer; use utils::id::{TenantId, TimelineId}; use utils::lsn::Lsn; use utils::sync::gate::Gate; use wal_decoder::models::value::Value; use wal_decoder::serialized_batch::SerializedValueBatch; // A very cheap hash for generating non-sequential keys. fn murmurhash32(mut h: u32) -> u32 { h ^= h >> 16; h = h.wrapping_mul(0x85ebca6b); h ^= h >> 13; h = h.wrapping_mul(0xc2b2ae35); h ^= h >> 16; h } #[derive(serde::Serialize, Clone, Copy, Debug, PartialEq)] enum KeyLayout { /// Sequential unique keys Sequential, /// Random unique keys Random, /// Random keys, but only use the bits from the mask of them RandomReuse(u32), } #[derive(serde::Serialize, Clone, Copy, Debug, PartialEq)] enum WriteDelta { Yes, No, } #[derive(serde::Serialize, Clone, Copy, Debug, PartialEq)] enum ConcurrentReads { Yes, No, } async fn ingest( conf: &'static PageServerConf, put_size: usize, put_count: usize, key_layout: KeyLayout, write_delta: WriteDelta, concurrent_reads: ConcurrentReads, ) -> anyhow::Result<()> { if concurrent_reads == ConcurrentReads::Yes { assert_eq!(key_layout, KeyLayout::Sequential); } let mut lsn = utils::lsn::Lsn(1000); let mut key = Key::from_i128(0x0); let timeline_id = TimelineId::generate(); let tenant_id = TenantId::generate(); let tenant_shard_id = TenantShardId::unsharded(tenant_id); tokio::fs::create_dir_all(conf.timeline_path(&tenant_shard_id, &timeline_id)).await?; let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error).with_scope_debug_tools(); let gate = utils::sync::gate::Gate::default(); let cancel = CancellationToken::new(); let layer = Arc::new( InMemoryLayer::create( conf, timeline_id, tenant_shard_id, lsn, &gate, &cancel, &ctx, ) .await?, ); let data = Value::Image(Bytes::from(vec![0u8; put_size])); let data_ser_size = data.serialized_size().unwrap() as usize; let ctx = RequestContext::new( pageserver::task_mgr::TaskKind::WalReceiverConnectionHandler, pageserver::context::DownloadBehavior::Download, ); const READ_BATCH_SIZE: u32 = 32; let (tx, mut rx) = tokio::sync::watch::channel::<Option<Key>>(None); let reader_cancel = CancellationToken::new(); let reader_handle = if concurrent_reads == ConcurrentReads::Yes { Some(tokio::task::spawn({ let cancel = reader_cancel.clone(); let layer = layer.clone(); let ctx = ctx.attached_child(); async move { let gate = Gate::default(); let gate_guard = gate.enter().unwrap(); let io_concurrency = IoConcurrency::spawn_from_conf( GetVectoredConcurrentIo::SidecarTask, gate_guard, ); rx.wait_for(|key| key.is_some()).await.unwrap(); while !cancel.is_cancelled() { let key = match *rx.borrow() { Some(some) => some, None => unreachable!(), }; let mut start_key = key; start_key.field6 = key.field6.saturating_sub(READ_BATCH_SIZE); let key_range = start_key..key.next(); let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone()); layer .get_values_reconstruct_data( KeySpace::single(key_range), Lsn(1)..Lsn(u64::MAX), &mut reconstruct_state, &ctx, ) .await .unwrap(); let mut collect_futs = std::mem::take(&mut reconstruct_state.keys) .into_values() .map(|state| state.sink_pending_ios()) .collect::<FuturesUnordered<_>>(); while collect_futs.next().await.is_some() {} } drop(io_concurrency); gate.close().await; } })) } else { None }; const BATCH_SIZE: usize = 16; let mut batch = Vec::new(); for i in 0..put_count { lsn += put_size as u64; // Generate lots of keys within a single relation, which simulates the typical bulk ingest case: people // usually care the most about write performance when they're blasting a huge batch of data into a huge table. match key_layout { KeyLayout::Sequential => { // Use sequential order to illustrate the experience a user is likely to have // when ingesting bulk data. key.field6 = i as u32; } KeyLayout::Random => { // Use random-order keys to avoid giving a false advantage to data structures that are // faster when inserting on the end. key.field6 = murmurhash32(i as u32); } KeyLayout::RandomReuse(mask) => { // Use low bits only, to limit cardinality key.field6 = murmurhash32(i as u32) & mask; } } batch.push((key.to_compact(), lsn, data_ser_size, data.clone())); if batch.len() >= BATCH_SIZE { let last_key = Key::from_compact(batch.last().unwrap().0); let this_batch = std::mem::take(&mut batch); let serialized = SerializedValueBatch::from_values(this_batch); layer.put_batch(serialized, &ctx).await?; tx.send(Some(last_key)).unwrap(); } } if !batch.is_empty() { let last_key = Key::from_compact(batch.last().unwrap().0); let this_batch = std::mem::take(&mut batch); let serialized = SerializedValueBatch::from_values(this_batch); layer.put_batch(serialized, &ctx).await?; tx.send(Some(last_key)).unwrap(); } layer.freeze(lsn + 1).await; if write_delta == WriteDelta::Yes { let l0_flush_state = L0FlushGlobalState::new(L0FlushConfig::Direct { max_concurrency: NonZeroUsize::new(1).unwrap(), }); let (_desc, path) = layer .write_to_disk(&ctx, None, l0_flush_state.inner(), &gate, cancel.clone()) .await? .unwrap(); tokio::fs::remove_file(path).await?; } reader_cancel.cancel(); if let Some(handle) = reader_handle { handle.await.unwrap(); } Ok(()) } /// Wrapper to instantiate a tokio runtime fn ingest_main( conf: &'static PageServerConf, io_mode: IoMode, put_size: usize, put_count: usize, key_layout: KeyLayout, write_delta: WriteDelta, concurrent_reads: ConcurrentReads, ) { pageserver::virtual_file::set_io_mode(io_mode); let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(); runtime.block_on(async move { let r = ingest( conf, put_size, put_count, key_layout, write_delta, concurrent_reads, ) .await; if let Err(e) = r { panic!("{e:?}"); } }); } /// Declare a series of benchmarks for the Pageserver's ingest write path. /// /// This benchmark does not include WAL decode: it starts at InMemoryLayer::put_value, and ends either /// at freezing the ephemeral layer, or writing the ephemeral layer out to an L0 (depending on whether WriteDelta is set). /// /// Genuine disk I/O is used, so expect results to differ depending on storage. However, when running on /// a fast disk, CPU is the bottleneck at time of writing. fn criterion_benchmark(c: &mut Criterion) { let temp_dir_parent: Utf8PathBuf = env::current_dir().unwrap().try_into().unwrap(); let temp_dir = camino_tempfile::tempdir_in(temp_dir_parent).unwrap(); eprintln!("Data directory: {}", temp_dir.path()); let conf: &'static PageServerConf = Box::leak(Box::new( pageserver::config::PageServerConf::dummy_conf(temp_dir.path().to_path_buf()), )); virtual_file::init( 16384, virtual_file::io_engine_for_bench(), // immaterial, each `ingest_main` invocation below overrides this conf.virtual_file_io_mode, // without actually doing syncs, buffered writes have an unfair advantage over direct IO writes virtual_file::SyncMode::Sync, ); page_cache::init(conf.page_cache_size); #[derive(serde::Serialize)] struct ExplodedParameters { io_mode: IoMode, volume_mib: usize, key_size: usize, key_layout: KeyLayout, write_delta: WriteDelta, concurrent_reads: ConcurrentReads, } #[derive(Clone)] struct HandPickedParameters { volume_mib: usize, key_size: usize, key_layout: KeyLayout, write_delta: WriteDelta, } let expect = vec![ // Small values (100b) tests HandPickedParameters { volume_mib: 128, key_size: 100, key_layout: KeyLayout::Sequential, write_delta: WriteDelta::Yes, }, HandPickedParameters { volume_mib: 128, key_size: 100, key_layout: KeyLayout::Random, write_delta: WriteDelta::Yes, }, HandPickedParameters { volume_mib: 128, key_size: 100, key_layout: KeyLayout::RandomReuse(0x3ff), write_delta: WriteDelta::Yes, }, HandPickedParameters { volume_mib: 128, key_size: 100, key_layout: KeyLayout::Sequential, write_delta: WriteDelta::No, }, // Large values (8k) tests HandPickedParameters { volume_mib: 128, key_size: 8192, key_layout: KeyLayout::Sequential, write_delta: WriteDelta::Yes, }, HandPickedParameters { volume_mib: 128, key_size: 8192, key_layout: KeyLayout::Sequential, write_delta: WriteDelta::No, }, ]; let exploded_parameters = { let mut out = Vec::new(); for concurrent_reads in [ConcurrentReads::Yes, ConcurrentReads::No] { for param in expect.clone() { let HandPickedParameters { volume_mib, key_size, key_layout, write_delta, } = param; if key_layout != KeyLayout::Sequential && concurrent_reads == ConcurrentReads::Yes { continue; } out.push(ExplodedParameters { io_mode: IoMode::DirectRw, volume_mib, key_size, key_layout, write_delta, concurrent_reads, }); } } out }; impl ExplodedParameters { fn benchmark_id(&self) -> String { let ExplodedParameters { io_mode, volume_mib, key_size, key_layout, write_delta, concurrent_reads, } = self; format!( "io_mode={io_mode:?} volume_mib={volume_mib:?} key_size_bytes={key_size:?} key_layout={key_layout:?} write_delta={write_delta:?} concurrent_reads={concurrent_reads:?}" ) } } let mut group = c.benchmark_group("ingest"); for params in exploded_parameters { let id = params.benchmark_id(); let ExplodedParameters { io_mode, volume_mib, key_size, key_layout, write_delta, concurrent_reads, } = params; let put_count = volume_mib * 1024 * 1024 / key_size; group.throughput(criterion::Throughput::Bytes((key_size * put_count) as u64)); group.sample_size(10); group.bench_function(id, |b| { b.iter(|| { ingest_main( conf, io_mode, key_size, put_count, key_layout, write_delta, concurrent_reads, ) }) }); } } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); /* cargo bench --bench bench_ingest im4gn.2xlarge: ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=Yes time: [1.2901 s 1.2943 s 1.2991 s] thrpt: [98.533 MiB/s 98.892 MiB/s 99.220 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=Random write_delta=Yes time: [2.1387 s 2.1623 s 2.1845 s] thrpt: [58.595 MiB/s 59.197 MiB/s 59.851 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=RandomReuse(1023) write_delta=Y... time: [1.2036 s 1.2074 s 1.2122 s] thrpt: [105.60 MiB/s 106.01 MiB/s 106.35 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=No time: [520.55 ms 521.46 ms 522.57 ms] thrpt: [244.94 MiB/s 245.47 MiB/s 245.89 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=Yes time: [440.33 ms 442.24 ms 444.10 ms] thrpt: [288.22 MiB/s 289.43 MiB/s 290.69 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=No time: [168.78 ms 169.42 ms 170.18 ms] thrpt: [752.16 MiB/s 755.52 MiB/s 758.40 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=Yes time: [1.2978 s 1.3094 s 1.3227 s] thrpt: [96.775 MiB/s 97.758 MiB/s 98.632 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=Random write_delta=Yes time: [2.1976 s 2.2067 s 2.2154 s] thrpt: [57.777 MiB/s 58.006 MiB/s 58.245 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=RandomReuse(1023) write_delta=Yes time: [1.2103 s 1.2160 s 1.2233 s] thrpt: [104.64 MiB/s 105.26 MiB/s 105.76 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=No time: [525.05 ms 526.37 ms 527.79 ms] thrpt: [242.52 MiB/s 243.17 MiB/s 243.79 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=Yes time: [443.06 ms 444.88 ms 447.15 ms] thrpt: [286.26 MiB/s 287.72 MiB/s 288.90 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=No time: [169.40 ms 169.80 ms 170.17 ms] thrpt: [752.21 MiB/s 753.81 MiB/s 755.60 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=Yes time: [1.2844 s 1.2915 s 1.2990 s] thrpt: [98.536 MiB/s 99.112 MiB/s 99.657 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=Random write_delta=Yes time: [2.1431 s 2.1663 s 2.1900 s] thrpt: [58.446 MiB/s 59.087 MiB/s 59.726 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=RandomReuse(1023) write_delta=Y... time: [1.1906 s 1.1926 s 1.1947 s] thrpt: [107.14 MiB/s 107.33 MiB/s 107.51 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=No time: [516.86 ms 518.25 ms 519.47 ms] thrpt: [246.40 MiB/s 246.98 MiB/s 247.65 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=Yes time: [536.50 ms 536.53 ms 536.60 ms] thrpt: [238.54 MiB/s 238.57 MiB/s 238.59 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=No time: [267.77 ms 267.90 ms 268.04 ms] thrpt: [477.53 MiB/s 477.79 MiB/s 478.02 MiB/s] Hetzner AX102: ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=Yes time: [836.58 ms 861.93 ms 886.57 ms] thrpt: [144.38 MiB/s 148.50 MiB/s 153.00 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=Random write_delta=Yes time: [1.2782 s 1.3191 s 1.3665 s] thrpt: [93.668 MiB/s 97.037 MiB/s 100.14 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=RandomReuse(1023) write_delta=Y... time: [791.27 ms 807.08 ms 822.95 ms] thrpt: [155.54 MiB/s 158.60 MiB/s 161.77 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=No time: [310.78 ms 314.66 ms 318.47 ms] thrpt: [401.92 MiB/s 406.79 MiB/s 411.87 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=Yes time: [377.11 ms 387.77 ms 399.21 ms] thrpt: [320.63 MiB/s 330.10 MiB/s 339.42 MiB/s] ingest/io_mode=Buffered volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=No time: [128.37 ms 132.96 ms 138.55 ms] thrpt: [923.83 MiB/s 962.69 MiB/s 997.11 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=Yes time: [900.38 ms 914.88 ms 928.86 ms] thrpt: [137.80 MiB/s 139.91 MiB/s 142.16 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=Random write_delta=Yes time: [1.2538 s 1.2936 s 1.3313 s] thrpt: [96.149 MiB/s 98.946 MiB/s 102.09 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=RandomReuse(1023) write_delta=Yes time: [787.17 ms 803.89 ms 820.63 ms] thrpt: [155.98 MiB/s 159.23 MiB/s 162.61 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=No time: [318.78 ms 321.89 ms 324.74 ms] thrpt: [394.16 MiB/s 397.65 MiB/s 401.53 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=Yes time: [374.01 ms 383.45 ms 393.20 ms] thrpt: [325.53 MiB/s 333.81 MiB/s 342.24 MiB/s] ingest/io_mode=Direct volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=No time: [137.98 ms 141.31 ms 143.57 ms] thrpt: [891.58 MiB/s 905.79 MiB/s 927.66 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=Yes time: [613.69 ms 622.48 ms 630.97 ms] thrpt: [202.86 MiB/s 205.63 MiB/s 208.57 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=Random write_delta=Yes time: [1.0299 s 1.0766 s 1.1273 s] thrpt: [113.55 MiB/s 118.90 MiB/s 124.29 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=RandomReuse(1023) write_delta=Y... time: [637.80 ms 647.78 ms 658.01 ms] thrpt: [194.53 MiB/s 197.60 MiB/s 200.69 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=100 key_layout=Sequential write_delta=No time: [266.09 ms 267.20 ms 268.31 ms] thrpt: [477.06 MiB/s 479.04 MiB/s 481.04 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=Yes time: [269.34 ms 273.27 ms 277.69 ms] thrpt: [460.95 MiB/s 468.40 MiB/s 475.24 MiB/s] ingest/io_mode=DirectRw volume_mib=128 key_size_bytes=8192 key_layout=Sequential write_delta=No time: [123.18 ms 124.24 ms 125.15 ms] thrpt: [1022.8 MiB/s 1.0061 GiB/s 1.0148 GiB/s] */
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/benches/bench_metrics.rs
pageserver/benches/bench_metrics.rs
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use utils::id::{TenantId, TimelineId}; // // Demonstrates that repeat label values lookup is a multicore scalability bottleneck // that is worth avoiding. // criterion_group!( label_values, label_values::bench_naive_usage, label_values::bench_cache_label_values_lookup ); mod label_values { use super::*; pub fn bench_naive_usage(c: &mut Criterion) { let mut g = c.benchmark_group("label_values__naive_usage"); for ntimelines in [1, 4, 8] { g.bench_with_input( BenchmarkId::new("ntimelines", ntimelines), &ntimelines, |b, ntimelines| { b.iter_custom(|iters| { let barrier = std::sync::Barrier::new(*ntimelines + 1); let timelines = (0..*ntimelines) .map(|_| { ( TenantId::generate().to_string(), "0000".to_string(), TimelineId::generate().to_string(), ) }) .collect::<Vec<_>>(); let metric_vec = metrics::UIntGaugeVec::new( metrics::opts!("testmetric", "testhelp"), &["tenant_id", "shard_id", "timeline_id"], ) .unwrap(); std::thread::scope(|s| { for (tenant_id, shard_id, timeline_id) in &timelines { s.spawn(|| { barrier.wait(); for _ in 0..iters { metric_vec .with_label_values(&[tenant_id, shard_id, timeline_id]) .inc(); } barrier.wait(); }); } barrier.wait(); let start = std::time::Instant::now(); barrier.wait(); start.elapsed() }) }) }, ); } g.finish(); } pub fn bench_cache_label_values_lookup(c: &mut Criterion) { let mut g = c.benchmark_group("label_values__cache_label_values_lookup"); for ntimelines in [1, 4, 8] { g.bench_with_input( BenchmarkId::new("ntimelines", ntimelines), &ntimelines, |b, ntimelines| { b.iter_custom(|iters| { let barrier = std::sync::Barrier::new(*ntimelines + 1); let timelines = (0..*ntimelines) .map(|_| { ( TenantId::generate().to_string(), "0000".to_string(), TimelineId::generate().to_string(), ) }) .collect::<Vec<_>>(); let metric_vec = metrics::UIntGaugeVec::new( metrics::opts!("testmetric", "testhelp"), &["tenant_id", "shard_id", "timeline_id"], ) .unwrap(); std::thread::scope(|s| { for (tenant_id, shard_id, timeline_id) in &timelines { s.spawn(|| { let metric = metric_vec.with_label_values(&[ tenant_id, shard_id, timeline_id, ]); barrier.wait(); for _ in 0..iters { metric.inc(); } barrier.wait(); }); } barrier.wait(); let start = std::time::Instant::now(); barrier.wait(); start.elapsed() }) }) }, ); } g.finish(); } } // // Demonstrates that even a single metric can be a scalability bottleneck // if multiple threads in it concurrently but there's nothing we can do // about it without changing the metrics framework to use e.g. sharded counte atomics. // criterion_group!( single_metric_multicore_scalability, single_metric_multicore_scalability::bench, ); mod single_metric_multicore_scalability { use super::*; pub fn bench(c: &mut Criterion) { let mut g = c.benchmark_group("single_metric_multicore_scalability"); for nthreads in [1, 4, 8] { g.bench_with_input( BenchmarkId::new("nthreads", nthreads), &nthreads, |b, nthreads| { b.iter_custom(|iters| { let barrier = std::sync::Barrier::new(*nthreads + 1); let metric = metrics::UIntGauge::new("testmetric", "testhelp").unwrap(); std::thread::scope(|s| { for _ in 0..*nthreads { s.spawn(|| { barrier.wait(); for _ in 0..iters { metric.inc(); } barrier.wait(); }); } barrier.wait(); let start = std::time::Instant::now(); barrier.wait(); start.elapsed() }) }) }, ); } g.finish(); } } // // Demonstrates that even if we cache label value, the propagation of such a cached metric value // by Clone'ing it is a scalability bottleneck. // The reason is that it's an Arc internally and thus there's contention on the reference count atomics. // // We can avoid that by having long-lived references per thread (= indirection). // criterion_group!( propagation_of_cached_label_value, propagation_of_cached_label_value::bench_naive, propagation_of_cached_label_value::bench_long_lived_reference_per_thread, ); mod propagation_of_cached_label_value { use std::sync::Arc; use super::*; pub fn bench_naive(c: &mut Criterion) { let mut g = c.benchmark_group("propagation_of_cached_label_value__naive"); for nthreads in [1, 4, 8] { g.bench_with_input( BenchmarkId::new("nthreads", nthreads), &nthreads, |b, nthreads| { b.iter_custom(|iters| { let barrier = std::sync::Barrier::new(*nthreads + 1); let metric = metrics::UIntGauge::new("testmetric", "testhelp").unwrap(); std::thread::scope(|s| { for _ in 0..*nthreads { s.spawn(|| { barrier.wait(); for _ in 0..iters { // propagating the metric means we'd clone it into the child RequestContext let propagated = metric.clone(); // simulate some work criterion::black_box(propagated); } barrier.wait(); }); } barrier.wait(); let start = std::time::Instant::now(); barrier.wait(); start.elapsed() }) }) }, ); } g.finish(); } pub fn bench_long_lived_reference_per_thread(c: &mut Criterion) { let mut g = c.benchmark_group("propagation_of_cached_label_value__long_lived_reference_per_thread"); for nthreads in [1, 4, 8] { g.bench_with_input( BenchmarkId::new("nthreads", nthreads), &nthreads, |b, nthreads| { b.iter_custom(|iters| { let barrier = std::sync::Barrier::new(*nthreads + 1); let metric = metrics::UIntGauge::new("testmetric", "testhelp").unwrap(); std::thread::scope(|s| { for _ in 0..*nthreads { s.spawn(|| { // This is the technique. let this_threads_metric_reference = Arc::new(metric.clone()); barrier.wait(); for _ in 0..iters { // propagating the metric means we'd clone it into the child RequestContext let propagated = Arc::clone(&this_threads_metric_reference); // simulate some work (include the pointer chase!) criterion::black_box(&*propagated); } barrier.wait(); }); } barrier.wait(); let start = std::time::Instant::now(); barrier.wait(); start.elapsed() }) }) }, ); } } } criterion_group!(histograms, histograms::bench_bucket_scalability); mod histograms { use std::time::Instant; use criterion::{BenchmarkId, Criterion}; use metrics::core::Collector; pub fn bench_bucket_scalability(c: &mut Criterion) { let mut g = c.benchmark_group("bucket_scalability"); for n in [1, 4, 8, 16, 32, 64, 128, 256] { g.bench_with_input(BenchmarkId::new("nbuckets", n), &n, |b, n| { b.iter_custom(|iters| { let buckets: Vec<f64> = (0..*n).map(|i| i as f64 * 100.0).collect(); let histo = metrics::Histogram::with_opts( metrics::prometheus::HistogramOpts::new("name", "help") .buckets(buckets.clone()), ) .unwrap(); let start = Instant::now(); for i in 0..usize::try_from(iters).unwrap() { histo.observe(buckets[i % buckets.len()]); } let elapsed = start.elapsed(); // self-test let mfs = histo.collect(); assert_eq!(mfs.len(), 1); let metrics = mfs[0].get_metric(); assert_eq!(metrics.len(), 1); let histo = metrics[0].get_histogram(); let buckets = histo.get_bucket(); assert!( buckets .iter() .enumerate() .all(|(i, b)| b.get_cumulative_count() >= i as u64 * (iters / buckets.len() as u64)) ); elapsed }) }); } } } criterion_main!( label_values, single_metric_multicore_scalability, propagation_of_cached_label_value, histograms, ); /* RUST_BACKTRACE=full cargo bench --bench bench_metrics -- --discard-baseline --noplot Results on an im4gn.2xlarge instance label_values__naive_usage/ntimelines/1 time: [178.71 ns 178.74 ns 178.76 ns] label_values__naive_usage/ntimelines/4 time: [532.94 ns 539.59 ns 546.31 ns] label_values__naive_usage/ntimelines/8 time: [1.1082 µs 1.1109 µs 1.1135 µs] label_values__cache_label_values_lookup/ntimelines/1 time: [6.4116 ns 6.4119 ns 6.4123 ns] label_values__cache_label_values_lookup/ntimelines/4 time: [6.3482 ns 6.3819 ns 6.4079 ns] label_values__cache_label_values_lookup/ntimelines/8 time: [6.4213 ns 6.5279 ns 6.6293 ns] single_metric_multicore_scalability/nthreads/1 time: [6.0102 ns 6.0104 ns 6.0106 ns] single_metric_multicore_scalability/nthreads/4 time: [38.127 ns 38.275 ns 38.416 ns] single_metric_multicore_scalability/nthreads/8 time: [73.698 ns 74.882 ns 75.864 ns] propagation_of_cached_label_value__naive/nthreads/1 time: [14.424 ns 14.425 ns 14.426 ns] propagation_of_cached_label_value__naive/nthreads/4 time: [100.71 ns 102.53 ns 104.35 ns] propagation_of_cached_label_value__naive/nthreads/8 time: [211.50 ns 214.44 ns 216.87 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/1 time: [14.135 ns 14.147 ns 14.160 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/4 time: [14.243 ns 14.255 ns 14.268 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/8 time: [14.470 ns 14.682 ns 14.895 ns] bucket_scalability/nbuckets/1 time: [30.352 ns 30.353 ns 30.354 ns] bucket_scalability/nbuckets/4 time: [30.464 ns 30.465 ns 30.467 ns] bucket_scalability/nbuckets/8 time: [30.569 ns 30.575 ns 30.584 ns] bucket_scalability/nbuckets/16 time: [30.961 ns 30.965 ns 30.969 ns] bucket_scalability/nbuckets/32 time: [35.691 ns 35.707 ns 35.722 ns] bucket_scalability/nbuckets/64 time: [47.829 ns 47.898 ns 47.974 ns] bucket_scalability/nbuckets/128 time: [73.479 ns 73.512 ns 73.545 ns] bucket_scalability/nbuckets/256 time: [127.92 ns 127.94 ns 127.96 ns] Results on an i3en.3xlarge instance label_values__naive_usage/ntimelines/1 time: [117.32 ns 117.53 ns 117.74 ns] label_values__naive_usage/ntimelines/4 time: [736.58 ns 741.12 ns 745.61 ns] label_values__naive_usage/ntimelines/8 time: [1.4513 µs 1.4596 µs 1.4665 µs] label_values__cache_label_values_lookup/ntimelines/1 time: [8.0964 ns 8.0979 ns 8.0995 ns] label_values__cache_label_values_lookup/ntimelines/4 time: [8.1620 ns 8.2912 ns 8.4491 ns] label_values__cache_label_values_lookup/ntimelines/8 time: [14.148 ns 14.237 ns 14.324 ns] single_metric_multicore_scalability/nthreads/1 time: [8.0993 ns 8.1013 ns 8.1046 ns] single_metric_multicore_scalability/nthreads/4 time: [80.039 ns 80.672 ns 81.297 ns] single_metric_multicore_scalability/nthreads/8 time: [153.58 ns 154.23 ns 154.90 ns] propagation_of_cached_label_value__naive/nthreads/1 time: [13.924 ns 13.926 ns 13.928 ns] propagation_of_cached_label_value__naive/nthreads/4 time: [143.66 ns 145.27 ns 146.59 ns] propagation_of_cached_label_value__naive/nthreads/8 time: [296.51 ns 297.90 ns 299.30 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/1 time: [14.013 ns 14.149 ns 14.308 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/4 time: [14.311 ns 14.625 ns 14.984 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/8 time: [25.981 ns 26.227 ns 26.476 ns] Results on an Standard L16s v3 (16 vcpus, 128 GiB memory) Intel(R) Xeon(R) Platinum 8370C CPU @ 2.80GHz label_values__naive_usage/ntimelines/1 time: [101.63 ns 101.84 ns 102.06 ns] label_values__naive_usage/ntimelines/4 time: [417.55 ns 424.73 ns 432.63 ns] label_values__naive_usage/ntimelines/8 time: [874.91 ns 889.51 ns 904.25 ns] label_values__cache_label_values_lookup/ntimelines/1 time: [5.7724 ns 5.7760 ns 5.7804 ns] label_values__cache_label_values_lookup/ntimelines/4 time: [7.8878 ns 7.9401 ns 8.0034 ns] label_values__cache_label_values_lookup/ntimelines/8 time: [7.2621 ns 7.6354 ns 8.0337 ns] single_metric_multicore_scalability/nthreads/1 time: [5.7710 ns 5.7744 ns 5.7785 ns] single_metric_multicore_scalability/nthreads/4 time: [66.629 ns 66.994 ns 67.336 ns] single_metric_multicore_scalability/nthreads/8 time: [130.85 ns 131.98 ns 132.91 ns] propagation_of_cached_label_value__naive/nthreads/1 time: [11.540 ns 11.546 ns 11.553 ns] propagation_of_cached_label_value__naive/nthreads/4 time: [131.22 ns 131.90 ns 132.56 ns] propagation_of_cached_label_value__naive/nthreads/8 time: [260.99 ns 262.75 ns 264.26 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/1 time: [11.544 ns 11.550 ns 11.557 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/4 time: [11.568 ns 11.642 ns 11.763 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/8 time: [13.416 ns 14.121 ns 14.886 ns Results on an M4 MAX MacBook Pro Total Number of Cores: 14 (10 performance and 4 efficiency) label_values__naive_usage/ntimelines/1 time: [52.711 ns 53.026 ns 53.381 ns] label_values__naive_usage/ntimelines/4 time: [323.99 ns 330.40 ns 337.53 ns] label_values__naive_usage/ntimelines/8 time: [1.1615 µs 1.1998 µs 1.2399 µs] label_values__cache_label_values_lookup/ntimelines/1 time: [1.6635 ns 1.6715 ns 1.6809 ns] label_values__cache_label_values_lookup/ntimelines/4 time: [1.7786 ns 1.7876 ns 1.8028 ns] label_values__cache_label_values_lookup/ntimelines/8 time: [1.8195 ns 1.8371 ns 1.8665 ns] single_metric_multicore_scalability/nthreads/1 time: [1.7764 ns 1.7909 ns 1.8079 ns] single_metric_multicore_scalability/nthreads/4 time: [33.875 ns 34.868 ns 35.923 ns] single_metric_multicore_scalability/nthreads/8 time: [226.85 ns 235.30 ns 244.18 ns] propagation_of_cached_label_value__naive/nthreads/1 time: [3.4337 ns 3.4491 ns 3.4660 ns] propagation_of_cached_label_value__naive/nthreads/4 time: [69.486 ns 71.937 ns 74.472 ns] propagation_of_cached_label_value__naive/nthreads/8 time: [434.87 ns 456.47 ns 477.84 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/1 time: [3.3767 ns 3.3974 ns 3.4220 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/4 time: [3.6105 ns 4.2355 ns 5.1463 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/8 time: [4.0889 ns 4.9714 ns 6.0779 ns] bucket_scalability/nbuckets/1 time: [4.8455 ns 4.8542 ns 4.8646 ns] bucket_scalability/nbuckets/4 time: [4.5663 ns 4.5722 ns 4.5787 ns] bucket_scalability/nbuckets/8 time: [4.5531 ns 4.5670 ns 4.5842 ns] bucket_scalability/nbuckets/16 time: [4.6392 ns 4.6524 ns 4.6685 ns] bucket_scalability/nbuckets/32 time: [6.0302 ns 6.0439 ns 6.0589 ns] bucket_scalability/nbuckets/64 time: [10.608 ns 10.644 ns 10.691 ns] bucket_scalability/nbuckets/128 time: [22.178 ns 22.316 ns 22.483 ns] bucket_scalability/nbuckets/256 time: [42.190 ns 42.328 ns 42.492 ns] Results on a Hetzner AX102 AMD Ryzen 9 7950X3D 16-Core Processor label_values__naive_usage/ntimelines/1 time: [64.510 ns 64.559 ns 64.610 ns] label_values__naive_usage/ntimelines/4 time: [309.71 ns 326.09 ns 342.32 ns] label_values__naive_usage/ntimelines/8 time: [776.92 ns 819.35 ns 856.93 ns] label_values__cache_label_values_lookup/ntimelines/1 time: [1.2855 ns 1.2943 ns 1.3021 ns] label_values__cache_label_values_lookup/ntimelines/4 time: [1.3865 ns 1.4139 ns 1.4441 ns] label_values__cache_label_values_lookup/ntimelines/8 time: [1.5311 ns 1.5669 ns 1.6046 ns] single_metric_multicore_scalability/nthreads/1 time: [1.1927 ns 1.1981 ns 1.2049 ns] single_metric_multicore_scalability/nthreads/4 time: [24.346 ns 25.439 ns 26.634 ns] single_metric_multicore_scalability/nthreads/8 time: [58.666 ns 60.137 ns 61.486 ns] propagation_of_cached_label_value__naive/nthreads/1 time: [2.7067 ns 2.7238 ns 2.7402 ns] propagation_of_cached_label_value__naive/nthreads/4 time: [62.723 ns 66.214 ns 69.787 ns] propagation_of_cached_label_value__naive/nthreads/8 time: [164.24 ns 170.10 ns 175.68 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/1 time: [2.2915 ns 2.2960 ns 2.3012 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/4 time: [2.5726 ns 2.6158 ns 2.6624 ns] propagation_of_cached_label_value__long_lived_reference_per_thread/nthreads/8 time: [2.7068 ns 2.8243 ns 2.9824 ns] bucket_scalability/nbuckets/1 time: [6.3998 ns 6.4288 ns 6.4684 ns] bucket_scalability/nbuckets/4 time: [6.3603 ns 6.3620 ns 6.3637 ns] bucket_scalability/nbuckets/8 time: [6.1646 ns 6.1654 ns 6.1667 ns] bucket_scalability/nbuckets/16 time: [6.1341 ns 6.1391 ns 6.1454 ns] bucket_scalability/nbuckets/32 time: [8.2206 ns 8.2254 ns 8.2301 ns] bucket_scalability/nbuckets/64 time: [13.988 ns 13.994 ns 14.000 ns] bucket_scalability/nbuckets/128 time: [28.180 ns 28.216 ns 28.251 ns] bucket_scalability/nbuckets/256 time: [54.914 ns 54.931 ns 54.951 ns] */
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/benches/bench_walredo.rs
pageserver/benches/bench_walredo.rs
//! Quantify a single walredo manager's throughput under N concurrent callers. //! //! The benchmark implementation ([`bench_impl`]) is parametrized by //! - `redo_work` => an async closure that takes a `PostgresRedoManager` and performs one redo //! - `n_redos` => number of times the benchmark shell execute the `redo_work` //! - `nclients` => number of clients (more on this shortly). //! //! The benchmark impl sets up a multi-threaded tokio runtime with default parameters. //! It spawns `nclients` times [`client`] tokio tasks. //! Each task executes the `redo_work` `n_redos/nclients` times. //! //! We exercise the following combinations: //! - `redo_work = ping / short / medium`` //! - `nclients = [1, 2, 4, 8, 16, 32, 64, 128]` //! //! We let `criterion` determine the `n_redos` using `iter_custom`. //! The idea is that for each `(redo_work, nclients)` combination, //! criterion will run the `bench_impl` multiple times with different `n_redos`. //! The `bench_impl` reports the aggregate wall clock time from the clients' perspective. //! Criterion will divide that by `n_redos` to compute the "time per iteration". //! In our case, "time per iteration" means "time per redo_work execution". //! //! NB: the way by which `iter_custom` determines the "number of iterations" //! is called sampling. Apparently the idea here is to detect outliers. //! We're not sure whether the current choice of sampling method makes sense. //! See https://bheisler.github.io/criterion.rs/book/user_guide/command_line_output.html#collecting-samples //! //! # Reference Numbers //! //! 2024-09-18 on im4gn.2xlarge //! //! ```text //! ping/1 time: [21.789 µs 21.918 µs 22.078 µs] //! ping/2 time: [27.686 µs 27.812 µs 27.970 µs] //! ping/4 time: [35.468 µs 35.671 µs 35.926 µs] //! ping/8 time: [59.682 µs 59.987 µs 60.363 µs] //! ping/16 time: [101.79 µs 102.37 µs 103.08 µs] //! ping/32 time: [184.18 µs 185.15 µs 186.36 µs] //! ping/64 time: [349.86 µs 351.45 µs 353.47 µs] //! ping/128 time: [684.53 µs 687.98 µs 692.17 µs] //! short/1 time: [31.833 µs 32.126 µs 32.428 µs] //! short/2 time: [35.558 µs 35.756 µs 35.992 µs] //! short/4 time: [44.850 µs 45.138 µs 45.484 µs] //! short/8 time: [65.985 µs 66.379 µs 66.853 µs] //! short/16 time: [127.06 µs 127.90 µs 128.87 µs] //! short/32 time: [252.98 µs 254.70 µs 256.73 µs] //! short/64 time: [497.13 µs 499.86 µs 503.26 µs] //! short/128 time: [987.46 µs 993.45 µs 1.0004 ms] //! medium/1 time: [137.91 µs 138.55 µs 139.35 µs] //! medium/2 time: [192.00 µs 192.91 µs 194.07 µs] //! medium/4 time: [389.62 µs 391.55 µs 394.01 µs] //! medium/8 time: [776.80 µs 780.33 µs 784.77 µs] //! medium/16 time: [1.5323 ms 1.5383 ms 1.5459 ms] //! medium/32 time: [3.0120 ms 3.0226 ms 3.0350 ms] //! medium/64 time: [5.7405 ms 5.7787 ms 5.8166 ms] //! medium/128 time: [10.412 ms 10.574 ms 10.718 ms] //! ``` use std::future::Future; use std::sync::Arc; use std::time::{Duration, Instant}; use anyhow::Context; use bytes::{Buf, Bytes}; use criterion::{BenchmarkId, Criterion}; use once_cell::sync::Lazy; use pageserver::config::PageServerConf; use pageserver::walredo::{PostgresRedoManager, RedoAttemptType}; use pageserver_api::key::Key; use pageserver_api::shard::TenantShardId; use postgres_ffi::{BLCKSZ, PgMajorVersion}; use tokio::sync::Barrier; use tokio::task::JoinSet; use utils::id::TenantId; use utils::lsn::Lsn; use wal_decoder::models::record::NeonWalRecord; fn bench(c: &mut Criterion) { macro_rules! bench_group { ($name:expr, $redo_work:expr) => {{ let name: &str = $name; let nclients = [1, 2, 4, 8, 16, 32, 64, 128]; for nclients in nclients { let mut group = c.benchmark_group(name); group.bench_with_input( BenchmarkId::from_parameter(nclients), &nclients, |b, nclients| { b.iter_custom(|iters| bench_impl($redo_work, iters, *nclients)); }, ); } }}; } // // benchmark the protocol implementation // let pg_version = PgMajorVersion::PG14; bench_group!( "ping", Arc::new(move |mgr: Arc<PostgresRedoManager>| async move { let _: () = mgr.ping(pg_version).await.unwrap(); }) ); // // benchmarks with actual record redo // let make_redo_work = |req: &'static Request| { Arc::new(move |mgr: Arc<PostgresRedoManager>| async move { let page = req.execute(&mgr).await.unwrap(); assert_eq!(page.remaining(), BLCKSZ as usize); }) }; bench_group!("short", { static REQUEST: Lazy<Request> = Lazy::new(Request::short_input); make_redo_work(&REQUEST) }); bench_group!("medium", { static REQUEST: Lazy<Request> = Lazy::new(Request::medium_input); make_redo_work(&REQUEST) }); } criterion::criterion_group!(benches, bench); criterion::criterion_main!(benches); // Returns the sum of each client's wall-clock time spent executing their share of the n_redos. fn bench_impl<F, Fut>(redo_work: Arc<F>, n_redos: u64, nclients: u64) -> Duration where F: Fn(Arc<PostgresRedoManager>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static, { let repo_dir = camino_tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); let conf = PageServerConf::dummy_conf(repo_dir.path().to_path_buf()); let conf = Box::leak(Box::new(conf)); let tenant_shard_id = TenantShardId::unsharded(TenantId::generate()); let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(); let start = Arc::new(Barrier::new(nclients as usize)); let mut tasks = JoinSet::new(); let manager = PostgresRedoManager::new(conf, tenant_shard_id); let manager = Arc::new(manager); // divide the amount of work equally among the clients. let nredos_per_client = n_redos / nclients; for _ in 0..nclients { rt.block_on(async { tasks.spawn(client( Arc::clone(&manager), Arc::clone(&start), Arc::clone(&redo_work), nredos_per_client, )) }); } rt.block_on(async move { let mut total_wallclock_time = Duration::ZERO; while let Some(res) = tasks.join_next().await { total_wallclock_time += res.unwrap(); } total_wallclock_time }) } async fn client<F, Fut>( mgr: Arc<PostgresRedoManager>, start: Arc<Barrier>, redo_work: Arc<F>, n_redos: u64, ) -> Duration where F: Fn(Arc<PostgresRedoManager>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static, { start.wait().await; let start = Instant::now(); for _ in 0..n_redos { redo_work(Arc::clone(&mgr)).await; // The real pageserver will rarely if ever do 2 walredos in a row without // yielding to the executor. tokio::task::yield_now().await; } start.elapsed() } macro_rules! lsn { ($input:expr) => {{ let input = $input; match <Lsn as std::str::FromStr>::from_str(input) { Ok(lsn) => lsn, Err(e) => panic!("failed to parse {}: {}", input, e), } }}; } /// Simple wrapper around `WalRedoManager::request_redo`. /// /// In benchmarks this is cloned around. #[derive(Clone)] struct Request { key: Key, lsn: Lsn, base_img: Option<(Lsn, Bytes)>, records: Vec<(Lsn, NeonWalRecord)>, pg_version: PgMajorVersion, } impl Request { async fn execute(&self, manager: &PostgresRedoManager) -> anyhow::Result<Bytes> { let Request { key, lsn, base_img, records, pg_version, } = self; // TODO: avoid these clones manager .request_redo( *key, *lsn, base_img.clone(), records.clone(), *pg_version, RedoAttemptType::ReadPage, ) .await .context("request_redo") } fn pg_record(will_init: bool, bytes: &'static [u8]) -> NeonWalRecord { let rec = Bytes::from_static(bytes); NeonWalRecord::Postgres { will_init, rec } } /// Short payload, 1132 bytes. // pg_records are copypasted from log, where they are put with Debug impl of Bytes, which uses \0 // for null bytes. #[allow(clippy::octal_escapes)] pub fn short_input() -> Request { let pg_record = Self::pg_record; Request { key: Key { field1: 0, field2: 1663, field3: 13010, field4: 1259, field5: 0, field6: 0, }, lsn: lsn!("0/16E2408"), base_img: None, records: vec![ ( lsn!("0/16A9388"), pg_record(true, b"j\x03\0\0\0\x04\0\0\xe8\x7fj\x01\0\0\0\0\0\n\0\0\xd0\x16\x13Y\0\x10\0\04\x03\xd4\0\x05\x7f\x06\0\0\xd22\0\0\xeb\x04\0\0\0\0\0\0\xff\x03\0\0\0\0\x80\xeca\x01\0\0\x01\0\xd4\0\xa0\x1d\0 \x04 \0\0\0\0/\0\x01\0\xa0\x9dX\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0.\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\00\x9f\x9a\x01P\x9e\xb2\x01\0\x04\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x02\0!\0\x01\x08 \xff\xff\xff?\0\0\0\0\0\0@\0\0another_table\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x98\x08\0\0\x02@\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0@\0\0\0\0\0\0\0\0\0\0\0\0\x80\xbf\0\0\0\0\0\0\0\0\0\0pr\x01\0\0\0\0\0\0\0\0\x01d\0\0\0\0\0\0\x04\0\0\x01\0\0\0\0\0\0\0\x0c\x02\0\0\0\0\0\0\0\0\0\0\0\0\0\0/\0!\x80\x03+ \xff\xff\xff\x7f\0\0\0\0\0\xdf\x04\0\0pg_type\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x0b\0\0\0G\0\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0\0\0\0\0\0\0\0\x0e\0\0\0\0@\x16D\x0e\0\0\0K\x10\0\0\x01\0pr \0\0\0\0\0\0\0\0\x01n\0\0\0\0\0\xd6\x02\0\0\x01\0\0\0[\x01\0\0\0\0\0\0\0\t\x04\0\0\x02\0\0\0\x01\0\0\0\n\0\0\0\n\0\0\0\x7f\0\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0\0\0C\x01\0\0\x15\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0.\0!\x80\x03+ \xff\xff\xff\x7f\0\0\0\0\0;\n\0\0pg_statistic\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x0b\0\0\0\xfd.\0\0\0\0\0\0\n\0\0\0\x02\0\0\0;\n\0\0\0\0\0\0\x13\0\0\0\0\0\xcbC\x13\0\0\0\x18\x0b\0\0\x01\0pr\x1f\0\0\0\0\0\0\0\0\x01n\0\0\0\0\0\xd6\x02\0\0\x01\0\0\0C\x01\0\0\0\0\0\0\0\t\x04\0\0\x01\0\0\0\x01\0\0\0\n\0\0\0\n\0\0\0\x7f\0\0\0\0\0\0\x02\0\x01"), ), ( lsn!("0/16D4080"), pg_record(false, b"\xbc\0\0\0\0\0\0\0h?m\x01\0\0\0\0p\n\0\09\x08\xa3\xea\0 \x8c\0\x7f\x06\0\0\xd22\0\0\xeb\x04\0\0\0\0\0\0\xff\x02\0@\0\0another_table\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x98\x08\0\0\x02@\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0@\0\0\0\0\0\0\x05\0\0\0\0@zD\x05\0\0\0\0\0\0\0\0\0pr\x01\0\0\0\0\0\0\0\0\x01d\0\0\0\0\0\0\x04\0\0\x01\0\0\0\x02\0"), ), ], pg_version: PgMajorVersion::PG14, } } /// Medium sized payload, serializes as 26393 bytes. // see [`short`] #[allow(clippy::octal_escapes)] pub fn medium_input() -> Request { let pg_record = Self::pg_record; Request { key: Key { field1: 0, field2: 1663, field3: 13010, field4: 16384, field5: 0, field6: 0, }, lsn: lsn!("0/16E2440"), base_img: None, records: vec![ (lsn!("0/16B40A0"), pg_record(true, b"C\0\0\0\0\x04\0\0(@k\x01\0\0\0\0\x80\n\0\0\x9c$2\xb4\0`\x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\0\0\0\0\0\0\0\0\x01\0\0")), (lsn!("0/16B40E8"), pg_record(false, b"C\0\0\0\0\x04\0\0X@k\x01\0\0\0\0\0\n\0\0\x8c\xe7\xaa}\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x01\0\0\0\0\0\0\0\x02\0\0")), (lsn!("0/16B4130"), pg_record(false, b"C\0\0\0\0\x04\0\0\xa0@k\x01\0\0\0\0\0\n\0\0\xb3\xa9a\x89\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x02\0\0\0\0\0\0\0\x03\0\0")), (lsn!("0/16B4178"), pg_record(false, b"C\0\0\0\0\x04\0\0\xe8@k\x01\0\0\0\0\0\n\0\0Z\xd8\xd4W\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x03\0\0\0\0\0\0\0\x04\0\0")), (lsn!("0/16B41C0"), pg_record(false, b"C\0\0\0\0\x04\0\00Ak\x01\0\0\0\0\0\n\0\0G%L\xe1\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x04\0\0\0\0\0\0\0\x05\0\0")), (lsn!("0/16B4208"), pg_record(false, b"C\0\0\0\0\x04\0\0xAk\x01\0\0\0\0\0\n\0\0\xbf\xe2Z\xed\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x05\0\0\0\0\0\0\0\x06\0\0")), (lsn!("0/16B4250"), pg_record(false, b"C\0\0\0\0\x04\0\0\xc0Ak\x01\0\0\0\0\0\n\0\0\xcc\xcc6}\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x06\0\0\0\0\0\0\0\x07\0\0")), (lsn!("0/16B4298"), pg_record(false, b"C\0\0\0\0\x04\0\0\x08Bk\x01\0\0\0\0\0\n\0\0\xdc\t\x18v\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x07\0\0\0\0\0\0\0\x08\0\0")), (lsn!("0/16B42E0"), pg_record(false, b"C\0\0\0\0\x04\0\0PBk\x01\0\0\0\0\0\n\0\0\xe3\\\xb0U\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x08\0\0\0\0\0\0\0\t\0\0")), (lsn!("0/16B4328"), pg_record(false, b"C\0\0\0\0\x04\0\0\x98Bk\x01\0\0\0\0\0\n\0\0\x83[\xe8\x90\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\t\0\0\0\0\0\0\0\n\0\0")), (lsn!("0/16B4370"), pg_record(false, b"C\0\0\0\0\x04\0\0\xe0Bk\x01\0\0\0\0\0\n\0\0$\xd5m\xad\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\n\0\0\0\0\0\0\0\x0b\0\0")), (lsn!("0/16B43B8"), pg_record(false, b"C\0\0\0\0\x04\0\0(Ck\x01\0\0\0\0\0\n\0\0\x94\x93\xe7-\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x0b\0\0\0\0\0\0\0\x0c\0\0")), (lsn!("0/16B4400"), pg_record(false, b"C\0\0\0\0\x04\0\0pCk\x01\0\0\0\0\0\n\0\0\xd0Y@\xc5\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x0c\0\0\0\0\0\0\0\r\0\0")), (lsn!("0/16B4448"), pg_record(false, b"C\0\0\0\0\x04\0\0\xb8Ck\x01\0\0\0\0\0\n\0\0\xb0^\x18\0\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\r\0\0\0\0\0\0\0\x0e\0\0")), (lsn!("0/16B4490"), pg_record(false, b"C\0\0\0\0\x04\0\0\0Dk\x01\0\0\0\0\0\n\0\0\x97,\x15z\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x0e\0\0\0\0\0\0\0\x0f\0\0")), (lsn!("0/16B44D8"), pg_record(false, b"C\0\0\0\0\x04\0\0HDk\x01\0\0\0\0\0\n\0\0\xfa\x04\xb1@\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x0f\0\0\0\0\0\0\0\x10\0\0")), (lsn!("0/16B4520"), pg_record(false, b"C\0\0\0\0\x04\0\0\x90Dk\x01\0\0\0\0\0\n\0\0Z\xd9\xa49\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x10\0\0\0\0\0\0\0\x11\0\0")), (lsn!("0/16B4568"), pg_record(false, b"C\0\0\0\0\x04\0\0\xd8Dk\x01\0\0\0\0\0\n\0\0\xa2\x1e\xb25\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x11\0\0\0\0\0\0\0\x12\0\0")), (lsn!("0/16B45B0"), pg_record(false, b"C\0\0\0\0\x04\0\0 Ek\x01\0\0\0\0\0\n\0\0\\\xa7\x08V\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x12\0\0\0\0\0\0\0\x13\0\0")), (lsn!("0/16B45F8"), pg_record(false, b"C\0\0\0\0\x04\0\0hEk\x01\0\0\0\0\0\n\0\0\xb5\xd6\xbd\x88\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x13\0\0\0\0\0\0\0\x14\0\0")), (lsn!("0/16B4640"), pg_record(false, b"C\0\0\0\0\x04\0\0\xb0Ek\x01\0\0\0\0\0\n\0\0i\xdcT\xa9\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x14\0\0\0\0\0\0\0\x15\0\0")), (lsn!("0/16B4688"), pg_record(false, b"C\0\0\0\0\x04\0\0\xf8Ek\x01\0\0\0\0\0\n\0\0\x91\x1bB\xa5\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x15\0\0\0\0\0\0\0\x16\0\0")), (lsn!("0/16B46D0"), pg_record(false, b"C\0\0\0\0\x04\0\0@Fk\x01\0\0\0\0\0\n\0\0P[P\x89\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x16\0\0\0\0\0\0\0\x17\0\0")), (lsn!("0/16B4718"), pg_record(false, b"C\0\0\0\0\x04\0\0\x88Fk\x01\0\0\0\0\0\n\0\0\xf2\xf0\0>\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x17\0\0\0\0\0\0\0\x18\0\0")), (lsn!("0/16B4760"), pg_record(false, b"C\0\0\0\0\x04\0\0\xd0Fk\x01\0\0\0\0\0\n\0\0\xcd\xa5\xa8\x1d\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x18\0\0\0\0\0\0\0\x19\0\0")), (lsn!("0/16B47A8"), pg_record(false, b"C\0\0\0\0\x04\0\0\x18Gk\x01\0\0\0\0\0\n\0\0lU\x81O\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x19\0\0\0\0\0\0\0\x1a\0\0")), (lsn!("0/16B47F0"), pg_record(false, b"C\0\0\0\0\x04\0\0`Gk\x01\0\0\0\0\0\n\0\0\xcb\xdb\x04r\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x1a\0\0\0\0\0\0\0\x1b\0\0")), (lsn!("0/16B4838"), pg_record(false, b"C\0\0\0\0\x04\0\0\xa8Gk\x01\0\0\0\0\0\n\0\0\xbaj\xffe\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x1b\0\0\0\0\0\0\0\x1c\0\0")), (lsn!("0/16B4880"), pg_record(false, b"C\0\0\0\0\x04\0\0\xf0Gk\x01\0\0\0\0\0\n\0\0\xfe\xa0X\x8d\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x1c\0\0\0\0\0\0\0\x1d\0\0")), (lsn!("0/16B48C8"), pg_record(false, b"C\0\0\0\0\x04\0\08Hk\x01\0\0\0\0\0\n\0\0\x06\x9e_\x0e\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x1d\0\0\0\0\0\0\0\x1e\0\0")), (lsn!("0/16B4910"), pg_record(false, b"C\0\0\0\0\x04\0\0\x80Hk\x01\0\0\0\0\0\n\0\0u\xb03\x9e\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x1e\0\0\0\0\0\0\0\x1f\0\0")), (lsn!("0/16B4958"), pg_record(false, b"C\0\0\0\0\x04\0\0\xc8Hk\x01\0\0\0\0\0\n\0\0\xb6\x1e\xe3-\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\x1f\0\0\0\0\0\0\0 \0\0")), (lsn!("0/16B49A0"), pg_record(false, b"C\0\0\0\0\x04\0\0\x10Ik\x01\0\0\0\0\0\n\0\0(\xd2\x8d\xe1\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0 \0\0\0\0\0\0\0!\0\0")), (lsn!("0/16B49E8"), pg_record(false, b"C\0\0\0\0\x04\0\0XIk\x01\0\0\0\0\0\n\0\0\xd0\x15\x9b\xed\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0!\0\0\0\0\0\0\0\"\0\0")), (lsn!("0/16B4A30"), pg_record(false, b"C\0\0\0\0\x04\0\0\xa0Ik\x01\0\0\0\0\0\n\0\0\xef[P\x19\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\"\0\0\0\0\0\0\0#\0\0")), (lsn!("0/16B4A78"), pg_record(false, b"C\0\0\0\0\x04\0\0\xe8Ik\x01\0\0\0\0\0\n\0\0\x06*\xe5\xc7\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0#\0\0\0\0\0\0\0$\0\0")), (lsn!("0/16B4AC0"), pg_record(false, b"C\0\0\0\0\x04\0\00Jk\x01\0\0\0\0\0\n\0\0hNrZ\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0$\0\0\0\0\0\0\0%\0\0")), (lsn!("0/16B4B08"), pg_record(false, b"C\0\0\0\0\x04\0\0xJk\x01\0\0\0\0\0\n\0\0\x90\x89dV\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0%\0\0\0\0\0\0\0&\0\0")), (lsn!("0/16B4B50"), pg_record(false, b"C\0\0\0\0\x04\0\0\xc0Jk\x01\0\0\0\0\0\n\0\0\xe3\xa7\x08\xc6\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0&\0\0\0\0\0\0\0'\0\0")), (lsn!("0/16B4B98"), pg_record(false, b"C\0\0\0\0\x04\0\0\x08Kk\x01\0\0\0\0\0\n\0\0\x80\xfb)\xe6\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0'\0\0\0\0\0\0\0(\0\0")), (lsn!("0/16B4BE0"), pg_record(false, b"C\0\0\0\0\x04\0\0PKk\x01\0\0\0\0\0\n\0\0\xbf\xae\x81\xc5\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0(\0\0\0\0\0\0\0)\0\0")), (lsn!("0/16B4C28"), pg_record(false, b"C\0\0\0\0\x04\0\0\x98Kk\x01\0\0\0\0\0\n\0\0\xdf\xa9\xd9\0\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0)\0\0\0\0\0\0\0*\0\0")), (lsn!("0/16B4C70"), pg_record(false, b"C\0\0\0\0\x04\0\0\xe0Kk\x01\0\0\0\0\0\n\0\0x'\\=\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0*\0\0\0\0\0\0\0+\0\0")), (lsn!("0/16B4CB8"), pg_record(false, b"C\0\0\0\0\x04\0\0(Lk\x01\0\0\0\0\0\n\0\0]\xca\xc6\xc0\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0+\0\0\0\0\0\0\0,\0\0")), (lsn!("0/16B4D00"), pg_record(false, b"C\0\0\0\0\x04\0\0pLk\x01\0\0\0\0\0\n\0\0\x19\0a(\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0,\0\0\0\0\0\0\0-\0\0")), (lsn!("0/16B4D48"), pg_record(false, b"C\0\0\0\0\x04\0\0\xb8Lk\x01\0\0\0\0\0\n\0\0y\x079\xed\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0-\0\0\0\0\0\0\0.\0\0")), (lsn!("0/16B4D90"), pg_record(false, b"C\0\0\0\0\x04\0\0\0Mk\x01\0\0\0\0\0\n\0\0\xcb\xde$\xea\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0.\0\0\0\0\0\0\0/\0\0")), (lsn!("0/16B4DD8"), pg_record(false, b"C\0\0\0\0\x04\0\0HMk\x01\0\0\0\0\0\n\0\0\xa6\xf6\x80\xd0\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0/\0\0\0\0\0\0\00\0\0")), (lsn!("0/16B4E20"), pg_record(false, b"C\0\0\0\0\x04\0\0\x90Mk\x01\0\0\0\0\0\n\0\0\x06+\x95\xa9\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\00\0\0\0\0\0\0\01\0\0")), (lsn!("0/16B4E68"), pg_record(false, b"C\0\0\0\0\x04\0\0\xd8Mk\x01\0\0\0\0\0\n\0\0\xfe\xec\x83\xa5\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\01\0\0\0\0\0\0\02\0\0")), (lsn!("0/16B4EB0"), pg_record(false, b"C\0\0\0\0\x04\0\0 Nk\x01\0\0\0\0\0\n\0\0s\xcc6\xed\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\02\0\0\0\0\0\0\03\0\0")), (lsn!("0/16B4EF8"), pg_record(false, b"C\0\0\0\0\x04\0\0hNk\x01\0\0\0\0\0\n\0\0\x9a\xbd\x833\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\03\0\0\0\0\0\0\04\0\0")), (lsn!("0/16B4F40"), pg_record(false, b"C\0\0\0\0\x04\0\0\xb0Nk\x01\0\0\0\0\0\n\0\0F\xb7j\x12\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\04\0\0\0\0\0\0\05\0\0")), (lsn!("0/16B4F88"), pg_record(false, b"C\0\0\0\0\x04\0\0\xf8Nk\x01\0\0\0\0\0\n\0\0\xbep|\x1e\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\05\0\0\0\0\0\0\06\0\0")), (lsn!("0/16B4FD0"), pg_record(false, b"C\0\0\0\0\x04\0\0@Ok\x01\0\0\0\0\0\n\0\0\x0c\xa9a\x19\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\06\0\0\0\0\0\0\07\0\0")), (lsn!("0/16B5018"), pg_record(false, b"C\0\0\0\0\x04\0\0\x88Ok\x01\0\0\0\0\0\n\0\0\xae\x021\xae\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\07\0\0\0\0\0\0\08\0\0")), (lsn!("0/16B5060"), pg_record(false, b"C\0\0\0\0\x04\0\0\xd0Ok\x01\0\0\0\0\0\n\0\0\x91W\x99\x8d\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\08\0\0\0\0\0\0\09\0\0")), (lsn!("0/16B50A8"), pg_record(false, b"C\0\0\0\0\x04\0\0\x18Pk\x01\0\0\0\0\0\n\0\0\0\xd4\x0eS\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\09\0\0\0\0\0\0\0:\0\0")), (lsn!("0/16B50F0"), pg_record(false, b"C\0\0\0\0\x04\0\0`Pk\x01\0\0\0\0\0\n\0\0\xa7Z\x8bn\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0:\0\0\0\0\0\0\0;\0\0")), (lsn!("0/16B5138"), pg_record(false, b"C\0\0\0\0\x04\0\0\xa8Pk\x01\0\0\0\0\0\n\0\0\xd6\xebpy\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0;\0\0\0\0\0\0\0<\0\0")), (lsn!("0/16B5180"), pg_record(false, b"C\0\0\0\0\x04\0\0\xf0Pk\x01\0\0\0\0\0\n\0\0\x92!\xd7\x91\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0<\0\0\0\0\0\0\0=\0\0")), (lsn!("0/16B51C8"), pg_record(false, b"C\0\0\0\0\x04\0\08Qk\x01\0\0\0\0\0\n\0\03\xd1\xfe\xc3\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0=\0\0\0\0\0\0\0>\0\0")), (lsn!("0/16B5210"), pg_record(false, b"C\0\0\0\0\x04\0\0\x80Qk\x01\0\0\0\0\0\n\0\0@\xff\x92S\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0>\0\0\0\0\0\0\0?\0\0")), (lsn!("0/16B5258"), pg_record(false, b"C\0\0\0\0\x04\0\0\xc8Qk\x01\0\0\0\0\0\n\0\0.*G\xf7\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0?\0\0\0\0\0\0\0@\0\0")), (lsn!("0/16B52A0"), pg_record(false, b"C\0\0\0\0\x04\0\0\x10Rk\x01\0\0\0\0\0\n\0\0=\xb23T\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0@\0\0\0\0\0\0\0A\0\0")), (lsn!("0/16B52E8"), pg_record(false, b"C\0\0\0\0\x04\0\0XRk\x01\0\0\0\0\0\n\0\0\xc5u%X\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0A\0\0\0\0\0\0\0B\0\0")), (lsn!("0/16B5330"), pg_record(false, b"C\0\0\0\0\x04\0\0\xa0Rk\x01\0\0\0\0\0\n\0\0\xfa;\xee\xac\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0B\0\0\0\0\0\0\0C\0\0")), (lsn!("0/16B5378"), pg_record(false, b"C\0\0\0\0\x04\0\0\xe8Rk\x01\0\0\0\0\0\n\0\0\x13J[r\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0C\0\0\0\0\0\0\0D\0\0")), (lsn!("0/16B53C0"), pg_record(false, b"C\0\0\0\0\x04\0\00Sk\x01\0\0\0\0\0\n\0\0\x0e\xb7\xc3\xc4\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0D\0\0\0\0\0\0\0E\0\0")), (lsn!("0/16B5408"), pg_record(false, b"C\0\0\0\0\x04\0\0xSk\x01\0\0\0\0\0\n\0\0\xf6p\xd5\xc8\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0E\0\0\0\0\0\0\0F\0\0")), (lsn!("0/16B5450"), pg_record(false, b"C\0\0\0\0\x04\0\0\xc0Sk\x01\0\0\0\0\0\n\0\0\x85^\xb9X\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0F\0\0\0\0\0\0\0G\0\0")), (lsn!("0/16B5498"), pg_record(false, b"C\0\0\0\0\x04\0\0\x08Tk\x01\0\0\0\0\0\n\0\0s\xa9\x88\x05\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0G\0\0\0\0\0\0\0H\0\0")), (lsn!("0/16B54E0"), pg_record(false, b"C\0\0\0\0\x04\0\0PTk\x01\0\0\0\0\0\n\0\0L\xfc &\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0H\0\0\0\0\0\0\0I\0\0")), (lsn!("0/16B5528"), pg_record(false, b"C\0\0\0\0\x04\0\0\x98Tk\x01\0\0\0\0\0\n\0\0,\xfbx\xe3\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0I\0\0\0\0\0\0\0J\0\0")), (lsn!("0/16B5570"), pg_record(false, b"C\0\0\0\0\x04\0\0\xe0Tk\x01\0\0\0\0\0\n\0\0\x8bu\xfd\xde\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0J\0\0\0\0\0\0\0K\0\0")), (lsn!("0/16B55B8"), pg_record(false, b"C\0\0\0\0\x04\0\0(Uk\x01\0\0\0\0\0\n\0\0;3w^\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0K\0\0\0\0\0\0\0L\0\0")), (lsn!("0/16B5600"), pg_record(false, b"C\0\0\0\0\x04\0\0pUk\x01\0\0\0\0\0\n\0\0\x7f\xf9\xd0\xb6\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0L\0\0\0\0\0\0\0M\0\0")), (lsn!("0/16B5648"), pg_record(false, b"C\0\0\0\0\x04\0\0\xb8Uk\x01\0\0\0\0\0\n\0\0\x1f\xfe\x88s\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0M\0\0\0\0\0\0\0N\0\0")), (lsn!("0/16B5690"), pg_record(false, b"C\0\0\0\0\x04\0\0\0Vk\x01\0\0\0\0\0\n\0\0\xde\xbe\x9a_\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0N\0\0\0\0\0\0\0O\0\0")), (lsn!("0/16B56D8"), pg_record(false, b"C\0\0\0\0\x04\0\0HVk\x01\0\0\0\0\0\n\0\0\xb3\x96>e\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0O\0\0\0\0\0\0\0P\0\0")), (lsn!("0/16B5720"), pg_record(false, b"C\0\0\0\0\x04\0\0\x90Vk\x01\0\0\0\0\0\n\0\0\x13K+\x1c\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0P\0\0\0\0\0\0\0Q\0\0")), (lsn!("0/16B5768"), pg_record(false, b"C\0\0\0\0\x04\0\0\xd8Vk\x01\0\0\0\0\0\n\0\0\xeb\x8c=\x10\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0Q\0\0\0\0\0\0\0R\0\0")), (lsn!("0/16B57B0"), pg_record(false, b"C\0\0\0\0\x04\0\0 Wk\x01\0\0\0\0\0\n\0\0\x155\x87s\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0R\0\0\0\0\0\0\0S\0\0")), (lsn!("0/16B57F8"), pg_record(false, b"C\0\0\0\0\x04\0\0hWk\x01\0\0\0\0\0\n\0\0\xfcD2\xad\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0S\0\0\0\0\0\0\0T\0\0")), (lsn!("0/16B5840"), pg_record(false, b"C\0\0\0\0\x04\0\0\xb0Wk\x01\0\0\0\0\0\n\0\0 N\xdb\x8c\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0T\0\0\0\0\0\0\0U\0\0")), (lsn!("0/16B5888"), pg_record(false, b"C\0\0\0\0\x04\0\0\xf8Wk\x01\0\0\0\0\0\n\0\0\xd8\x89\xcd\x80\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0U\0\0\0\0\0\0\0V\0\0")), (lsn!("0/16B58D0"), pg_record(false, b"C\0\0\0\0\x04\0\0@Xk\x01\0\0\0\0\0\n\0\03\x9e\xfeV\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0V\0\0\0\0\0\0\0W\0\0")), (lsn!("0/16B5918"), pg_record(false, b"C\0\0\0\0\x04\0\0\x88Xk\x01\0\0\0\0\0\n\0\0\x915\xae\xe1\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0W\0\0\0\0\0\0\0X\0\0")), (lsn!("0/16B5960"), pg_record(false, b"C\0\0\0\0\x04\0\0\xd0Xk\x01\0\0\0\0\0\n\0\0\xae`\x06\xc2\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0X\0\0\0\0\0\0\0Y\0\0")), (lsn!("0/16B59A8"), pg_record(false, b"C\0\0\0\0\x04\0\0\x18Yk\x01\0\0\0\0\0\n\0\0\x0f\x90/\x90\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0Y\0\0\0\0\0\0\0Z\0\0")), (lsn!("0/16B59F0"), pg_record(false, b"C\0\0\0\0\x04\0\0`Yk\x01\0\0\0\0\0\n\0\0\xa8\x1e\xaa\xad\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0Z\0\0\0\0\0\0\0[\0\0")), (lsn!("0/16B5A38"), pg_record(false, b"C\0\0\0\0\x04\0\0\xa8Yk\x01\0\0\0\0\0\n\0\0\xd9\xafQ\xba\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0[\0\0\0\0\0\0\0\\\0\0")), (lsn!("0/16B5A80"), pg_record(false, b"C\0\0\0\0\x04\0\0\xf0Yk\x01\0\0\0\0\0\n\0\0\x9de\xf6R\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0\\\0\0\0\0\0\0\0]\0\0")), (lsn!("0/16B5AC8"), pg_record(false, b"C\0\0\0\0\x04\0\08Zk\x01\0\0\0\0\0\n\0\0O\x0c\xd0+\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0]\0\0\0\0\0\0\0^\0\0")), (lsn!("0/16B5B10"), pg_record(false, b"C\0\0\0\0\x04\0\0\x80Zk\x01\0\0\0\0\0\n\0\0<\"\xbc\xbb\0 \x12\0\x7f\x06\0\0\xd22\0\0\0@\0\0\0\0\0\0\xff\x03\x01\0\0\x08\x01\0\0\0\x18\0^\0\0\0\0\0\0\0_\0\0")),
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/benches/upload_queue.rs
pageserver/benches/upload_queue.rs
//! Upload queue benchmarks. use std::str::FromStr as _; use std::sync::Arc; use std::sync::atomic::AtomicU32; use criterion::{Bencher, Criterion, criterion_group, criterion_main}; use pageserver::tenant::IndexPart; use pageserver::tenant::metadata::TimelineMetadata; use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata; use pageserver::tenant::storage_layer::LayerName; use pageserver::tenant::upload_queue::{Delete, UploadOp, UploadQueue, UploadTask}; use pprof::criterion::{Output, PProfProfiler}; use utils::generation::Generation; use utils::shard::{ShardCount, ShardIndex, ShardNumber}; // Register benchmarks with Criterion. criterion_group!( name = benches; config = Criterion::default().with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); targets = bench_upload_queue_next_ready, ); criterion_main!(benches); /// Benchmarks the cost of UploadQueue::next_ready() with the given number of in-progress tasks /// (which is equivalent to tasks ahead of it in the queue). This has linear cost, and the upload /// queue as a whole is thus quadratic. /// /// UploadOp::UploadLayer requires an entire tenant and timeline to construct, so we just test /// Delete and UploadMetadata instead. This is incidentally the most expensive case. fn bench_upload_queue_next_ready(c: &mut Criterion) { let mut g = c.benchmark_group("upload_queue_next_ready"); for inprogress in [0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000] { g.bench_function(format!("inprogress={inprogress}"), |b| { run_bench(b, inprogress).unwrap() }); } fn run_bench(b: &mut Bencher, inprogress: usize) -> anyhow::Result<()> { // Construct two layers. layer0 is in the indexes, layer1 will be deleted. let layer0 = LayerName::from_str("000000000000000000000000000000000000-100000000000000000000000000000000000__00000000016B59D8-00000000016B5A51").expect("invalid name"); let layer1 = LayerName::from_str("100000000000000000000000000000000001-200000000000000000000000000000000000__00000000016B59D8-00000000016B5A51").expect("invalid name"); let metadata = LayerFileMetadata { shard: ShardIndex::new(ShardNumber(1), ShardCount(2)), generation: Generation::Valid(1), file_size: 0, }; // Construct the (initial and uploaded) index with layer0. let mut index = IndexPart::empty(TimelineMetadata::example()); index.layer_metadata.insert(layer0, metadata.clone()); // Construct the queue. let mut queue = UploadQueue::Uninitialized; let queue = queue.initialize_with_current_remote_index_part(&index, 0)?; // Populate inprogress_tasks with a bunch of layer1 deletions. let delete = UploadOp::Delete(Delete { layers: vec![(layer1, metadata)], }); for task_id in 0..(inprogress as u64) { queue.inprogress_tasks.insert( task_id, Arc::new(UploadTask { task_id, retries: AtomicU32::new(0), op: delete.clone(), coalesced_ops: Vec::new(), }), ); } // Benchmark index upload scheduling. let index_upload = UploadOp::UploadMetadata { uploaded: Box::new(index), }; b.iter(|| { queue.queued_operations.push_front(index_upload.clone()); assert!(queue.next_ready().is_some()); }); Ok(()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/benches/bench_layer_map.rs
pageserver/benches/bench_layer_map.rs
use std::cmp::{max, min}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use std::str::FromStr; use std::time::Instant; use criterion::measurement::WallTime; use criterion::{BenchmarkGroup, Criterion, black_box, criterion_group, criterion_main}; use pageserver::tenant::layer_map::LayerMap; use pageserver::tenant::storage_layer::{LayerName, PersistentLayerDesc}; use pageserver_api::key::Key; use pageserver_api::shard::TenantShardId; use rand::prelude::{SeedableRng, StdRng}; use rand::seq::IndexedRandom; use utils::id::{TenantId, TimelineId}; use utils::lsn::Lsn; fn fixture_path(relative: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative) } fn build_layer_map(filename_dump: PathBuf) -> LayerMap { let mut layer_map = LayerMap::default(); let mut min_lsn = Lsn(u64::MAX); let mut max_lsn = Lsn(0); let filenames = BufReader::new(File::open(filename_dump).unwrap()).lines(); let mut updates = layer_map.batch_update(); for fname in filenames { let fname = fname.unwrap(); let fname = LayerName::from_str(&fname).unwrap(); let layer = PersistentLayerDesc::from(fname); let lsn_range = layer.get_lsn_range(); min_lsn = min(min_lsn, lsn_range.start); max_lsn = max(max_lsn, Lsn(lsn_range.end.0 - 1)); updates.insert_historic(layer); } println!("min: {min_lsn}, max: {max_lsn}"); updates.flush(); layer_map } /// Construct a layer map query pattern for benchmarks fn uniform_query_pattern(layer_map: &LayerMap) -> Vec<(Key, Lsn)> { // For each image layer we query one of the pages contained, at LSN right // before the image layer was created. This gives us a somewhat uniform // coverage of both the lsn and key space because image layers have // approximately equal sizes and cover approximately equal WAL since // last image. layer_map .iter_historic_layers() .filter_map(|l| { if l.is_incremental() { None } else { let kr = l.get_key_range(); let lr = l.get_lsn_range(); let key_inside = kr.start.next(); let lsn_before = Lsn(lr.start.0 - 1); Some((key_inside, lsn_before)) } }) .collect() } // Benchmark using metadata extracted from our performance test environment, from // a project where we have run pgbench many timmes. The pgbench database was initialized // between each test run. fn bench_from_captest_env(c: &mut Criterion) { // TODO consider compressing this file let layer_map = build_layer_map(fixture_path("benches/odd-brook-layernames.txt")); let queries: Vec<(Key, Lsn)> = uniform_query_pattern(&layer_map); // Test with uniform query pattern c.bench_function("captest_uniform_queries", |b| { b.iter(|| { for q in queries.clone().into_iter() { black_box(layer_map.search(q.0, q.1)); } }); }); // test with a key that corresponds to the RelDir entry. See pgdatadir_mapping.rs. c.bench_function("captest_rel_dir_query", |b| { b.iter(|| { let result = black_box(layer_map.search( Key::from_hex("000000067F00008000000000000000000001").unwrap(), // This LSN is higher than any of the LSNs in the tree Lsn::from_str("D0/80208AE1").unwrap(), )); result.unwrap(); }); }); } // Benchmark using metadata extracted from a real project that was taknig // too long processing layer map queries. fn bench_from_real_project(c: &mut Criterion) { // Init layer map let now = Instant::now(); let layer_map = build_layer_map(fixture_path("benches/odd-brook-layernames.txt")); println!("Finished layer map init in {:?}", now.elapsed()); // Choose uniformly distributed queries let queries: Vec<(Key, Lsn)> = uniform_query_pattern(&layer_map); // Define and name the benchmark function let mut group = c.benchmark_group("real_map"); group.bench_function("uniform_queries", |b| { b.iter(|| { for q in queries.clone().into_iter() { black_box(layer_map.search(q.0, q.1)); } }); }); group.finish(); } // Benchmark using synthetic data. Arrange image layers on stacked diagonal lines. fn bench_sequential(c: &mut Criterion) { // Init layer map. Create 100_000 layers arranged in 1000 diagonal lines. // // TODO This code is pretty slow and runs even if we're only running other // benchmarks. It needs to be somewhere else, but it's not clear where. // Putting it inside the `bench_function` closure is not a solution // because then it runs multiple times during warmup. let now = Instant::now(); let mut layer_map = LayerMap::default(); let mut updates = layer_map.batch_update(); for i in 0..100_000 { let i32 = (i as u32) % 100; let zero = Key::from_hex("000000000000000000000000000000000000").unwrap(); let layer = PersistentLayerDesc::new_img( TenantShardId::unsharded(TenantId::generate()), TimelineId::generate(), zero.add(10 * i32)..zero.add(10 * i32 + 1), Lsn(i), 0, ); updates.insert_historic(layer); } updates.flush(); println!("Finished layer map init in {:?}", now.elapsed()); // Choose 100 uniformly random queries let rng = &mut StdRng::seed_from_u64(1); let queries: Vec<(Key, Lsn)> = uniform_query_pattern(&layer_map) .choose_multiple(rng, 100) .copied() .collect(); // Define and name the benchmark function let mut group = c.benchmark_group("sequential"); group.bench_function("uniform_queries", |b| { b.iter(|| { for q in queries.clone().into_iter() { black_box(layer_map.search(q.0, q.1)); } }); }); group.finish(); } fn bench_visibility_with_map( group: &mut BenchmarkGroup<WallTime>, layer_map: LayerMap, read_points: Vec<Lsn>, bench_name: &str, ) { group.bench_function(bench_name, |b| { b.iter(|| black_box(layer_map.get_visibility(read_points.clone()))); }); } // Benchmark using synthetic data. Arrange image layers on stacked diagonal lines. fn bench_visibility(c: &mut Criterion) { let mut group = c.benchmark_group("visibility"); { // Init layer map. Create 100_000 layers arranged in 1000 diagonal lines. let now = Instant::now(); let mut layer_map = LayerMap::default(); let mut updates = layer_map.batch_update(); for i in 0..100_000 { let i32 = (i as u32) % 100; let zero = Key::from_hex("000000000000000000000000000000000000").unwrap(); let layer = PersistentLayerDesc::new_img( TenantShardId::unsharded(TenantId::generate()), TimelineId::generate(), zero.add(10 * i32)..zero.add(10 * i32 + 1), Lsn(i), 0, ); updates.insert_historic(layer); } updates.flush(); println!("Finished layer map init in {:?}", now.elapsed()); let mut read_points = Vec::new(); for i in (0..100_000).step_by(1000) { read_points.push(Lsn(i)); } bench_visibility_with_map(&mut group, layer_map, read_points, "sequential"); } { let layer_map = build_layer_map(fixture_path("benches/odd-brook-layernames.txt")); let read_points = vec![Lsn(0x1C760FA190)]; bench_visibility_with_map(&mut group, layer_map, read_points, "real_map"); let layer_map = build_layer_map(fixture_path("benches/odd-brook-layernames.txt")); let read_points = vec![ Lsn(0x1C760FA190), Lsn(0x000000931BEAD539), Lsn(0x000000931BF63011), Lsn(0x000000931B33AE68), Lsn(0x00000038E67ABFA0), Lsn(0x000000931B33AE68), Lsn(0x000000914E3F38F0), Lsn(0x000000931B33AE68), ]; bench_visibility_with_map(&mut group, layer_map, read_points, "real_map_many_branches"); } group.finish(); } criterion_group!(group_1, bench_from_captest_env); criterion_group!(group_2, bench_from_real_project); criterion_group!(group_3, bench_sequential); criterion_group!(group_4, bench_visibility); criterion_main!(group_1, group_2, group_3, group_4);
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/lib.rs
pageserver/compaction/src/lib.rs
// The main module implementing the compaction algorithm pub mod compact_tiered; pub(crate) mod identify_levels; // Traits that the caller of the compaction needs to implement pub mod interface; // Utility functions, useful for the implementation pub mod helpers; // A simulator with mock implementations of 'interface' pub mod simulator;
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/interface.rs
pageserver/compaction/src/interface.rs
//! This is what the compaction implementation needs to know about //! layers, keyspace etc. //! //! All the heavy lifting is done by the create_image and create_delta //! functions that the implementor provides. use std::ops::Range; use futures::Future; use pageserver_api::key::Key; use pageserver_api::keyspace::ShardedRange; use pageserver_api::shard::ShardIdentity; use utils::lsn::Lsn; /// Public interface. This is the main thing that the implementor needs to provide pub trait CompactionJobExecutor { // Type system. // // We assume that there are two kinds of layers, deltas and images. The // compaction doesn't distinguish whether they are stored locally or // remotely. // // The keyspace is defined by the CompactionKey trait. type Key: CompactionKey; type Layer: CompactionLayer<Self::Key> + Clone; type DeltaLayer: CompactionDeltaLayer<Self> + Clone; type ImageLayer: CompactionImageLayer<Self> + Clone; // This is passed through to all the interface functions. The compaction // implementation doesn't do anything with it, but it might be useful for // the interface implementation. type RequestContext: CompactionRequestContext; // ---- // Functions that the planner uses to support its decisions // ---- fn get_shard_identity(&self) -> &ShardIdentity; /// Return all layers that overlap the given bounding box. fn get_layers( &mut self, key_range: &Range<Self::Key>, lsn_range: &Range<Lsn>, ctx: &Self::RequestContext, ) -> impl Future<Output = anyhow::Result<Vec<Self::Layer>>> + Send; fn get_keyspace( &mut self, key_range: &Range<Self::Key>, lsn: Lsn, ctx: &Self::RequestContext, ) -> impl Future<Output = anyhow::Result<CompactionKeySpace<Self::Key>>> + Send; /// NB: This is a pretty expensive operation. In the real pageserver /// implementation, it downloads the layer, and keeps it resident /// until the DeltaLayer is dropped. fn downcast_delta_layer( &self, layer: &Self::Layer, ctx: &Self::RequestContext, ) -> impl Future<Output = anyhow::Result<Option<Self::DeltaLayer>>> + Send; // ---- // Functions to execute the plan // ---- /// Create a new image layer, materializing all the values in the key range, /// at given 'lsn'. fn create_image( &mut self, lsn: Lsn, key_range: &Range<Self::Key>, ctx: &Self::RequestContext, ) -> impl Future<Output = anyhow::Result<()>> + Send; /// Create a new delta layer, containing all the values from 'input_layers' /// in the given key and LSN range. fn create_delta( &mut self, lsn_range: &Range<Lsn>, key_range: &Range<Self::Key>, input_layers: &[Self::DeltaLayer], ctx: &Self::RequestContext, ) -> impl Future<Output = anyhow::Result<()>> + Send; /// Delete a layer. The compaction implementation will call this only after /// all the create_image() or create_delta() calls that deletion of this /// layer depends on have finished. But if the implementor has extra lazy /// background tasks, like uploading the index json file to remote storage. /// it is the implementation's responsibility to track those. fn delete_layer( &mut self, layer: &Self::Layer, ctx: &Self::RequestContext, ) -> impl Future<Output = anyhow::Result<()>> + Send; } pub trait CompactionKey: std::cmp::Ord + Clone + Copy + std::fmt::Display { const MIN: Self; const MAX: Self; /// Calculate distance between key_range.start and key_range.end. /// /// This returns u32, for compatibility with Repository::key. If the /// distance is larger, return u32::MAX. fn key_range_size(key_range: &Range<Self>, shard_identity: &ShardIdentity) -> u32; // return "self + 1" fn next(&self) -> Self; // return "self + <some decent amount to skip>". The amount to skip // is left to the implementation. // FIXME: why not just "add(u32)" ? This is hard to use fn skip_some(&self) -> Self; } impl CompactionKey for Key { const MIN: Self = Self::MIN; const MAX: Self = Self::MAX; fn key_range_size(r: &std::ops::Range<Self>, shard_identity: &ShardIdentity) -> u32 { ShardedRange::new(r.clone(), shard_identity).page_count() } fn next(&self) -> Key { (self as &Key).next() } fn skip_some(&self) -> Key { self.add(128) } } /// Contiguous ranges of keys that belong to the key space. In key order, and /// with no overlap. pub type CompactionKeySpace<K> = Vec<Range<K>>; /// Functions needed from all layers. pub trait CompactionLayer<K: CompactionKey> { fn key_range(&self) -> &Range<K>; fn lsn_range(&self) -> &Range<Lsn>; fn file_size(&self) -> u64; /// For debugging, short human-readable representation of the layer. E.g. filename. fn short_id(&self) -> String; fn is_delta(&self) -> bool; } pub trait CompactionDeltaLayer<E: CompactionJobExecutor + ?Sized>: CompactionLayer<E::Key> { type DeltaEntry<'a>: CompactionDeltaEntry<'a, E::Key> where Self: 'a; /// Return all keys in this delta layer. fn load_keys( &self, ctx: &E::RequestContext, ) -> impl Future<Output = anyhow::Result<Vec<Self::DeltaEntry<'_>>>> + Send; } pub trait CompactionImageLayer<E: CompactionJobExecutor + ?Sized>: CompactionLayer<E::Key> {} pub trait CompactionDeltaEntry<'a, K> { fn key(&self) -> K; fn lsn(&self) -> Lsn; fn size(&self) -> u64; } pub trait CompactionRequestContext {}
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/helpers.rs
pageserver/compaction/src/helpers.rs
//! This file contains generic utility functions over the interface types, //! which could be handy for any compaction implementation. use std::collections::{BinaryHeap, VecDeque}; use std::fmt::Display; use std::future::Future; use std::ops::{DerefMut, Range}; use std::pin::Pin; use std::task::{Poll, ready}; use futures::future::BoxFuture; use futures::{Stream, StreamExt}; use itertools::Itertools; use pageserver_api::shard::ShardIdentity; use pin_project_lite::pin_project; use utils::lsn::Lsn; use crate::interface::*; pub const PAGE_SZ: u64 = 8192; pub fn keyspace_total_size<K>( keyspace: &CompactionKeySpace<K>, shard_identity: &ShardIdentity, ) -> u64 where K: CompactionKey, { keyspace .iter() .map(|r| K::key_range_size(r, shard_identity) as u64) .sum() } pub fn overlaps_with<T: Ord>(a: &Range<T>, b: &Range<T>) -> bool { !(a.end <= b.start || b.end <= a.start) } /// Whether a fully contains b, example as below /// ```plain /// | a | /// | b | /// ``` pub fn fully_contains<T: Ord>(a: &Range<T>, b: &Range<T>) -> bool { a.start <= b.start && a.end >= b.end } pub fn union_to_keyspace<K: Ord>(a: &mut CompactionKeySpace<K>, b: CompactionKeySpace<K>) { let x = std::mem::take(a); let mut all_ranges_iter = [x.into_iter(), b.into_iter()] .into_iter() .kmerge_by(|a, b| a.start < b.start); let mut ranges = Vec::new(); if let Some(first) = all_ranges_iter.next() { let (mut start, mut end) = (first.start, first.end); for r in all_ranges_iter { assert!(r.start >= start); if r.start > end { ranges.push(start..end); start = r.start; end = r.end; } else if r.end > end { end = r.end; } } ranges.push(start..end); } *a = ranges } pub fn intersect_keyspace<K: Ord + Clone + Copy>( a: &CompactionKeySpace<K>, r: &Range<K>, ) -> CompactionKeySpace<K> { let mut ranges: Vec<Range<K>> = Vec::new(); for x in a.iter() { if x.end <= r.start { continue; } if x.start >= r.end { break; } ranges.push(x.clone()) } // trim the ends if let Some(first) = ranges.first_mut() { first.start = std::cmp::max(first.start, r.start); } if let Some(last) = ranges.last_mut() { last.end = std::cmp::min(last.end, r.end); } ranges } /// Create a stream that iterates through all DeltaEntrys among all input /// layers, in key-lsn order. /// /// This is public because the create_delta() implementation likely wants to use this too /// TODO: move to a more shared place pub fn merge_delta_keys<'a, E: CompactionJobExecutor>( layers: &'a [E::DeltaLayer], ctx: &'a E::RequestContext, ) -> MergeDeltaKeys<'a, E> { // Use a binary heap to merge the layers. Each input layer is initially // represented by a LazyLoadLayer::Unloaded element, which uses the start of // the layer's key range as the key. The first time a layer reaches the top // of the heap, all the keys of the layer are loaded into a sorted vector. // // This helps to keep the memory usage reasonable: we only need to hold in // memory the DeltaEntrys of the layers that overlap with the "current" key. let mut heap: BinaryHeap<LazyLoadLayer<'a, E>> = BinaryHeap::new(); for l in layers { heap.push(LazyLoadLayer::Unloaded(l)); } MergeDeltaKeys { heap, ctx, load_future: None, } } pub async fn merge_delta_keys_buffered<'a, E: CompactionJobExecutor + 'a>( layers: &'a [E::DeltaLayer], ctx: &'a E::RequestContext, ) -> anyhow::Result<impl Stream<Item = <E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>> { let mut keys = Vec::new(); for l in layers { // Boxing and casting to LoadFuture is required to obtain the right Sync bound. // If we do l.load_keys(ctx).await? directly, there is a compilation error. let load_future: LoadFuture<'a, _> = Box::pin(l.load_keys(ctx)); keys.extend(load_future.await?.into_iter()); } keys.sort_by_key(|k| (k.key(), k.lsn())); let stream = futures::stream::iter(keys.into_iter()); Ok(stream) } enum LazyLoadLayer<'a, E: CompactionJobExecutor> { Loaded(VecDeque<<E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>), Unloaded(&'a E::DeltaLayer), } impl<E: CompactionJobExecutor> LazyLoadLayer<'_, E> { fn min_key(&self) -> E::Key { match self { Self::Loaded(entries) => entries.front().unwrap().key(), Self::Unloaded(dl) => dl.key_range().start, } } fn min_lsn(&self) -> Lsn { match self { Self::Loaded(entries) => entries.front().unwrap().lsn(), Self::Unloaded(dl) => dl.lsn_range().start, } } } impl<E: CompactionJobExecutor> PartialOrd for LazyLoadLayer<'_, E> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl<E: CompactionJobExecutor> Ord for LazyLoadLayer<'_, E> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { // reverse order so that we get a min-heap (other.min_key(), other.min_lsn()).cmp(&(self.min_key(), self.min_lsn())) } } impl<E: CompactionJobExecutor> PartialEq for LazyLoadLayer<'_, E> { fn eq(&self, other: &Self) -> bool { self.cmp(other) == std::cmp::Ordering::Equal } } impl<E: CompactionJobExecutor> Eq for LazyLoadLayer<'_, E> {} type LoadFuture<'a, E> = BoxFuture<'a, anyhow::Result<Vec<E>>>; // Stream returned by `merge_delta_keys` pin_project! { #[allow(clippy::type_complexity)] pub struct MergeDeltaKeys<'a, E: CompactionJobExecutor> { heap: BinaryHeap<LazyLoadLayer<'a, E>>, #[pin] load_future: Option<LoadFuture<'a, <E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>>, ctx: &'a E::RequestContext, } } impl<'a, E> Stream for MergeDeltaKeys<'a, E> where E: CompactionJobExecutor + 'a, { type Item = anyhow::Result<<E::DeltaLayer as CompactionDeltaLayer<E>>::DeltaEntry<'a>>; fn poll_next( self: Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> Poll<std::option::Option<<Self as futures::Stream>::Item>> { let mut this = self.project(); loop { if let Some(mut load_future) = this.load_future.as_mut().as_pin_mut() { // We are waiting for loading the keys to finish match ready!(load_future.as_mut().poll(cx)) { Ok(entries) => { this.load_future.set(None); *this.heap.peek_mut().unwrap() = LazyLoadLayer::Loaded(VecDeque::from(entries)); } Err(e) => { return Poll::Ready(Some(Err(e))); } } } // If the topmost layer in the heap hasn't been loaded yet, start // loading it. Otherwise return the next entry from it and update // the layer's position in the heap (this decreaseKey operation is // performed implicitly when `top` is dropped). if let Some(mut top) = this.heap.peek_mut() { match top.deref_mut() { LazyLoadLayer::Unloaded(l) => { let fut = l.load_keys(this.ctx); this.load_future.set(Some(Box::pin(fut))); continue; } LazyLoadLayer::Loaded(entries) => { let result = entries.pop_front().unwrap(); if entries.is_empty() { std::collections::binary_heap::PeekMut::pop(top); } return Poll::Ready(Some(Ok(result))); } } } else { return Poll::Ready(None); } } } } // Accumulate values at key boundaries pub struct KeySize<K> { pub key: K, pub num_values: u64, pub size: u64, /// The lsns to partition at (if empty then no per-lsn partitioning) pub partition_lsns: Vec<(Lsn, u64)>, } pub fn accum_key_values<'a, I, K, D, E>( input: I, target_size: u64, ) -> impl Stream<Item = Result<KeySize<K>, E>> where K: Eq + PartialOrd + Display + Copy, I: Stream<Item = Result<D, E>>, D: CompactionDeltaEntry<'a, K>, { async_stream::try_stream! { // Initialize the state from the first value let mut input = std::pin::pin!(input); if let Some(first) = input.next().await { let first = first?; let mut part_size = first.size(); let mut accum: KeySize<K> = KeySize { key: first.key(), num_values: 1, size: part_size, partition_lsns: Vec::new(), }; let mut last_key = accum.key; while let Some(this) = input.next().await { let this = this?; if this.key() == accum.key { let add_size = this.size(); if part_size + add_size > target_size { accum.partition_lsns.push((this.lsn(), part_size)); part_size = 0; } part_size += add_size; accum.size += add_size; accum.num_values += 1; } else { assert!(last_key <= accum.key, "last_key={last_key} <= accum.key={}", accum.key); last_key = accum.key; yield accum; part_size = this.size(); accum = KeySize { key: this.key(), num_values: 1, size: part_size, partition_lsns: Vec::new(), }; } } assert!(last_key <= accum.key, "last_key={last_key} <= accum.key={}", accum.key); yield accum; } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/identify_levels.rs
pageserver/compaction/src/identify_levels.rs
//! An LSM tree consists of multiple levels, each exponentially larger than the //! previous level. And each level consists of multiple "tiers". With tiered //! compaction, a level is compacted when it has accumulated more than N tiers, //! forming one tier on the next level. //! //! In the pageserver, we don't explicitly track the levels and tiers. Instead, //! we identify them by looking at the shapes of the layers. It's an easy task //! for a human, but it's not straightforward to come up with the exact //! rules. Especially if there are cases like interrupted, half-finished //! compactions, or highly skewed data distributions that have let us "skip" //! some levels. It's not critical to classify all cases correctly; at worst we //! delay some compaction work, and suffer from more read amplification, or we //! perform some unnecessary compaction work. //! //! `identify_level` performs that shape-matching. //! //! It returns a Level struct, which has `depth()` function to count the number //! of "tiers" in the level. The tier count is the max depth of stacked layers //! within the level. That's a good measure, because the point of compacting is //! to reduce read amplification, and the depth is what determines that. //! //! One interesting effect of this is that if we generate very small delta //! layers at L0, e.g. because the L0 layers are flushed by timeout rather than //! because they reach the target size, the L0 compaction will combine them to //! one larger file. But if the combined file is still smaller than the target //! file size, the file will still be considered to be part of L0 at the next //! iteration. use std::collections::BTreeSet; use std::ops::Range; use anyhow::bail; use tracing::{info, trace}; use utils::lsn::Lsn; use crate::interface::*; pub struct Level<L> { pub lsn_range: Range<Lsn>, pub layers: Vec<L>, } /// Identify an LSN > `end_lsn` that partitions the LSN space, so that there are /// no layers that cross the boundary LSN. /// /// A further restriction is that all layers in the returned partition cover at /// most 'lsn_max_size' LSN bytes. pub async fn identify_level<K, L>( all_layers: Vec<L>, end_lsn: Lsn, lsn_max_size: u64, ) -> anyhow::Result<Option<Level<L>>> where K: CompactionKey, L: CompactionLayer<K> + Clone, { // filter out layers that are above the `end_lsn`, they are completely irrelevant. let mut layers = Vec::new(); for l in all_layers { if l.lsn_range().start < end_lsn && l.lsn_range().end > end_lsn { // shouldn't happen. Indicates that the caller passed a bogus // end_lsn. bail!( "identify_level() called with end_lsn that does not partition the LSN space: end_lsn {} intersects with layer {}", end_lsn, l.short_id() ); } // include image layers sitting exacty at `end_lsn`. let is_image = !l.is_delta(); if (is_image && l.lsn_range().start > end_lsn) || (!is_image && l.lsn_range().start >= end_lsn) { continue; } layers.push(l); } // All the remaining layers either belong to this level, or are below it. info!( "identify level at {}, size {}, num layers below: {}", end_lsn, lsn_max_size, layers.len() ); if layers.is_empty() { return Ok(None); } // Walk the ranges in LSN order. // // ----- end_lsn // | // | // v // layers.sort_by_key(|l| l.lsn_range().end); let mut candidate_start_lsn = end_lsn; let mut candidate_layers: Vec<L> = Vec::new(); let mut current_best_start_lsn = end_lsn; let mut current_best_layers: Vec<L> = Vec::new(); let mut iter = layers.into_iter(); loop { let Some(l) = iter.next_back() else { // Reached end. Accept the last candidate current_best_start_lsn = candidate_start_lsn; current_best_layers.extend_from_slice(&std::mem::take(&mut candidate_layers)); break; }; trace!( "inspecting {} for candidate {}, current best {}", l.short_id(), candidate_start_lsn, current_best_start_lsn ); let r = l.lsn_range(); // Image layers don't restrict our choice of cutoff LSN if l.is_delta() { // Is this candidate workable? In other words, are there any // delta layers that span across this LSN // // Valid: Not valid: // + + // | | + // + <- candidate + | <- candidate // + + // | // + if r.end <= candidate_start_lsn { // Hooray, there are no crossing LSNs. And we have visited // through all the layers within candidate..end_lsn. The // current candidate can be accepted. current_best_start_lsn = r.end; current_best_layers.extend_from_slice(&std::mem::take(&mut candidate_layers)); candidate_start_lsn = r.start; } // Is it small enough to be considered part of this level? if r.end.0 - r.start.0 > lsn_max_size { // Too large, this layer belongs to next level. Stop. trace!( "too large {}, size {} vs {}", l.short_id(), r.end.0 - r.start.0, lsn_max_size ); break; } // If this crosses the candidate lsn, push it down. if r.start < candidate_start_lsn { trace!( "layer {} prevents from stopping at {}", l.short_id(), candidate_start_lsn ); candidate_start_lsn = r.start; } } // Include this layer in our candidate candidate_layers.push(l); } Ok(if current_best_start_lsn == end_lsn { // empty level None } else { Some(Level { lsn_range: current_best_start_lsn..end_lsn, layers: current_best_layers, }) }) } impl<L> Level<L> { /// Count the number of deltas stacked on each other. pub fn depth<K>(&self) -> u64 where K: CompactionKey, L: CompactionLayer<K>, { struct Event<K> { key: K, layer_idx: usize, start: bool, } let mut events: Vec<Event<K>> = Vec::new(); for (idx, l) in self.layers.iter().enumerate() { let key_range = l.key_range(); if key_range.end == key_range.start.next() && l.is_delta() { // Ignore single-key delta layers as they can be stacked on top of each other // as that is the only way to cut further. continue; } events.push(Event { key: l.key_range().start, layer_idx: idx, start: true, }); events.push(Event { key: l.key_range().end, layer_idx: idx, start: false, }); } events.sort_by_key(|e| (e.key, e.start)); // Sweep the key space left to right. Stop at each distinct key, and // count the number of deltas on top of the highest image at that key. // // This is a little inefficient, as we walk through the active_set on // every key. We could increment/decrement a counter on each step // instead, but that'd require a bit more complex bookkeeping. let mut active_set: BTreeSet<(Lsn, bool, usize)> = BTreeSet::new(); let mut max_depth = 0; let mut events_iter = events.iter().peekable(); while let Some(e) = events_iter.next() { let l = &self.layers[e.layer_idx]; let is_image = !l.is_delta(); // update the active set if e.start { active_set.insert((l.lsn_range().end, is_image, e.layer_idx)); } else { active_set.remove(&(l.lsn_range().end, is_image, e.layer_idx)); } // recalculate depth if this was the last event at this point let more_events_at_this_key = events_iter.peek().is_some_and(|next_e| next_e.key == e.key); if !more_events_at_this_key { let mut active_depth = 0; for (_end_lsn, is_image, _idx) in active_set.iter().rev() { if *is_image { break; } active_depth += 1; } if active_depth > max_depth { max_depth = active_depth; } } } debug_assert_eq!(active_set, BTreeSet::new()); max_depth } } #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; use super::*; use crate::simulator::{Key, MockDeltaLayer, MockImageLayer, MockLayer}; fn delta(key_range: Range<Key>, lsn_range: Range<Lsn>) -> MockLayer { MockLayer::Delta(Arc::new(MockDeltaLayer { key_range, lsn_range, // identify_level() doesn't pay attention to the rest of the fields file_size: 0, deleted: Mutex::new(false), records: vec![], })) } fn image(key_range: Range<Key>, lsn: Lsn) -> MockLayer { MockLayer::Image(Arc::new(MockImageLayer { key_range, lsn_range: lsn..(lsn + 1), // identify_level() doesn't pay attention to the rest of the fields file_size: 0, deleted: Mutex::new(false), })) } #[tokio::test] async fn test_identify_level() -> anyhow::Result<()> { let layers = vec![ delta(Key::MIN..Key::MAX, Lsn(0x8000)..Lsn(0x9000)), delta(Key::MIN..Key::MAX, Lsn(0x5000)..Lsn(0x7000)), delta(Key::MIN..Key::MAX, Lsn(0x4000)..Lsn(0x5000)), delta(Key::MIN..Key::MAX, Lsn(0x3000)..Lsn(0x4000)), delta(Key::MIN..Key::MAX, Lsn(0x2000)..Lsn(0x3000)), delta(Key::MIN..Key::MAX, Lsn(0x1000)..Lsn(0x2000)), ]; // All layers fit in the max file size let level = identify_level(layers.clone(), Lsn(0x10000), 0x2000) .await? .unwrap(); assert_eq!(level.depth(), 6); // Same LSN with smaller max file size. The second layer from the top is larger // and belongs to next level. let level = identify_level(layers.clone(), Lsn(0x10000), 0x1000) .await? .unwrap(); assert_eq!(level.depth(), 1); // Call with a smaller LSN let level = identify_level(layers.clone(), Lsn(0x3000), 0x1000) .await? .unwrap(); assert_eq!(level.depth(), 2); // Call with an LSN that doesn't partition the space let result = identify_level(layers, Lsn(0x6000), 0x1000).await; assert!(result.is_err()); Ok(()) } #[tokio::test] async fn test_overlapping_lsn_ranges() -> anyhow::Result<()> { // The files LSN ranges overlap, so even though there are more files that // fit under the file size, they are not included in the level because they // overlap so that we'd need to include the oldest file, too, which is // larger let layers = vec![ delta(Key::MIN..Key::MAX, Lsn(0x4000)..Lsn(0x5000)), delta(Key::MIN..Key::MAX, Lsn(0x3000)..Lsn(0x4000)), // overlap delta(Key::MIN..Key::MAX, Lsn(0x2500)..Lsn(0x3500)), // overlap delta(Key::MIN..Key::MAX, Lsn(0x2000)..Lsn(0x3000)), // overlap delta(Key::MIN..Key::MAX, Lsn(0x1000)..Lsn(0x2500)), // larger ]; let level = identify_level(layers.clone(), Lsn(0x10000), 0x1000) .await? .unwrap(); assert_eq!(level.depth(), 1); Ok(()) } #[tokio::test] async fn test_depth_nonoverlapping() -> anyhow::Result<()> { // The key ranges don't overlap, so depth is only 1. let layers = vec![ delta(4000..5000, Lsn(0x6000)..Lsn(0x7000)), delta(3000..4000, Lsn(0x7000)..Lsn(0x8000)), delta(1000..2000, Lsn(0x8000)..Lsn(0x9000)), ]; let level = identify_level(layers.clone(), Lsn(0x10000), 0x2000) .await? .unwrap(); assert_eq!(level.layers.len(), 3); assert_eq!(level.depth(), 1); // Staggered. The 1st and 3rd layer don't overlap with each other. let layers = vec![ delta(1000..2000, Lsn(0x8000)..Lsn(0x9000)), delta(1500..2500, Lsn(0x7000)..Lsn(0x8000)), delta(2000..3000, Lsn(0x6000)..Lsn(0x7000)), ]; let level = identify_level(layers.clone(), Lsn(0x10000), 0x2000) .await? .unwrap(); assert_eq!(level.layers.len(), 3); assert_eq!(level.depth(), 2); Ok(()) } #[tokio::test] async fn test_depth_images() -> anyhow::Result<()> { let layers: Vec<MockLayer> = vec![ delta(1000..2000, Lsn(0x8000)..Lsn(0x9000)), delta(1500..2500, Lsn(0x7000)..Lsn(0x8000)), delta(2000..3000, Lsn(0x6000)..Lsn(0x7000)), // This covers the same key range as the 2nd delta layer. The depth // in that key range is therefore 0. image(1500..2500, Lsn(0x9000)), ]; let level = identify_level(layers.clone(), Lsn(0x10000), 0x2000) .await? .unwrap(); assert_eq!(level.layers.len(), 4); assert_eq!(level.depth(), 1); Ok(()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/simulator.rs
pageserver/compaction/src/simulator.rs
mod draw; use std::fmt::Write; use std::ops::Range; use std::sync::{Arc, Mutex}; use draw::{LayerTraceEvent, LayerTraceFile, LayerTraceOp}; use futures::StreamExt; use pageserver_api::shard::ShardIdentity; use rand::Rng; use tracing::info; use utils::lsn::Lsn; use crate::helpers::{PAGE_SZ, merge_delta_keys, overlaps_with}; use crate::interface; use crate::interface::CompactionLayer; // // Implementation for the CompactionExecutor interface // pub struct MockTimeline { // Parameters for the compaction algorithm pub target_file_size: u64, tiers_per_level: u64, num_l0_flushes: u64, last_compact_at_flush: u64, last_flush_lsn: Lsn, // In-memory layer records: Vec<MockRecord>, total_len: u64, start_lsn: Lsn, end_lsn: Lsn, // Current keyspace at `end_lsn`. This is updated on every ingested record. keyspace: KeySpace, // historic keyspaces old_keyspaces: Vec<(Lsn, KeySpace)>, // "on-disk" layers pub live_layers: Vec<MockLayer>, num_deleted_layers: u64, // Statistics wal_ingested: u64, bytes_written: u64, bytes_deleted: u64, layers_created: u64, layers_deleted: u64, // All the events - creation and deletion of files - are collected // in 'history'. It is used to draw the SVG animation at the end. time: u64, history: Vec<draw::LayerTraceEvent>, } type KeySpace = interface::CompactionKeySpace<Key>; pub struct MockRequestContext {} impl interface::CompactionRequestContext for MockRequestContext {} pub type Key = u64; impl interface::CompactionKey for Key { const MIN: Self = u64::MIN; const MAX: Self = u64::MAX; fn key_range_size(key_range: &Range<Self>, _shard_identity: &ShardIdentity) -> u32 { std::cmp::min(key_range.end - key_range.start, u32::MAX as u64) as u32 } fn next(&self) -> Self { self + 1 } fn skip_some(&self) -> Self { // round up to next xx self + 100 } } #[derive(Clone)] pub struct MockRecord { lsn: Lsn, key: Key, len: u64, } impl interface::CompactionDeltaEntry<'_, Key> for MockRecord { fn key(&self) -> Key { self.key } fn lsn(&self) -> Lsn { self.lsn } fn size(&self) -> u64 { self.len } } pub struct MockDeltaLayer { pub key_range: Range<Key>, pub lsn_range: Range<Lsn>, pub file_size: u64, pub deleted: Mutex<bool>, pub records: Vec<MockRecord>, } impl interface::CompactionLayer<Key> for Arc<MockDeltaLayer> { fn key_range(&self) -> &Range<Key> { &self.key_range } fn lsn_range(&self) -> &Range<Lsn> { &self.lsn_range } fn file_size(&self) -> u64 { self.file_size } fn short_id(&self) -> String { format!( "{:016X}-{:016X}__{:08X}-{:08X}", self.key_range.start, self.key_range.end, self.lsn_range.start.0, self.lsn_range.end.0 ) } fn is_delta(&self) -> bool { true } } impl interface::CompactionDeltaLayer<MockTimeline> for Arc<MockDeltaLayer> { type DeltaEntry<'a> = MockRecord; async fn load_keys(&self, _ctx: &MockRequestContext) -> anyhow::Result<Vec<MockRecord>> { Ok(self.records.clone()) } } pub struct MockImageLayer { pub key_range: Range<Key>, pub lsn_range: Range<Lsn>, pub file_size: u64, pub deleted: Mutex<bool>, } impl interface::CompactionImageLayer<MockTimeline> for Arc<MockImageLayer> {} impl interface::CompactionLayer<Key> for Arc<MockImageLayer> { fn key_range(&self) -> &Range<Key> { &self.key_range } fn lsn_range(&self) -> &Range<Lsn> { &self.lsn_range } fn file_size(&self) -> u64 { self.file_size } fn short_id(&self) -> String { format!( "{:016X}-{:016X}__{:08X}", self.key_range.start, self.key_range.end, self.lsn_range.start.0, ) } fn is_delta(&self) -> bool { false } } impl MockTimeline { pub fn new() -> Self { MockTimeline { target_file_size: 256 * 1024 * 1024, tiers_per_level: 4, num_l0_flushes: 0, last_compact_at_flush: 0, last_flush_lsn: Lsn(0), records: Vec::new(), total_len: 0, start_lsn: Lsn(1000), end_lsn: Lsn(1000), keyspace: KeySpace::new(), old_keyspaces: vec![], live_layers: vec![], num_deleted_layers: 0, wal_ingested: 0, bytes_written: 0, bytes_deleted: 0, layers_created: 0, layers_deleted: 0, time: 0, history: Vec::new(), } } pub async fn compact(&mut self) -> anyhow::Result<()> { let ctx = MockRequestContext {}; crate::compact_tiered::compact_tiered( self, self.last_flush_lsn, self.target_file_size, self.tiers_per_level, &ctx, ) .await?; Ok(()) } // Ingest one record to the timeline pub fn ingest_record(&mut self, key: Key, len: u64) { self.records.push(MockRecord { lsn: self.end_lsn, key, len, }); self.total_len += len; self.end_lsn += len; if self.total_len > self.target_file_size { self.flush_l0(); } } pub async fn compact_if_needed(&mut self) -> anyhow::Result<()> { if self.num_l0_flushes - self.last_compact_at_flush >= self.tiers_per_level { self.compact().await?; self.last_compact_at_flush = self.num_l0_flushes; } Ok(()) } pub fn flush_l0(&mut self) { if self.records.is_empty() { return; } let mut records = std::mem::take(&mut self.records); records.sort_by_key(|rec| rec.key); let lsn_range = self.start_lsn..self.end_lsn; let new_layer = Arc::new(MockDeltaLayer { key_range: Key::MIN..Key::MAX, lsn_range: lsn_range.clone(), file_size: self.total_len, records, deleted: Mutex::new(false), }); info!("flushed L0 layer {}", new_layer.short_id()); self.live_layers.push(MockLayer::from(&new_layer)); // reset L0 self.start_lsn = self.end_lsn; self.total_len = 0; self.records = Vec::new(); self.layers_created += 1; self.bytes_written += new_layer.file_size; self.time += 1; self.history.push(LayerTraceEvent { time_rel: self.time, op: LayerTraceOp::Flush, file: LayerTraceFile { filename: new_layer.short_id(), key_range: new_layer.key_range.clone(), lsn_range: new_layer.lsn_range.clone(), }, }); self.num_l0_flushes += 1; self.last_flush_lsn = self.end_lsn; } // Ingest `num_records' records to the timeline, with random keys // uniformly distributed in `key_range` pub fn ingest_uniform( &mut self, num_records: u64, len: u64, key_range: &Range<Key>, ) -> anyhow::Result<()> { crate::helpers::union_to_keyspace(&mut self.keyspace, vec![key_range.clone()]); let mut rng = rand::rng(); for _ in 0..num_records { self.ingest_record(rng.random_range(key_range.clone()), len); self.wal_ingested += len; } Ok(()) } pub fn stats(&self) -> anyhow::Result<String> { let mut s = String::new(); writeln!(s, "STATISTICS:")?; writeln!( s, "WAL ingested: {:>10} MB", self.wal_ingested / (1024 * 1024) )?; writeln!( s, "size created: {:>10} MB", self.bytes_written / (1024 * 1024) )?; writeln!( s, "size deleted: {:>10} MB", self.bytes_deleted / (1024 * 1024) )?; writeln!(s, "files created: {:>10}", self.layers_created)?; writeln!(s, "files deleted: {:>10}", self.layers_deleted)?; writeln!( s, "write amp: {:>10.2}", self.bytes_written as f64 / self.wal_ingested as f64 )?; writeln!( s, "storage amp: {:>10.2}", (self.bytes_written - self.bytes_deleted) as f64 / self.wal_ingested as f64 )?; Ok(s) } pub fn draw_history<W: std::io::Write>(&self, output: W) -> anyhow::Result<()> { draw::draw_history(&self.history, output) } } impl Default for MockTimeline { fn default() -> Self { Self::new() } } #[derive(Clone)] pub enum MockLayer { Delta(Arc<MockDeltaLayer>), Image(Arc<MockImageLayer>), } impl interface::CompactionLayer<Key> for MockLayer { fn key_range(&self) -> &Range<Key> { match self { MockLayer::Delta(this) => this.key_range(), MockLayer::Image(this) => this.key_range(), } } fn lsn_range(&self) -> &Range<Lsn> { match self { MockLayer::Delta(this) => this.lsn_range(), MockLayer::Image(this) => this.lsn_range(), } } fn file_size(&self) -> u64 { match self { MockLayer::Delta(this) => this.file_size, MockLayer::Image(this) => this.file_size, } } fn short_id(&self) -> String { match self { MockLayer::Delta(this) => this.short_id(), MockLayer::Image(this) => this.short_id(), } } fn is_delta(&self) -> bool { match self { MockLayer::Delta(_) => true, MockLayer::Image(_) => false, } } } impl MockLayer { fn is_deleted(&self) -> bool { let guard = match self { MockLayer::Delta(this) => this.deleted.lock().unwrap(), MockLayer::Image(this) => this.deleted.lock().unwrap(), }; *guard } fn mark_deleted(&self) { let mut deleted_guard = match self { MockLayer::Delta(this) => this.deleted.lock().unwrap(), MockLayer::Image(this) => this.deleted.lock().unwrap(), }; assert!(!*deleted_guard, "layer already deleted"); *deleted_guard = true; } } impl From<&Arc<MockDeltaLayer>> for MockLayer { fn from(l: &Arc<MockDeltaLayer>) -> Self { MockLayer::Delta(l.clone()) } } impl From<&Arc<MockImageLayer>> for MockLayer { fn from(l: &Arc<MockImageLayer>) -> Self { MockLayer::Image(l.clone()) } } impl interface::CompactionJobExecutor for MockTimeline { type Key = Key; type Layer = MockLayer; type DeltaLayer = Arc<MockDeltaLayer>; type ImageLayer = Arc<MockImageLayer>; type RequestContext = MockRequestContext; fn get_shard_identity(&self) -> &ShardIdentity { static IDENTITY: ShardIdentity = ShardIdentity::unsharded(); &IDENTITY } async fn get_layers( &mut self, key_range: &Range<Self::Key>, lsn_range: &Range<Lsn>, _ctx: &Self::RequestContext, ) -> anyhow::Result<Vec<Self::Layer>> { // Clear any deleted layers from our vec self.live_layers.retain(|l| !l.is_deleted()); let layers: Vec<MockLayer> = self .live_layers .iter() .filter(|l| { overlaps_with(l.lsn_range(), lsn_range) && overlaps_with(l.key_range(), key_range) }) .cloned() .collect(); Ok(layers) } async fn get_keyspace( &mut self, key_range: &Range<Self::Key>, _lsn: Lsn, _ctx: &Self::RequestContext, ) -> anyhow::Result<interface::CompactionKeySpace<Key>> { // find it in the levels if self.old_keyspaces.is_empty() { Ok(crate::helpers::intersect_keyspace( &self.keyspace, key_range, )) } else { // not implemented // The mock implementation only allows requesting the // keyspace at the level's end LSN. That's all that the // current implementation needs. panic!("keyspace not available for requested lsn"); } } async fn downcast_delta_layer( &self, layer: &MockLayer, _ctx: &MockRequestContext, ) -> anyhow::Result<Option<Arc<MockDeltaLayer>>> { Ok(match layer { MockLayer::Delta(l) => Some(l.clone()), MockLayer::Image(_) => None, }) } async fn create_image( &mut self, lsn: Lsn, key_range: &Range<Key>, ctx: &MockRequestContext, ) -> anyhow::Result<()> { let keyspace = self.get_keyspace(key_range, lsn, ctx).await?; let mut accum_size: u64 = 0; for r in keyspace { accum_size += r.end - r.start; } let new_layer = Arc::new(MockImageLayer { key_range: key_range.clone(), lsn_range: lsn..lsn, file_size: accum_size * PAGE_SZ, deleted: Mutex::new(false), }); info!( "created image layer, size {}: {}", new_layer.file_size, new_layer.short_id() ); self.live_layers.push(MockLayer::Image(new_layer.clone())); // update stats self.bytes_written += new_layer.file_size; self.layers_created += 1; self.time += 1; self.history.push(LayerTraceEvent { time_rel: self.time, op: LayerTraceOp::CreateImage, file: LayerTraceFile { filename: new_layer.short_id(), key_range: new_layer.key_range.clone(), lsn_range: new_layer.lsn_range.clone(), }, }); Ok(()) } async fn create_delta( &mut self, lsn_range: &Range<Lsn>, key_range: &Range<Key>, input_layers: &[Arc<MockDeltaLayer>], ctx: &MockRequestContext, ) -> anyhow::Result<()> { let mut key_value_stream = std::pin::pin!(merge_delta_keys::<MockTimeline>(input_layers, ctx)); let mut records: Vec<MockRecord> = Vec::new(); let mut total_len = 2; while let Some(delta_entry) = key_value_stream.next().await { let delta_entry: MockRecord = delta_entry?; if key_range.contains(&delta_entry.key) && lsn_range.contains(&delta_entry.lsn) { total_len += delta_entry.len; records.push(delta_entry); } } let total_records = records.len(); let new_layer = Arc::new(MockDeltaLayer { key_range: key_range.clone(), lsn_range: lsn_range.clone(), file_size: total_len, records, deleted: Mutex::new(false), }); info!( "created delta layer, recs {}, size {}: {}", total_records, total_len, new_layer.short_id() ); self.live_layers.push(MockLayer::Delta(new_layer.clone())); // update stats self.bytes_written += total_len; self.layers_created += 1; self.time += 1; self.history.push(LayerTraceEvent { time_rel: self.time, op: LayerTraceOp::CreateDelta, file: LayerTraceFile { filename: new_layer.short_id(), key_range: new_layer.key_range.clone(), lsn_range: new_layer.lsn_range.clone(), }, }); Ok(()) } async fn delete_layer( &mut self, layer: &Self::Layer, _ctx: &MockRequestContext, ) -> anyhow::Result<()> { let layer = std::pin::pin!(layer); info!("deleting layer: {}", layer.short_id()); self.num_deleted_layers += 1; self.bytes_deleted += layer.file_size(); layer.mark_deleted(); self.time += 1; self.history.push(LayerTraceEvent { time_rel: self.time, op: LayerTraceOp::Delete, file: LayerTraceFile { filename: layer.short_id(), key_range: layer.key_range().clone(), lsn_range: layer.lsn_range().clone(), }, }); Ok(()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/compact_tiered.rs
pageserver/compaction/src/compact_tiered.rs
//! # Tiered compaction algorithm. //! //! Read all the input delta files, and write a new set of delta files that //! include all the input WAL records. See retile_deltas(). //! //! In a "normal" LSM tree, you get to remove any values that are overwritten by //! later values, but in our system, we keep all the history. So the reshuffling //! doesn't remove any garbage, it just reshuffles the records to reduce read //! amplification, i.e. the number of files that you need to access to find the //! WAL records for a given key. //! //! If the new delta files would be very "narrow", i.e. each file would cover //! only a narrow key range, then we create a new set of image files //! instead. The current threshold is that if the estimated total size of the //! image layers is smaller than the size of the deltas, then we create image //! layers. That amounts to 2x storage amplification, and it means that the //! distance of image layers in LSN dimension is roughly equal to the logical //! database size. For example, if the logical database size is 10 GB, we would //! generate new image layers every 10 GB of WAL. use std::collections::{HashSet, VecDeque}; use std::ops::Range; use futures::StreamExt; use pageserver_api::shard::ShardIdentity; use tracing::{debug, info}; use utils::lsn::Lsn; use crate::helpers::{ PAGE_SZ, accum_key_values, keyspace_total_size, merge_delta_keys_buffered, overlaps_with, }; use crate::identify_levels::identify_level; use crate::interface::*; /// Main entry point to compaction. /// /// The starting point is a cutoff LSN (`end_lsn`). The compaction is run on /// everything below that point, that needs compaction. The cutoff LSN must /// partition the layers so that there are no layers that span across that /// LSN. To start compaction at the top of the tree, pass the end LSN of the /// written last L0 layer. pub async fn compact_tiered<E: CompactionJobExecutor>( executor: &mut E, end_lsn: Lsn, target_file_size: u64, fanout: u64, ctx: &E::RequestContext, ) -> anyhow::Result<()> { assert!(fanout >= 1, "fanout needs to be at least 1 but is {fanout}"); let exp_base = fanout.max(2); // Start at L0 let mut current_level_no = 0; let mut current_level_target_height = target_file_size; loop { // end LSN +1 to include possible image layers exactly at 'end_lsn'. let all_layers = executor .get_layers( &(E::Key::MIN..E::Key::MAX), &(Lsn(u64::MIN)..end_lsn + 1), ctx, ) .await?; info!( "Compacting L{}, total # of layers: {}", current_level_no, all_layers.len() ); // Identify the range of LSNs that belong to this level. We assume that // each file in this level spans an LSN range up to 1.75x target file // size. That should give us enough slop that if we created a slightly // oversized L0 layer, e.g. because flushing the in-memory layer was // delayed for some reason, we don't consider the oversized layer to // belong to L1. But not too much slop, that we don't accidentally // "skip" levels. let max_height = (current_level_target_height as f64 * 1.75) as u64; let Some(level) = identify_level(all_layers, end_lsn, max_height).await? else { break; }; // Calculate the height of this level. If the # of tiers exceeds the // fanout parameter, it's time to compact it. let depth = level.depth(); info!( "Level {} identified as LSN range {}-{}: depth {}", current_level_no, level.lsn_range.start, level.lsn_range.end, depth ); for l in &level.layers { debug!("LEVEL {} layer: {}", current_level_no, l.short_id()); } if depth < fanout { debug!( level = current_level_no, depth = depth, fanout, "too few deltas to compact" ); break; } compact_level( &level.lsn_range, &level.layers, executor, target_file_size, ctx, ) .await?; if current_level_target_height == u64::MAX { // our target height includes all possible lsns info!( level = current_level_no, depth = depth, "compaction loop reached max current_level_target_height" ); break; } current_level_no += 1; current_level_target_height = current_level_target_height.saturating_mul(exp_base); } Ok(()) } async fn compact_level<E: CompactionJobExecutor>( lsn_range: &Range<Lsn>, layers: &[E::Layer], executor: &mut E, target_file_size: u64, ctx: &E::RequestContext, ) -> anyhow::Result<bool> { let mut layer_fragments = Vec::new(); for l in layers { layer_fragments.push(LayerFragment::new(l.clone())); } let mut state = LevelCompactionState { shard_identity: *executor.get_shard_identity(), target_file_size, _lsn_range: lsn_range.clone(), layers: layer_fragments, jobs: Vec::new(), job_queue: Vec::new(), next_level: false, executor, }; let first_job = CompactionJob { key_range: E::Key::MIN..E::Key::MAX, lsn_range: lsn_range.clone(), strategy: CompactionStrategy::Divide, input_layers: state .layers .iter() .enumerate() .map(|i| LayerId(i.0)) .collect(), completed: false, }; state.jobs.push(first_job); state.job_queue.push(JobId(0)); state.execute(ctx).await?; info!( "compaction completed! Need to process next level: {}", state.next_level ); Ok(state.next_level) } /// Blackboard that keeps track of the state of all the jobs and work remaining struct LevelCompactionState<'a, E> where E: CompactionJobExecutor, { shard_identity: ShardIdentity, // parameters target_file_size: u64, _lsn_range: Range<Lsn>, layers: Vec<LayerFragment<E>>, // job queue jobs: Vec<CompactionJob<E>>, job_queue: Vec<JobId>, /// If false, no need to compact levels below this next_level: bool, /// Interface to the outside world executor: &'a mut E, } #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] struct LayerId(usize); #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] struct JobId(usize); struct PendingJobSet { pending: HashSet<JobId>, completed: HashSet<JobId>, } impl PendingJobSet { fn new() -> Self { PendingJobSet { pending: HashSet::new(), completed: HashSet::new(), } } fn complete_job(&mut self, job_id: JobId) { self.pending.remove(&job_id); self.completed.insert(job_id); } fn all_completed(&self) -> bool { self.pending.is_empty() } } // When we decide to rewrite a set of layers, LayerFragment is used to keep // track which new layers supersede an old layer. When all the stakeholder jobs // have completed, this layer can be deleted. struct LayerFragment<E> where E: CompactionJobExecutor, { layer: E::Layer, // If we will write new layers to replace this one, this keeps track of the // jobs that need to complete before this layer can be deleted. As the jobs // complete, they are moved from 'pending' to 'completed' set. Once the // 'pending' set becomes empty, the layer can be deleted. // // If None, this layer is not rewritten and must not be deleted. deletable_after: Option<PendingJobSet>, deleted: bool, } impl<E> LayerFragment<E> where E: CompactionJobExecutor, { fn new(layer: E::Layer) -> Self { LayerFragment { layer, deletable_after: None, deleted: false, } } } #[derive(PartialEq)] enum CompactionStrategy { Divide, CreateDelta, CreateImage, } struct CompactionJob<E: CompactionJobExecutor> { key_range: Range<E::Key>, lsn_range: Range<Lsn>, strategy: CompactionStrategy, input_layers: Vec<LayerId>, completed: bool, } impl<E> LevelCompactionState<'_, E> where E: CompactionJobExecutor, { /// Main loop of the executor. /// /// In each iteration, we take the next job from the queue, and execute it. /// The execution might add new jobs to the queue. Keep going until the /// queue is empty. /// /// Initially, the job queue consists of one Divide job over the whole /// level. On first call, it is divided into smaller jobs. async fn execute(&mut self, ctx: &E::RequestContext) -> anyhow::Result<()> { // TODO: this would be pretty straightforward to parallelize with FuturesUnordered while let Some(next_job_id) = self.job_queue.pop() { info!("executing job {}", next_job_id.0); self.execute_job(next_job_id, ctx).await?; } // all done! Ok(()) } async fn execute_job(&mut self, job_id: JobId, ctx: &E::RequestContext) -> anyhow::Result<()> { let job = &self.jobs[job_id.0]; match job.strategy { CompactionStrategy::Divide => { self.divide_job(job_id, ctx).await?; Ok(()) } CompactionStrategy::CreateDelta => { let mut deltas: Vec<E::DeltaLayer> = Vec::new(); let mut layer_ids: Vec<LayerId> = Vec::new(); for layer_id in &job.input_layers { let layer = &self.layers[layer_id.0].layer; if let Some(dl) = self.executor.downcast_delta_layer(layer, ctx).await? { deltas.push(dl.clone()); layer_ids.push(*layer_id); } } self.executor .create_delta(&job.lsn_range, &job.key_range, &deltas, ctx) .await?; self.jobs[job_id.0].completed = true; // did we complete any fragments? for layer_id in layer_ids { let l = &mut self.layers[layer_id.0]; if let Some(deletable_after) = l.deletable_after.as_mut() { deletable_after.complete_job(job_id); if deletable_after.all_completed() { self.executor.delete_layer(&l.layer, ctx).await?; l.deleted = true; } } } self.next_level = true; Ok(()) } CompactionStrategy::CreateImage => { self.executor .create_image(job.lsn_range.end, &job.key_range, ctx) .await?; self.jobs[job_id.0].completed = true; // TODO: we could check if any layers < PITR horizon became deletable Ok(()) } } } fn push_job(&mut self, job: CompactionJob<E>) -> JobId { let job_id = JobId(self.jobs.len()); self.jobs.push(job); self.job_queue.push(job_id); job_id } /// Take a partition of the key space, and decide how to compact it. /// /// TODO: Currently, this is called exactly once for the level, and we /// decide whether to create new image layers to cover the whole level, or /// write a new set of deltas. In the future, this should try to partition /// the key space, and make the decision separately for each partition. async fn divide_job(&mut self, job_id: JobId, ctx: &E::RequestContext) -> anyhow::Result<()> { let job = &self.jobs[job_id.0]; assert!(job.strategy == CompactionStrategy::Divide); // Check for dummy cases if job.input_layers.is_empty() { return Ok(()); } let job = &self.jobs[job_id.0]; assert!(job.strategy == CompactionStrategy::Divide); // Would it be better to create images for this partition? // Decide based on the average density of the level let keyspace_size = keyspace_total_size( &self .executor .get_keyspace(&job.key_range, job.lsn_range.end, ctx) .await?, &self.shard_identity, ) * PAGE_SZ; let wal_size = job .input_layers .iter() .filter(|layer_id| self.layers[layer_id.0].layer.is_delta()) .map(|layer_id| self.layers[layer_id.0].layer.file_size()) .sum::<u64>(); if keyspace_size < wal_size { // seems worth it info!( "covering with images, because keyspace_size is {}, size of deltas between {}-{} is {}", keyspace_size, job.lsn_range.start, job.lsn_range.end, wal_size ); self.cover_with_images(job_id, ctx).await } else { // do deltas info!( "coverage not worth it, keyspace_size {}, wal_size {}", keyspace_size, wal_size ); self.retile_deltas(job_id, ctx).await } } // LSN // ^ // | // | ###|###|##### // | +--+-----+--+ +--+-----+--+ // | | | | | | | | | // | +--+--+--+--+ +--+--+--+--+ // | | | | | | | // | +---+-+-+---+ ==> +---+-+-+---+ // | | | | | | | | | // | +---+-+-++--+ +---+-+-++--+ // | | | | | | | | | // | +-----+--+--+ +-----+--+--+ // | // +--------------> key // async fn cover_with_images( &mut self, job_id: JobId, ctx: &E::RequestContext, ) -> anyhow::Result<()> { let job = &self.jobs[job_id.0]; assert!(job.strategy == CompactionStrategy::Divide); // XXX: do we still need the "holes" stuff? let mut new_jobs = Vec::new(); // Slide a window through the keyspace let keyspace = self .executor .get_keyspace(&job.key_range, job.lsn_range.end, ctx) .await?; let mut window = KeyspaceWindow::new( E::Key::MIN..E::Key::MAX, keyspace, self.target_file_size / PAGE_SZ, ); while let Some(key_range) = window.choose_next_image(&self.shard_identity) { new_jobs.push(CompactionJob::<E> { key_range, lsn_range: job.lsn_range.clone(), strategy: CompactionStrategy::CreateImage, input_layers: Vec::new(), // XXX: Is it OK for this to be empty for image layer? completed: false, }); } for j in new_jobs.into_iter().rev() { let _job_id = self.push_job(j); // TODO: image layers don't let us delete anything. unless < PITR horizon //let j = &self.jobs[job_id.0]; // for layer_id in j.input_layers.iter() { // self.layers[layer_id.0].pending_stakeholders.insert(job_id); //} } Ok(()) } // Merge the contents of all the input delta layers into a new set // of delta layers, based on the current partitioning. // // We split the new delta layers on the key dimension. We iterate through // the key space, and for each key, check if including the next key to the // current output layer we're building would cause the layer to become too // large. If so, dump the current output layer and start new one. It's // possible that there is a single key with so many page versions that // storing all of them in a single layer file would be too large. In that // case, we also split on the LSN dimension. // // LSN // ^ // | // | +-----------+ +--+--+--+--+ // | | | | | | | | // | +-----------+ | | | | | // | | | | | | | | // | +-----------+ ==> | | | | | // | | | | | | | | // | +-----------+ | | | | | // | | | | | | | | // | +-----------+ +--+--+--+--+ // | // +--------------> key // // // If one key (X) has a lot of page versions: // // LSN // ^ // | (X) // | +-----------+ +--+--+--+--+ // | | | | | | | | // | +-----------+ | | +--+ | // | | | | | | | | // | +-----------+ ==> | | | | | // | | | | | +--+ | // | +-----------+ | | | | | // | | | | | | | | // | +-----------+ +--+--+--+--+ // | // +--------------> key // // TODO: this actually divides the layers into fixed-size chunks, not // based on the partitioning. // // TODO: we should also opportunistically materialize and // garbage collect what we can. async fn retile_deltas( &mut self, job_id: JobId, ctx: &E::RequestContext, ) -> anyhow::Result<()> { let job = &self.jobs[job_id.0]; assert!(job.strategy == CompactionStrategy::Divide); // Sweep the key space left to right, running an estimate of how much // disk size and keyspace we have accumulated // // Once the disk size reaches the target threshold, stop and think. // If we have accumulated only a narrow band of keyspace, create an // image layer. Otherwise write a delta layer. // FIXME: we are ignoring images here. Did we already divide the work // so that we won't encounter them here? let mut deltas: Vec<E::DeltaLayer> = Vec::new(); for layer_id in &job.input_layers { let l = &self.layers[layer_id.0]; if let Some(dl) = self.executor.downcast_delta_layer(&l.layer, ctx).await? { deltas.push(dl.clone()); } } // Open stream let key_value_stream = std::pin::pin!( merge_delta_keys_buffered::<E>(deltas.as_slice(), ctx) .await? .map(Result::<_, anyhow::Error>::Ok) ); let mut new_jobs = Vec::new(); // Slide a window through the keyspace let mut key_accum = std::pin::pin!(accum_key_values(key_value_stream, self.target_file_size)); let mut all_in_window: bool = false; let mut window = Window::new(); // Helper function to create a job for a new delta layer with given key-lsn // rectangle. let create_delta_job = |key_range, lsn_range: &Range<Lsn>, new_jobs: &mut Vec<_>| { // The inputs for the job are all the input layers of the original job that // overlap with the rectangle. let batch_layers: Vec<LayerId> = job .input_layers .iter() .filter(|layer_id| { overlaps_with(self.layers[layer_id.0].layer.key_range(), &key_range) }) .cloned() .collect(); assert!(!batch_layers.is_empty()); new_jobs.push(CompactionJob { key_range, lsn_range: lsn_range.clone(), strategy: CompactionStrategy::CreateDelta, input_layers: batch_layers, completed: false, }); }; loop { if all_in_window && window.is_empty() { // All done! break; } // If we now have enough keyspace for next delta layer in the window, create a // new delta layer if let Some(key_range) = window.choose_next_delta(self.target_file_size, !all_in_window) { create_delta_job(key_range, &job.lsn_range, &mut new_jobs); continue; } assert!(!all_in_window); // Process next key in the key space match key_accum.next().await.transpose()? { None => { all_in_window = true; } Some(next_key) if next_key.partition_lsns.is_empty() => { // Normal case: extend the window by the key window.feed(next_key.key, next_key.size); } Some(next_key) => { // A key with too large size impact for a single delta layer. This // case occurs if you make a huge number of updates for a single key. // // Drain the window with has_more = false to make a clean cut before // the key, and then make dedicated delta layers for the single key. // // We cannot cluster the key with the others, because we don't want // layer files to overlap with each other in the lsn,key space (no // overlaps for the rectangles). let key = next_key.key; debug!("key {key} with size impact larger than the layer size"); while !window.is_empty() { let has_more = false; let key_range = window.choose_next_delta(self.target_file_size, has_more) .expect("with has_more==false, choose_next_delta always returns something for a non-empty Window"); create_delta_job(key_range, &job.lsn_range, &mut new_jobs); } // Not really required: but here for future resilience: // We make a "gap" here, so any structure the window holds should // probably be reset. window = Window::new(); let mut prior_lsn = job.lsn_range.start; let mut lsn_ranges = Vec::new(); for (lsn, _size) in next_key.partition_lsns.iter() { lsn_ranges.push(prior_lsn..*lsn); prior_lsn = *lsn; } lsn_ranges.push(prior_lsn..job.lsn_range.end); for lsn_range in lsn_ranges { let key_range = key..key.next(); create_delta_job(key_range, &lsn_range, &mut new_jobs); } } } } // All the input files are rewritten. Set up the tracking for when they can // be deleted. for layer_id in job.input_layers.iter() { let l = &mut self.layers[layer_id.0]; assert!(l.deletable_after.is_none()); l.deletable_after = Some(PendingJobSet::new()); } for j in new_jobs.into_iter().rev() { let job_id = self.push_job(j); let j = &self.jobs[job_id.0]; for layer_id in j.input_layers.iter() { self.layers[layer_id.0] .deletable_after .as_mut() .unwrap() .pending .insert(job_id); } } Ok(()) } } /// Sliding window through keyspace and values for image layer /// This is used by [`LevelCompactionState::cover_with_images`] to decide on good split points struct KeyspaceWindow<K> { head: KeyspaceWindowHead<K>, start_pos: KeyspaceWindowPos<K>, } struct KeyspaceWindowHead<K> { // overall key range to cover key_range: Range<K>, keyspace: Vec<Range<K>>, target_keysize: u64, } #[derive(Clone)] struct KeyspaceWindowPos<K> { end_key: K, keyspace_idx: usize, accum_keysize: u64, } impl<K: CompactionKey> KeyspaceWindowPos<K> { fn reached_end(&self, w: &KeyspaceWindowHead<K>) -> bool { self.keyspace_idx == w.keyspace.len() } // Advance the cursor until it reaches 'target_keysize'. fn advance_until_size( &mut self, w: &KeyspaceWindowHead<K>, max_size: u64, shard_identity: &ShardIdentity, ) { while self.accum_keysize < max_size && !self.reached_end(w) { let curr_range = &w.keyspace[self.keyspace_idx]; if self.end_key < curr_range.start { // skip over any unused space self.end_key = curr_range.start; } // We're now within 'curr_range'. Can we advance past it completely? let distance = K::key_range_size(&(self.end_key..curr_range.end), shard_identity); if (self.accum_keysize + distance as u64) < max_size { // oh yeah, it fits self.end_key = curr_range.end; self.keyspace_idx += 1; self.accum_keysize += distance as u64; } else { // advance within the range let skip_key = self.end_key.skip_some(); let distance = K::key_range_size(&(self.end_key..skip_key), shard_identity); if (self.accum_keysize + distance as u64) < max_size { self.end_key = skip_key; self.accum_keysize += distance as u64; } else { self.end_key = self.end_key.next(); self.accum_keysize += 1; } } } } } impl<K> KeyspaceWindow<K> where K: CompactionKey, { fn new(key_range: Range<K>, keyspace: CompactionKeySpace<K>, target_keysize: u64) -> Self { assert!(keyspace.first().unwrap().start >= key_range.start); let start_key = key_range.start; let start_pos = KeyspaceWindowPos::<K> { end_key: start_key, keyspace_idx: 0, accum_keysize: 0, }; Self { head: KeyspaceWindowHead::<K> { key_range, keyspace, target_keysize, }, start_pos, } } fn choose_next_image(&mut self, shard_identity: &ShardIdentity) -> Option<Range<K>> { if self.start_pos.keyspace_idx == self.head.keyspace.len() { // we've reached the end return None; } let mut next_pos = self.start_pos.clone(); next_pos.advance_until_size( &self.head, self.start_pos.accum_keysize + self.head.target_keysize, shard_identity, ); // See if we can gobble up the rest of the keyspace if we stretch out the layer, up to // 1.25x target size let mut end_pos = next_pos.clone(); end_pos.advance_until_size( &self.head, self.start_pos.accum_keysize + (self.head.target_keysize * 5 / 4), shard_identity, ); if end_pos.reached_end(&self.head) { // gobble up any unused keyspace between the last used key and end of the range assert!(end_pos.end_key <= self.head.key_range.end); end_pos.end_key = self.head.key_range.end; next_pos = end_pos; } let start_key = self.start_pos.end_key; self.start_pos = next_pos; Some(start_key..self.start_pos.end_key) } } // Take previous partitioning, based on the image layers below. // // Candidate is at the front: // // Consider stretching an image layer to next divider? If it's close enough, // that's the image candidate // // If it's too far, consider splitting at a reasonable point // // Is the image candidate smaller than the equivalent delta? If so, // split off the image. Otherwise, split off one delta. // Try to snap off the delta at a reasonable point struct WindowElement<K> { start_key: K, // inclusive last_key: K, // inclusive accum_size: u64, } /// Sliding window through keyspace and values for delta layer tiling /// /// This is used to decide which delta layer to write next. struct Window<K> { elems: VecDeque<WindowElement<K>>, // last key that was split off, inclusive splitoff_key: Option<K>, splitoff_size: u64, } impl<K> Window<K> where K: CompactionKey, { fn new() -> Self { Self { elems: VecDeque::new(), splitoff_key: None, splitoff_size: 0, } } fn feed(&mut self, key: K, size: u64) { let last_size; if let Some(last) = self.elems.back_mut() { // We require the keys to be strictly increasing for the window. // Keys should already have been deduplicated by `accum_key_values` assert!( last.last_key < key, "last_key(={}) >= key(={key})", last.last_key ); last_size = last.accum_size; } else { last_size = 0; } // This is a new key. let elem = WindowElement { start_key: key, last_key: key, accum_size: last_size + size, }; self.elems.push_back(elem); } fn remain_size(&self) -> u64 { self.elems.back().unwrap().accum_size - self.splitoff_size } fn peek_size(&self) -> u64 { self.elems.front().unwrap().accum_size - self.splitoff_size } fn is_empty(&self) -> bool { self.elems.is_empty() } fn commit_upto(&mut self, mut upto: usize) { while upto > 1 { let popped = self.elems.pop_front().unwrap(); self.elems.front_mut().unwrap().start_key = popped.start_key; upto -= 1; } } fn find_size_split(&self, target_size: u64) -> usize { self.elems .partition_point(|elem| elem.accum_size - self.splitoff_size < target_size) } fn pop(&mut self) { let first = self.elems.pop_front().unwrap(); self.splitoff_size = first.accum_size; self.splitoff_key = Some(first.last_key); } // the difference between delta and image is that an image covers // any unused keyspace before and after, while a delta tries to // minimize that. TODO: difference not implemented fn pop_delta(&mut self) -> Range<K> { let first = self.elems.front().unwrap(); let key_range = first.start_key..first.last_key.next(); self.pop(); key_range } // Prerequisite: we have enough input in the window // // On return None, the caller should feed more data and call again fn choose_next_delta(&mut self, target_size: u64, has_more: bool) -> Option<Range<K>> { if has_more && self.elems.is_empty() { // Starting up return None; } // If we still have an undersized candidate, just keep going while self.peek_size() < target_size { if self.elems.len() > 1 { self.commit_upto(2); } else if has_more { return None; } else { break; } } // Ensure we have enough input in the window to make a good decision if has_more && self.remain_size() < target_size * 5 / 4 { return None; } // The candidate on the front is now large enough, for a delta. // And we have enough data in the window to decide. // If we're willing to stretch it up to 1.25 target size, could we // gobble up the rest of the work? This avoids creating very small // "tail" layers at the end of the keyspace if !has_more && self.remain_size() < target_size * 5 / 4 { self.commit_upto(self.elems.len()); } else { let delta_split_at = self.find_size_split(target_size); self.commit_upto(delta_split_at); // If it's still not large enough, request the caller to fill the window if self.elems.len() == 1 && has_more { return None; } } Some(self.pop_delta()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/simulator/draw.rs
pageserver/compaction/src/simulator/draw.rs
use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fmt::Write; use std::ops::Range; use anyhow::Result; use svg_fmt::{BeginSvg, EndSvg, Fill, Stroke, Style, rgb}; use utils::lsn::Lsn; use super::Key; // Map values to their compressed coordinate - the index the value // would have in a sorted and deduplicated list of all values. struct CoordinateMap<T: Ord + Copy> { map: BTreeMap<T, usize>, stretch: f32, } impl<T: Ord + Copy> CoordinateMap<T> { fn new(coords: Vec<T>, stretch: f32) -> Self { let set: BTreeSet<T> = coords.into_iter().collect(); let mut map: BTreeMap<T, usize> = BTreeMap::new(); for (i, e) in set.iter().enumerate() { map.insert(*e, i); } Self { map, stretch } } // This assumes that the map contains an exact point for this. // Use map_inexact for values inbetween fn map(&self, val: T) -> f32 { *self.map.get(&val).unwrap() as f32 * self.stretch } // the value is still assumed to be within the min/max bounds // (this is currently unused) fn _map_inexact(&self, val: T) -> f32 { let prev = *self.map.range(..=val).next().unwrap().1; let next = *self.map.range(val..).next().unwrap().1; // interpolate (prev as f32 + (next - prev) as f32) * self.stretch } fn max(&self) -> f32 { self.map.len() as f32 * self.stretch } } #[derive(PartialEq, Hash, Eq)] pub enum LayerTraceOp { Flush, CreateDelta, CreateImage, Delete, } impl std::fmt::Display for LayerTraceOp { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { let op_str = match self { LayerTraceOp::Flush => "flush", LayerTraceOp::CreateDelta => "create_delta", LayerTraceOp::CreateImage => "create_image", LayerTraceOp::Delete => "delete", }; f.write_str(op_str) } } #[derive(PartialEq, Hash, Eq, Clone)] pub struct LayerTraceFile { pub filename: String, pub key_range: Range<Key>, pub lsn_range: Range<Lsn>, } impl LayerTraceFile { fn is_image(&self) -> bool { self.lsn_range.end == self.lsn_range.start } } pub struct LayerTraceEvent { pub time_rel: u64, pub op: LayerTraceOp, pub file: LayerTraceFile, } pub fn draw_history<W: std::io::Write>(history: &[LayerTraceEvent], mut output: W) -> Result<()> { let mut files: Vec<LayerTraceFile> = Vec::new(); for event in history { files.push(event.file.clone()); } let last_time_rel = history.last().unwrap().time_rel; // Collect all coordinates let mut keys: Vec<Key> = vec![]; let mut lsns: Vec<Lsn> = vec![]; for f in files.iter() { keys.push(f.key_range.start); keys.push(f.key_range.end); lsns.push(f.lsn_range.start); lsns.push(f.lsn_range.end); } // Analyze let key_map = CoordinateMap::new(keys, 2.0); // Stretch out vertically for better visibility let lsn_map = CoordinateMap::new(lsns, 3.0); let mut svg = String::new(); // Draw writeln!( svg, "{}", BeginSvg { w: key_map.max(), h: lsn_map.max(), } )?; let lsn_max = lsn_map.max(); // Sort the files by LSN, but so that image layers go after all delta layers // The SVG is painted in the order the elements appear, and we want to draw // image layers on top of the delta layers if they overlap // // (This could also be implemented via z coordinates: image layers get one z // coord, delta layers get another z coord.) let mut files_sorted: Vec<LayerTraceFile> = files.into_iter().collect(); files_sorted.sort_by(|a, b| { if a.is_image() && !b.is_image() { Ordering::Greater } else if !a.is_image() && b.is_image() { Ordering::Less } else { a.lsn_range.end.cmp(&b.lsn_range.end) } }); writeln!(svg, "<!-- layers -->")?; let mut files_seen = HashSet::new(); for f in files_sorted { if files_seen.contains(&f) { continue; } let key_start = key_map.map(f.key_range.start); let key_end = key_map.map(f.key_range.end); let key_diff = key_end - key_start; if key_start >= key_end { panic!("Invalid key range {key_start}-{key_end}"); } let lsn_start = lsn_map.map(f.lsn_range.start); let lsn_end = lsn_map.map(f.lsn_range.end); // Fill in and thicken rectangle if it's an // image layer so that we can see it. let mut style = Style { fill: Fill::Color(rgb(0x80, 0x80, 0x80)), stroke: Stroke::Color(rgb(0, 0, 0), 0.5), opacity: 1.0, stroke_opacity: 1.0, }; let y_start = lsn_max - lsn_start; let y_end = lsn_max - lsn_end; let x_margin = 0.25; let y_margin = 0.5; match f.lsn_range.start.cmp(&f.lsn_range.end) { Ordering::Less => { write!( svg, r#" <rect id="layer_{}" x="{}" y="{}" width="{}" height="{}" ry="{}" style="{}">"#, f.filename, key_start + x_margin, y_end + y_margin, key_diff - x_margin * 2.0, y_start - y_end - y_margin * 2.0, 1.0, // border_radius, style, )?; write!(svg, "<title>{}</title>", f.filename)?; writeln!(svg, "</rect>")?; } Ordering::Equal => { //lsn_diff = 0.3; //lsn_offset = -lsn_diff / 2.0; //margin = 0.05; style.fill = Fill::Color(rgb(0x80, 0, 0x80)); style.stroke = Stroke::Color(rgb(0x80, 0, 0x80), 3.0); write!( svg, r#" <line id="layer_{}" x1="{}" y1="{}" x2="{}" y2="{}" style="{}">"#, f.filename, key_start + x_margin, y_end, key_end - x_margin, y_end, style, )?; write!( svg, "<title>{}<br>{} - {}</title>", f.filename, lsn_end, y_end )?; writeln!(svg, "</line>")?; } Ordering::Greater => panic!("Invalid lsn range {lsn_start}-{lsn_end}"), } files_seen.insert(f); } writeln!(svg, "{EndSvg}")?; let mut layer_events_str = String::new(); let mut first = true; for e in history { if !first { writeln!(layer_events_str, ",")?; } write!( layer_events_str, r#" {{"time_rel": {}, "filename": "{}", "op": "{}"}}"#, e.time_rel, e.file.filename, e.op )?; first = false; } writeln!(layer_events_str)?; writeln!( output, r#"<!DOCTYPE html> <html> <head> <style> /* Keep the slider pinned at top */ .topbar {{ display: block; overflow: hidden; background-color: lightgrey; position: fixed; top: 0; width: 100%; /* width: 500px; */ }} .slidercontainer {{ float: left; width: 50%; margin-right: 200px; }} .slider {{ float: left; width: 100%; }} .legend {{ width: 200px; float: right; }} /* Main content */ .main {{ margin-top: 50px; /* Add a top margin to avoid content overlay */ }} </style> </head> <body onload="init()"> <script type="text/javascript"> var layer_events = [{layer_events_str}] let ticker; function init() {{ for (let i = 0; i < layer_events.length; i++) {{ var layer = document.getElementById("layer_" + layer_events[i].filename); layer.style.visibility = "hidden"; }} last_layer_event = -1; moveSlider(last_slider_pos) }} function startAnimation() {{ ticker = setInterval(animateStep, 100); }} function stopAnimation() {{ clearInterval(ticker); }} function animateStep() {{ if (last_layer_event < layer_events.length - 1) {{ var slider = document.getElementById("time-slider"); let prevPos = slider.value let nextEvent = last_layer_event + 1 while (nextEvent <= layer_events.length - 1) {{ if (layer_events[nextEvent].time_rel > prevPos) {{ break; }} nextEvent += 1; }} let nextPos = layer_events[nextEvent].time_rel slider.value = nextPos moveSlider(nextPos) }} }} function redoLayerEvent(n, dir) {{ var layer = document.getElementById("layer_" + layer_events[n].filename); switch (layer_events[n].op) {{ case "flush": layer.style.visibility = "visible"; break; case "create_delta": layer.style.visibility = "visible"; break; case "create_image": layer.style.visibility = "visible"; break; case "delete": layer.style.visibility = "hidden"; break; }} }} function undoLayerEvent(n) {{ var layer = document.getElementById("layer_" + layer_events[n].filename); switch (layer_events[n].op) {{ case "flush": layer.style.visibility = "hidden"; break; case "create_delta": layer.style.visibility = "hidden"; break; case "create_image": layer.style.visibility = "hidden"; break; case "delete": layer.style.visibility = "visible"; break; }} }} var last_slider_pos = 0 var last_layer_event = 0 var moveSlider = function(new_pos) {{ if (new_pos > last_slider_pos) {{ while (last_layer_event < layer_events.length - 1) {{ if (layer_events[last_layer_event + 1].time_rel > new_pos) {{ break; }} last_layer_event += 1; redoLayerEvent(last_layer_event) }} }} if (new_pos < last_slider_pos) {{ while (last_layer_event >= 0) {{ if (layer_events[last_layer_event].time_rel <= new_pos) {{ break; }} undoLayerEvent(last_layer_event) last_layer_event -= 1; }} }} last_slider_pos = new_pos; document.getElementById("debug_pos").textContent=new_pos; if (last_layer_event >= 0) {{ document.getElementById("debug_layer_event").textContent=last_layer_event + " " + layer_events[last_layer_event].time_rel + " " + layer_events[last_layer_event].op; }} else {{ document.getElementById("debug_layer_event").textContent="begin"; }} }} </script> <div class="topbar"> <div class="slidercontainer"> <label for="time-slider">TIME</label>: <input id="time-slider" class="slider" type="range" min="0" max="{last_time_rel}" value="0" oninput="moveSlider(this.value)"><br> pos: <span id="debug_pos"></span><br> event: <span id="debug_layer_event"></span><br> gc: <span id="debug_gc_event"></span><br> </div> <button onclick="startAnimation()">Play</button> <button onclick="stopAnimation()">Stop</button> <svg class="legend"> <rect x=5 y=0 width=20 height=20 style="fill:rgb(128,128,128);stroke:rgb(0,0,0);stroke-width:0.5;fill-opacity:1;stroke-opacity:1;"/> <line x1=5 y1=30 x2=25 y2=30 style="fill:rgb(128,0,128);stroke:rgb(128,0,128);stroke-width:3;fill-opacity:1;stroke-opacity:1;"/> <line x1=0 y1=40 x2=30 y2=40 style="fill:none;stroke:rgb(255,0,0);stroke-width:0.5;fill-opacity:1;stroke-opacity:1;"/> </svg> </div> <div class="main"> {svg} </div> </body> </html> "# )?; Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/src/bin/compaction-simulator.rs
pageserver/compaction/src/bin/compaction-simulator.rs
use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::OnceLock; use clap::{Parser, Subcommand}; use pageserver_compaction::helpers::PAGE_SZ; use pageserver_compaction::simulator::MockTimeline; use rand::Rng; use utils::project_git_version; project_git_version!(GIT_VERSION); #[derive(Parser)] #[command( version = GIT_VERSION, about = "Neon Pageserver compaction simulator", long_about = "A developer tool to visualize and test compaction" )] #[command(propagate_version = true)] struct CliOpts { #[command(subcommand)] command: Commands, } #[derive(Subcommand)] enum Commands { RunSuite, Simulate(SimulateCmd), } #[derive(Clone, clap::ValueEnum)] enum Distribution { Uniform, HotCold, } /// Read and update pageserver metadata file #[derive(Parser)] struct SimulateCmd { distribution: Distribution, /// Number of records to digest num_records: u64, /// Record length record_len: u64, // Logical database size in MB logical_size: u64, } async fn simulate(cmd: &SimulateCmd, results_path: &Path) -> anyhow::Result<()> { let mut executor = MockTimeline::new(); // Convert the logical size in MB into a key range. let key_range = 0..((cmd.logical_size * 1024 * 1024) / PAGE_SZ); //let key_range = u64::MIN..u64::MAX; println!( "starting simulation with key range {:016X}-{:016X}", key_range.start, key_range.end ); // helper function to print progress indicator let print_progress = |i| -> anyhow::Result<()> { if i == 0 || (i + 1) % 10000 == 0 || i == cmd.num_records - 1 { print!( "\ringested {} / {} records, {} MiB / {} MiB...", i + 1, cmd.num_records, (i + 1) * cmd.record_len / (1_000_000), cmd.num_records * cmd.record_len / (1_000_000), ); std::io::stdout().flush()?; } Ok(()) }; match cmd.distribution { Distribution::Uniform => { for i in 0..cmd.num_records { executor.ingest_uniform(1, cmd.record_len, &key_range)?; executor.compact_if_needed().await?; print_progress(i)?; } } Distribution::HotCold => { let splitpoint = key_range.start + (key_range.end - key_range.start) / 10; let hot_key_range = 0..splitpoint; let cold_key_range = splitpoint..key_range.end; for i in 0..cmd.num_records { let chosen_range = if rand::rng().random_bool(0.9) { &hot_key_range } else { &cold_key_range }; executor.ingest_uniform(1, cmd.record_len, chosen_range)?; executor.compact_if_needed().await?; print_progress(i)?; } } } println!("done!"); executor.flush_l0(); executor.compact_if_needed().await?; let stats = executor.stats()?; // Print the stats to stdout, and also to a file print!("{stats}"); std::fs::write(results_path.join("stats.txt"), stats)?; let animation_path = results_path.join("compaction-animation.html"); executor.draw_history(std::fs::File::create(&animation_path)?)?; println!( "animation: file://{}", animation_path.canonicalize()?.display() ); Ok(()) } async fn run_suite_cmd(results_path: &Path, workload: &SimulateCmd) -> anyhow::Result<()> { std::fs::create_dir(results_path)?; set_log_file(File::create(results_path.join("log"))?); let result = simulate(workload, results_path).await; set_log_stdout(); result } async fn run_suite() -> anyhow::Result<()> { let top_results_path = PathBuf::from(format!( "compaction-suite-results.{}", std::time::SystemTime::UNIX_EPOCH.elapsed()?.as_secs() )); std::fs::create_dir(&top_results_path)?; let workload = SimulateCmd { distribution: Distribution::Uniform, // Generate 20 GB of WAL record_len: 1_000, num_records: 20_000_000, // Logical size 5 GB logical_size: 5_000, }; run_suite_cmd(&top_results_path.join("uniform-20GB-5GB"), &workload).await?; println!( "All tests finished. Results in {}", top_results_path.display() ); Ok(()) } use std::fs::File; use std::io::Stdout; use std::sync::Mutex; use tracing_subscriber::fmt::MakeWriter; use tracing_subscriber::fmt::writer::EitherWriter; static LOG_FILE: OnceLock<Mutex<EitherWriter<File, Stdout>>> = OnceLock::new(); fn get_log_output() -> &'static Mutex<EitherWriter<File, Stdout>> { LOG_FILE.get_or_init(|| std::sync::Mutex::new(EitherWriter::B(std::io::stdout()))) } fn set_log_file(f: File) { *get_log_output().lock().unwrap() = EitherWriter::A(f); } fn set_log_stdout() { *get_log_output().lock().unwrap() = EitherWriter::B(std::io::stdout()); } fn init_logging() -> anyhow::Result<()> { // We fall back to printing all spans at info-level or above if // the RUST_LOG environment variable is not set. let rust_log_env_filter = || { tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")) }; // NB: the order of the with() calls does not matter. // See https://docs.rs/tracing-subscriber/0.3.16/tracing_subscriber/layer/index.html#per-layer-filtering use tracing_subscriber::prelude::*; tracing_subscriber::registry() .with({ let log_layer = tracing_subscriber::fmt::layer() .with_target(false) .with_ansi(false) .with_writer(|| get_log_output().make_writer()); log_layer.with_filter(rust_log_env_filter()) }) .init(); Ok(()) } #[tokio::main] async fn main() -> anyhow::Result<()> { let cli = CliOpts::parse(); init_logging()?; match cli.command { Commands::Simulate(cmd) => { simulate(&cmd, &PathBuf::from("/tmp/compactions.html")).await?; } Commands::RunSuite => { run_suite().await?; } }; Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/compaction/tests/tests.rs
pageserver/compaction/tests/tests.rs
use once_cell::sync::OnceCell; use pageserver_compaction::interface::CompactionLayer; use pageserver_compaction::simulator::MockTimeline; use utils::logging; static LOG_HANDLE: OnceCell<()> = OnceCell::new(); pub(crate) fn setup_logging() { LOG_HANDLE.get_or_init(|| { logging::init( logging::LogFormat::Test, logging::TracingErrorLayerEnablement::EnableWithRustLogFilter, logging::Output::Stdout, ) .expect("Failed to init test logging"); }); } /// Test the extreme case that there are so many updates for a single key that /// even if we produce an extremely narrow delta layer, spanning just that one /// key, we still too many records to fit in the target file size. We need to /// split in the LSN dimension too in that case. #[tokio::test] async fn test_many_updates_for_single_key() { setup_logging(); let mut executor = MockTimeline::new(); executor.target_file_size = 1_000_000; // 1 MB // Ingest 10 MB of updates to a single key. for _ in 1..1000 { executor.ingest_uniform(100, 10, &(0..100_000)).unwrap(); executor.ingest_uniform(1000, 10, &(0..1)).unwrap(); executor.compact().await.unwrap(); } // Check that all the layers are smaller than the target size (with some slop) for l in executor.live_layers.iter() { println!("layer {}: {}", l.short_id(), l.file_size()); } for l in executor.live_layers.iter() { assert!(l.file_size() < executor.target_file_size * 2); // Sanity check that none of the delta layers are empty either. if l.is_delta() { assert!(l.file_size() > 0); } } } #[tokio::test] async fn test_simple_updates() { setup_logging(); let mut executor = MockTimeline::new(); executor.target_file_size = 500_000; // 500 KB // Ingest some traffic. for _ in 1..400 { executor.ingest_uniform(100, 500, &(0..100_000)).unwrap(); } for l in executor.live_layers.iter() { println!("layer {}: {}", l.short_id(), l.file_size()); } println!("Running compaction..."); executor.compact().await.unwrap(); for l in executor.live_layers.iter() { println!("layer {}: {}", l.short_id(), l.file_size()); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/index_part.rs
pageserver/ctl/src/index_part.rs
use std::str::FromStr; use anyhow::{Context, Ok}; use camino::Utf8PathBuf; use pageserver::tenant::{ IndexPart, layer_map::{LayerMap, SearchResult}, remote_timeline_client::{index::LayerFileMetadata, remote_layer_path}, storage_layer::{LayerName, LayerVisibilityHint, PersistentLayerDesc, ReadableLayerWeak}, }; use pageserver_api::key::Key; use serde::Serialize; use std::collections::BTreeMap; use utils::{ id::{TenantId, TimelineId}, lsn::Lsn, shard::TenantShardId, }; #[derive(clap::Subcommand)] pub(crate) enum IndexPartCmd { Dump { path: Utf8PathBuf, }, /// Find all layers that need to be searched to construct the given page at the given LSN. Search { #[arg(long)] tenant_id: String, #[arg(long)] timeline_id: String, #[arg(long)] path: Utf8PathBuf, #[arg(long)] key: String, #[arg(long)] lsn: String, }, /// List all visible delta and image layers at the latest LSN. ListVisibleLayers { #[arg(long)] path: Utf8PathBuf, }, } fn create_layer_map_from_index_part( index_part: &IndexPart, tenant_shard_id: TenantShardId, timeline_id: TimelineId, ) -> LayerMap { let mut layer_map = LayerMap::default(); { let mut updates = layer_map.batch_update(); for (key, value) in index_part.layer_metadata.iter() { updates.insert_historic(PersistentLayerDesc::from_filename( tenant_shard_id, timeline_id, key.clone(), value.file_size, )); } } layer_map } async fn search_layers( tenant_id: &str, timeline_id: &str, path: &Utf8PathBuf, key: &str, lsn: &str, ) -> anyhow::Result<()> { let tenant_id = TenantId::from_str(tenant_id).unwrap(); let tenant_shard_id = TenantShardId::unsharded(tenant_id); let timeline_id = TimelineId::from_str(timeline_id).unwrap(); let index_json = { let bytes = tokio::fs::read(path).await?; IndexPart::from_json_bytes(&bytes).unwrap() }; let layer_map = create_layer_map_from_index_part(&index_json, tenant_shard_id, timeline_id); let key = Key::from_hex(key)?; let lsn = Lsn::from_str(lsn).unwrap(); let mut end_lsn = lsn; loop { let result = layer_map.search(key, end_lsn); match result { Some(SearchResult { layer, lsn_floor }) => { let disk_layer = match layer { ReadableLayerWeak::PersistentLayer(layer) => layer, ReadableLayerWeak::InMemoryLayer(_) => { anyhow::bail!("unexpected in-memory layer") } }; let metadata = index_json .layer_metadata .get(&disk_layer.layer_name()) .unwrap(); println!( "{}", remote_layer_path( &tenant_id, &timeline_id, metadata.shard, &disk_layer.layer_name(), metadata.generation ) ); end_lsn = lsn_floor; } None => break, } } Ok(()) } #[derive(Debug, Clone, Serialize)] struct VisibleLayers { pub total_images: u64, pub total_image_bytes: u64, pub total_deltas: u64, pub total_delta_bytes: u64, pub layer_metadata: BTreeMap<LayerName, LayerFileMetadata>, } impl VisibleLayers { pub fn new() -> Self { Self { layer_metadata: BTreeMap::new(), total_images: 0, total_image_bytes: 0, total_deltas: 0, total_delta_bytes: 0, } } pub fn add_layer(&mut self, name: LayerName, layer: LayerFileMetadata) { match name { LayerName::Image(_) => { self.total_images += 1; self.total_image_bytes += layer.file_size; } LayerName::Delta(_) => { self.total_deltas += 1; self.total_delta_bytes += layer.file_size; } } self.layer_metadata.insert(name, layer); } } async fn list_visible_layers(path: &Utf8PathBuf) -> anyhow::Result<()> { let tenant_id = TenantId::generate(); let tenant_shard_id = TenantShardId::unsharded(tenant_id); let timeline_id = TimelineId::generate(); let bytes = tokio::fs::read(path).await.context("read file")?; let index_part = IndexPart::from_json_bytes(&bytes).context("deserialize")?; let layer_map = create_layer_map_from_index_part(&index_part, tenant_shard_id, timeline_id); let mut visible_layers = VisibleLayers::new(); let (layers, _key_space) = layer_map.get_visibility(Vec::new()); for (layer, visibility) in layers { if visibility == LayerVisibilityHint::Visible { visible_layers.add_layer( layer.layer_name(), index_part .layer_metadata .get(&layer.layer_name()) .unwrap() .clone(), ); } } let output = serde_json::to_string_pretty(&visible_layers).context("serialize output")?; println!("{output}"); Ok(()) } pub(crate) async fn main(cmd: &IndexPartCmd) -> anyhow::Result<()> { match cmd { IndexPartCmd::Dump { path } => { let bytes = tokio::fs::read(path).await.context("read file")?; let des: IndexPart = IndexPart::from_json_bytes(&bytes).context("deserialize")?; let output = serde_json::to_string_pretty(&des).context("serialize output")?; println!("{output}"); Ok(()) } IndexPartCmd::Search { tenant_id, timeline_id, path, key, lsn, } => search_layers(tenant_id, timeline_id, path, key, lsn).await, IndexPartCmd::ListVisibleLayers { path } => list_visible_layers(path).await, } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/layers.rs
pageserver/ctl/src/layers.rs
use std::fs::{self, File}; use std::path::{Path, PathBuf}; use anyhow::Result; use camino::{Utf8Path, Utf8PathBuf}; use clap::Subcommand; use pageserver::context::{DownloadBehavior, RequestContext}; use pageserver::task_mgr::TaskKind; use pageserver::tenant::storage_layer::{DeltaLayer, ImageLayer, delta_layer, image_layer}; use pageserver::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME}; use pageserver::virtual_file::api::IoMode; use pageserver::{page_cache, virtual_file}; use pageserver_api::key::Key; use utils::id::{TenantId, TimelineId}; use crate::layer_map_analyzer::{LayerFile, parse_filename}; #[derive(Subcommand)] pub(crate) enum LayerCmd { /// List all tenants and timelines under the pageserver path /// /// Example: `cargo run --bin pagectl layer list .neon/` List { path: PathBuf }, /// List all layers of a given tenant and timeline /// /// Example: `cargo run --bin pagectl layer list .neon/` ListLayer { path: PathBuf, tenant: String, timeline: String, key: Option<Key>, }, /// Dump all information of a layer file DumpLayer { path: PathBuf, tenant: String, timeline: String, /// The id from list-layer command id: usize, }, /// Dump all information of a layer file locally DumpLayerLocal { path: PathBuf }, RewriteSummary { layer_file_path: Utf8PathBuf, #[clap(long)] new_tenant_id: Option<TenantId>, #[clap(long)] new_timeline_id: Option<TimelineId>, }, } async fn read_delta_file(path: impl AsRef<Path>, ctx: &RequestContext) -> Result<()> { virtual_file::init( 10, virtual_file::api::IoEngineKind::StdFs, IoMode::preferred(), virtual_file::SyncMode::Sync, ); page_cache::init(100); let path = Utf8Path::from_path(path.as_ref()).expect("non-Unicode path"); let file = File::open(path)?; let delta_layer = DeltaLayer::new_for_path(path, file)?; delta_layer.dump(true, ctx).await?; Ok(()) } async fn read_image_file(path: impl AsRef<Path>, ctx: &RequestContext) -> Result<()> { virtual_file::init( 10, virtual_file::api::IoEngineKind::StdFs, IoMode::preferred(), virtual_file::SyncMode::Sync, ); page_cache::init(100); let path = Utf8Path::from_path(path.as_ref()).expect("non-Unicode path"); let file = File::open(path)?; let image_layer = ImageLayer::new_for_path(path, file)?; image_layer.dump(true, ctx).await?; Ok(()) } pub(crate) async fn main(cmd: &LayerCmd) -> Result<()> { let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error).with_scope_debug_tools(); match cmd { LayerCmd::List { path } => { for tenant in fs::read_dir(path.join(TENANTS_SEGMENT_NAME))? { let tenant = tenant?; if !tenant.file_type()?.is_dir() { continue; } println!("tenant {}", tenant.file_name().to_string_lossy()); for timeline in fs::read_dir(tenant.path().join(TIMELINES_SEGMENT_NAME))? { let timeline = timeline?; if !timeline.file_type()?.is_dir() { continue; } println!("- timeline {}", timeline.file_name().to_string_lossy()); } } Ok(()) } LayerCmd::ListLayer { path, tenant, timeline, key, } => { let timeline_path = path .join(TENANTS_SEGMENT_NAME) .join(tenant) .join(TIMELINES_SEGMENT_NAME) .join(timeline); let mut idx = 0; let mut to_print = Vec::default(); for layer in fs::read_dir(timeline_path)? { let layer = layer?; if let Ok(layer_file) = parse_filename(&layer.file_name().into_string().unwrap()) { if let Some(key) = key { if layer_file.key_range.start <= *key && *key < layer_file.key_range.end { to_print.push((idx, layer_file)); } } else { to_print.push((idx, layer_file)); } idx += 1; } } if key.is_some() { to_print .sort_by_key(|(_idx, layer_file)| std::cmp::Reverse(layer_file.lsn_range.end)); } for (idx, layer_file) in to_print { print_layer_file(idx, &layer_file); } Ok(()) } LayerCmd::DumpLayer { path, tenant, timeline, id, } => { let timeline_path = path .join("tenants") .join(tenant) .join("timelines") .join(timeline); let mut idx = 0; for layer in fs::read_dir(timeline_path)? { let layer = layer?; if let Ok(layer_file) = parse_filename(&layer.file_name().into_string().unwrap()) { if *id == idx { print_layer_file(idx, &layer_file); if layer_file.is_delta { read_delta_file(layer.path(), &ctx).await?; } else { read_image_file(layer.path(), &ctx).await?; } break; } idx += 1; } } Ok(()) } LayerCmd::DumpLayerLocal { path } => { if let Ok(layer_file) = parse_filename(path.file_name().unwrap().to_str().unwrap()) { print_layer_file(0, &layer_file); if layer_file.is_delta { read_delta_file(path, &ctx).await?; } else { read_image_file(path, &ctx).await?; } } Ok(()) } LayerCmd::RewriteSummary { layer_file_path, new_tenant_id, new_timeline_id, } => { pageserver::virtual_file::init( 10, virtual_file::api::IoEngineKind::StdFs, IoMode::preferred(), virtual_file::SyncMode::Sync, ); pageserver::page_cache::init(100); let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error) .with_scope_debug_tools(); macro_rules! rewrite_closure { ($($summary_ty:tt)*) => {{ |summary| $($summary_ty)* { tenant_id: new_tenant_id.unwrap_or(summary.tenant_id), timeline_id: new_timeline_id.unwrap_or(summary.timeline_id), ..summary } }}; } let res = ImageLayer::rewrite_summary( layer_file_path, rewrite_closure!(image_layer::Summary), &ctx, ) .await; match res { Ok(()) => { println!("Successfully rewrote summary of image layer {layer_file_path}"); return Ok(()); } Err(image_layer::RewriteSummaryError::MagicMismatch) => (), // fallthrough Err(image_layer::RewriteSummaryError::Other(e)) => { return Err(e); } } let res = DeltaLayer::rewrite_summary( layer_file_path, rewrite_closure!(delta_layer::Summary), &ctx, ) .await; match res { Ok(()) => { println!("Successfully rewrote summary of delta layer {layer_file_path}"); return Ok(()); } Err(delta_layer::RewriteSummaryError::MagicMismatch) => (), // fallthrough Err(delta_layer::RewriteSummaryError::Other(e)) => { return Err(e); } } anyhow::bail!("not an image or delta layer: {layer_file_path}"); } } } fn print_layer_file(idx: usize, layer_file: &LayerFile) { println!( "[{:3}] key:{}-{}\n lsn:{}-{}\n delta:{}", idx, layer_file.key_range.start, layer_file.key_range.end, layer_file.lsn_range.start, layer_file.lsn_range.end, layer_file.is_delta, ); }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/key.rs
pageserver/ctl/src/key.rs
use std::str::FromStr; use anyhow::Context; use clap::Parser; use pageserver_api::key::Key; use pageserver_api::reltag::{BlockNumber, RelTag, SlruKind}; use pageserver_api::shard::{DEFAULT_STRIPE_SIZE, ShardCount, ShardStripeSize}; #[derive(Parser)] pub(super) struct DescribeKeyCommand { /// Key material in one of the forms: hex, span attributes captured from log, reltag blocknum input: Vec<String>, /// The number of shards to calculate what Keys placement would be. #[arg(long)] shard_count: Option<CustomShardCount>, /// The sharding stripe size. /// /// The default is hardcoded. It makes no sense to provide this without providing /// `--shard-count`. #[arg(long, requires = "shard_count")] stripe_size: Option<u32>, } /// Sharded shard count without unsharded count, which the actual ShardCount supports. #[derive(Clone, Copy)] pub(super) struct CustomShardCount(std::num::NonZeroU8); #[derive(Debug, thiserror::Error)] pub(super) enum InvalidShardCount { #[error(transparent)] ParsingFailed(#[from] std::num::ParseIntError), #[error("too few shards")] TooFewShards, } impl FromStr for CustomShardCount { type Err = InvalidShardCount; fn from_str(s: &str) -> Result<Self, Self::Err> { let inner: std::num::NonZeroU8 = s.parse()?; if inner.get() < 2 { Err(InvalidShardCount::TooFewShards) } else { Ok(CustomShardCount(inner)) } } } impl From<CustomShardCount> for ShardCount { fn from(value: CustomShardCount) -> Self { ShardCount::new(value.0.get()) } } impl DescribeKeyCommand { pub(super) fn execute(self) { let DescribeKeyCommand { input, shard_count, stripe_size, } = self; let material = KeyMaterial::try_from(input.as_slice()).unwrap(); let kind = material.kind(); let key = Key::from(material); println!("parsed from {kind}: {key}:"); println!(); println!("{key:?}"); macro_rules! kind_query { ([$($name:ident),*$(,)?]) => {{[$(kind_query!($name)),*]}}; ($name:ident) => {{ let s: &'static str = stringify!($name); let s = s.strip_prefix("is_").unwrap_or(s); let s = s.strip_suffix("_key").unwrap_or(s); #[allow(clippy::needless_borrow)] (s, key.$name()) }}; } // the current characterization is a mess of these boolean queries and separate // "recognization". I think it accurately represents how strictly we model the Key // right now, but could of course be made less confusing. let queries = kind_query!([ is_rel_block_key, is_rel_vm_block_key, is_rel_fsm_block_key, is_slru_block_key, is_inherited_key, is_rel_size_key, is_slru_segment_size_key, ]); let recognized_kind = "recognized kind"; let metadata_key = "metadata key"; let shard_placement = "shard placement"; let longest = queries .iter() .map(|t| t.0) .chain([recognized_kind, metadata_key, shard_placement]) .map(|s| s.len()) .max() .unwrap(); let colon = 1; let padding = 1; for (name, is) in queries { let width = longest - name.len() + colon + padding; println!("{}{:width$}{}", name, ":", is); } let width = longest - recognized_kind.len() + colon + padding; println!( "{}{:width$}{:?}", recognized_kind, ":", RecognizedKeyKind::new(key), ); if let Some(shard_count) = shard_count { // seeing the sharding placement might be confusing, so leave it out unless shard // count was given. let stripe_size = stripe_size .map(ShardStripeSize) .unwrap_or(DEFAULT_STRIPE_SIZE); println!( "# placement with shard_count: {} and stripe_size: {}:", shard_count.0, stripe_size.0 ); let width = longest - shard_placement.len() + colon + padding; println!( "{}{:width$}{:?}", shard_placement, ":", pageserver_api::shard::describe(&key, shard_count.into(), stripe_size) ); } } } /// Hand-wavy "inputs we accept" for a key. #[derive(Debug)] pub(super) enum KeyMaterial { Hex(Key), String(SpanAttributesFromLogs), Split(RelTag, BlockNumber), } impl KeyMaterial { fn kind(&self) -> &'static str { match self { KeyMaterial::Hex(_) => "hex", KeyMaterial::String(_) | KeyMaterial::Split(_, _) => "split", } } } impl From<KeyMaterial> for Key { fn from(value: KeyMaterial) -> Self { match value { KeyMaterial::Hex(key) => key, KeyMaterial::String(SpanAttributesFromLogs(rt, blocknum)) | KeyMaterial::Split(rt, blocknum) => { pageserver_api::key::rel_block_to_key(rt, blocknum) } } } } impl<S: AsRef<str>> TryFrom<&[S]> for KeyMaterial { type Error = anyhow::Error; fn try_from(value: &[S]) -> Result<Self, Self::Error> { match value { [] => anyhow::bail!( "need 1..N positional arguments describing the key, try hex or a log line" ), [one] => { let one = one.as_ref(); let key = Key::from_hex(one).map(KeyMaterial::Hex); let attrs = SpanAttributesFromLogs::from_str(one).map(KeyMaterial::String); match (key, attrs) { (Ok(key), _) => Ok(key), (_, Ok(s)) => Ok(s), (Err(e1), Err(e2)) => anyhow::bail!( "failed to parse {one:?} as hex or span attributes:\n- {e1:#}\n- {e2:#}" ), } } more => { // assume going left to right one of these is a reltag and then we find a blocknum // this works, because we don't have plain numbers at least right after reltag in // logs. for some definition of "works". let Some((reltag_at, reltag)) = more .iter() .map(AsRef::as_ref) .enumerate() .find_map(|(i, s)| { s.split_once("rel=") .map(|(_garbage, actual)| actual) .unwrap_or(s) .parse::<RelTag>() .ok() .map(|rt| (i, rt)) }) else { anyhow::bail!("found no RelTag in arguments"); }; let Some(blocknum) = more .iter() .map(AsRef::as_ref) .skip(reltag_at) .find_map(|s| { s.split_once("blkno=") .map(|(_garbage, actual)| actual) .unwrap_or(s) .parse::<BlockNumber>() .ok() }) else { anyhow::bail!("found no blocknum in arguments"); }; Ok(KeyMaterial::Split(reltag, blocknum)) } } } } #[derive(Debug)] pub(super) struct SpanAttributesFromLogs(RelTag, BlockNumber); impl std::str::FromStr for SpanAttributesFromLogs { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { // accept the span separator but do not require or fail if either is missing // "whatever{rel=1663/16389/24615 blkno=1052204 req_lsn=FFFFFFFF/FFFFFFFF}" let (_, reltag) = s .split_once("rel=") .ok_or_else(|| anyhow::anyhow!("cannot find 'rel='"))?; let reltag = reltag.split_whitespace().next().unwrap(); let (_, blocknum) = s .split_once("blkno=") .ok_or_else(|| anyhow::anyhow!("cannot find 'blkno='"))?; let blocknum = blocknum.split_whitespace().next().unwrap(); let reltag = reltag .parse() .with_context(|| format!("parse reltag from {reltag:?}"))?; let blocknum = blocknum .parse() .with_context(|| format!("parse blocknum from {blocknum:?}"))?; Ok(Self(reltag, blocknum)) } } #[derive(Debug)] #[allow(dead_code)] // debug print is used enum RecognizedKeyKind { DbDir, ControlFile, Checkpoint, AuxFilesV1, SlruDir(Result<SlruKind, u32>), RelMap(RelTagish<2>), RelDir(RelTagish<2>), AuxFileV2(Result<AuxFileV2, utils::Hex<[u8; 16]>>), } #[derive(Debug, PartialEq)] #[allow(unused)] enum AuxFileV2 { Recognized(&'static str, utils::Hex<[u8; 13]>), OtherWithPrefix(&'static str, utils::Hex<[u8; 13]>), Other(utils::Hex<[u8; 13]>), } impl RecognizedKeyKind { fn new(key: Key) -> Option<Self> { use RecognizedKeyKind::{ AuxFilesV1, Checkpoint, ControlFile, DbDir, RelDir, RelMap, SlruDir, }; let slru_dir_kind = pageserver_api::key::slru_dir_kind(&key); Some(match key { pageserver_api::key::DBDIR_KEY => DbDir, pageserver_api::key::CONTROLFILE_KEY => ControlFile, pageserver_api::key::CHECKPOINT_KEY => Checkpoint, pageserver_api::key::AUX_FILES_KEY => AuxFilesV1, _ if slru_dir_kind.is_some() => SlruDir(slru_dir_kind.unwrap()), _ if key.field1 == 0 && key.field4 == 0 && key.field5 == 0 && key.field6 == 0 => { RelMap([key.field2, key.field3].into()) } _ if key.field1 == 0 && key.field4 == 0 && key.field5 == 0 && key.field6 == 1 => { RelDir([key.field2, key.field3].into()) } _ if key.is_metadata_key() => RecognizedKeyKind::AuxFileV2( AuxFileV2::new(key).ok_or_else(|| utils::Hex(key.to_i128().to_be_bytes())), ), _ => return None, }) } } impl AuxFileV2 { fn new(key: Key) -> Option<AuxFileV2> { const EMPTY_HASH: [u8; 13] = { let mut out = [0u8; 13]; let hash = pageserver::aux_file::fnv_hash(b"").to_be_bytes(); let mut i = 3; while i < 16 { out[i - 3] = hash[i]; i += 1; } out }; let bytes = key.to_i128().to_be_bytes(); let hash = utils::Hex(<[u8; 13]>::try_from(&bytes[3..]).unwrap()); assert_eq!(EMPTY_HASH.len(), hash.0.len()); // TODO: we could probably find the preimages for the hashes Some(match (bytes[1], bytes[2]) { (1, 1) => AuxFileV2::Recognized("pg_logical/mappings/", hash), (1, 2) => AuxFileV2::Recognized("pg_logical/snapshots/", hash), (1, 3) if hash.0 == EMPTY_HASH => { AuxFileV2::Recognized("pg_logical/replorigin_checkpoint", hash) } (2, 1) => AuxFileV2::Recognized("pg_replslot/", hash), (3, 1) => AuxFileV2::Recognized("pg_stat/pgstat.stat", hash), (1, 0xff) => AuxFileV2::OtherWithPrefix("pg_logical/", hash), (0xff, 0xff) => AuxFileV2::Other(hash), _ => return None, }) } } /// Prefix of RelTag, currently only known use cases are the two item versions. /// /// Renders like a reltag with `/`, nothing else. struct RelTagish<const N: usize>([u32; N]); impl<const N: usize> From<[u32; N]> for RelTagish<N> { fn from(val: [u32; N]) -> Self { RelTagish(val) } } impl<const N: usize> std::fmt::Debug for RelTagish<N> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use std::fmt::Write as _; let mut first = true; self.0.iter().try_for_each(|x| { if !first { f.write_char('/')?; } first = false; write!(f, "{x}") }) } } #[cfg(test)] mod tests { use pageserver::aux_file::encode_aux_file_key; use super::*; #[test] fn hex_is_key_material() { let m = KeyMaterial::try_from(&["000000067F0000400200DF927900FFFFFFFF"][..]).unwrap(); assert!(matches!(m, KeyMaterial::Hex(_)), "{m:?}"); } #[test] fn single_positional_spanalike_is_key_material() { // why is this needed? if you are checking many, then copypaste starts to appeal let strings = [ ( line!(), "2024-05-15T15:33:49.873906Z ERROR page_service_conn_main{peer_addr=A:B}:process_query{tenant_id=C timeline_id=D}:handle_pagerequests:handle_get_page_at_lsn_request{rel=1663/208101/2620_fsm blkno=2 req_lsn=0/238D98C8}: error reading relation or page version: Read error: could not find data for key 000000067F00032CE5000000000000000001 (shard ShardNumber(0)) at LSN 0/1D0A16C1, request LSN 0/238D98C8, ancestor 0/0", ), (line!(), "rel=1663/208101/2620_fsm blkno=2"), (line!(), "rel=1663/208101/2620.1 blkno=2"), ]; let mut first: Option<Key> = None; for (line, example) in strings { let m = KeyMaterial::try_from(&[example][..]) .unwrap_or_else(|e| panic!("failed to parse example from line {line}: {e:?}")); let key = Key::from(m); if let Some(first) = first { assert_eq!(first, key); } else { first = Some(key); } } // not supporting this is rather accidential, but I think the input parsing is lenient // enough already KeyMaterial::try_from(&["1663/208101/2620_fsm 2"][..]).unwrap_err(); } #[test] fn multiple_spanlike_args() { let strings = [ ( line!(), &[ "process_query{tenant_id=C", "timeline_id=D}:handle_pagerequests:handle_get_page_at_lsn_request{rel=1663/208101/2620_fsm", "blkno=2", "req_lsn=0/238D98C8}", ][..], ), (line!(), &["rel=1663/208101/2620_fsm", "blkno=2"][..]), (line!(), &["1663/208101/2620_fsm", "2"][..]), ]; let mut first: Option<Key> = None; for (line, example) in strings { let m = KeyMaterial::try_from(example) .unwrap_or_else(|e| panic!("failed to parse example from line {line}: {e:?}")); let key = Key::from(m); if let Some(first) = first { assert_eq!(first, key); } else { first = Some(key); } } } #[test] fn recognized_auxfiles() { use AuxFileV2::*; let empty = [ 0x2e, 0x07, 0xbb, 0x01, 0x42, 0x62, 0xb8, 0x21, 0x75, 0x62, 0x95, 0xc5, 0x8d, ]; let foobar = [ 0x62, 0x79, 0x3c, 0x64, 0xbf, 0x6f, 0x0d, 0x35, 0x97, 0xba, 0x44, 0x6f, 0x18, ]; #[rustfmt::skip] let examples = [ (line!(), "pg_logical/mappings/foobar", Recognized("pg_logical/mappings/", utils::Hex(foobar))), (line!(), "pg_logical/snapshots/foobar", Recognized("pg_logical/snapshots/", utils::Hex(foobar))), (line!(), "pg_logical/replorigin_checkpoint", Recognized("pg_logical/replorigin_checkpoint", utils::Hex(empty))), (line!(), "pg_logical/foobar", OtherWithPrefix("pg_logical/", utils::Hex(foobar))), (line!(), "pg_replslot/foobar", Recognized("pg_replslot/", utils::Hex(foobar))), (line!(), "foobar", Other(utils::Hex(foobar))), ]; for (line, path, expected) in examples { let key = encode_aux_file_key(path); let recognized = AuxFileV2::new(key).unwrap_or_else(|| panic!("line {line} example failed")); assert_eq!(recognized, expected); } assert_eq!( AuxFileV2::new(Key::from_hex("600000102000000000000000000000000000").unwrap()), None, "example key has one too few 0 after 6 before 1" ); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/layer_map_analyzer.rs
pageserver/ctl/src/layer_map_analyzer.rs
//! Tool for extracting content-dependent metadata about layers. Useful for scanning real project layer files and evaluating the effectiveness of different heuristics on them. //! //! Currently it only analyzes holes, which are regions within the layer range that the layer contains no updates for. In the future it might do more analysis (maybe key quantiles?) but it should never return sensitive data. use std::cmp::Ordering; use std::collections::BinaryHeap; use std::ops::Range; use std::str::FromStr; use std::{fs, str}; use anyhow::{Result, anyhow}; use camino::{Utf8Path, Utf8PathBuf}; use pageserver::context::{DownloadBehavior, RequestContext}; use pageserver::page_cache::{self, PAGE_SZ}; use pageserver::task_mgr::TaskKind; use pageserver::tenant::block_io::FileBlockReader; use pageserver::tenant::disk_btree::{DiskBtreeReader, VisitDirection}; use pageserver::tenant::storage_layer::delta_layer::{DELTA_KEY_SIZE, Summary}; use pageserver::tenant::storage_layer::{LayerName, range_overlaps}; use pageserver::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME}; use pageserver::virtual_file::api::IoMode; use pageserver::virtual_file::{self, VirtualFile}; use pageserver_api::key::{KEY_SIZE, Key}; use utils::bin_ser::BeSer; use utils::lsn::Lsn; use crate::AnalyzeLayerMapCmd; const MIN_HOLE_LENGTH: i128 = (128 * 1024 * 1024 / PAGE_SZ) as i128; const DEFAULT_MAX_HOLES: usize = 10; /// Wrapper for key range to provide reverse ordering by range length for BinaryHeap #[derive(PartialEq, Eq)] pub struct Hole(Range<Key>); impl Ord for Hole { fn cmp(&self, other: &Self) -> Ordering { let other_len = other.0.end.to_i128() - other.0.start.to_i128(); let self_len = self.0.end.to_i128() - self.0.start.to_i128(); other_len.cmp(&self_len) } } impl PartialOrd for Hole { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } pub(crate) struct LayerFile { pub key_range: Range<Key>, pub lsn_range: Range<Lsn>, pub is_delta: bool, pub holes: Vec<Hole>, } impl LayerFile { fn skips(&self, key_range: &Range<Key>) -> bool { if !range_overlaps(&self.key_range, key_range) { return false; } let start = match self .holes .binary_search_by_key(&key_range.start, |hole| hole.0.start) { Ok(index) => index, Err(index) => { if index == 0 { return false; } index - 1 } }; self.holes[start].0.end >= key_range.end } } pub(crate) fn parse_filename(name: &str) -> anyhow::Result<LayerFile> { let layer_name = LayerName::from_str(name).map_err(|e| anyhow!("failed to parse layer name: {e}"))?; let holes = Vec::new(); Ok(LayerFile { key_range: layer_name.key_range().clone(), lsn_range: layer_name.lsn_as_range(), is_delta: layer_name.is_delta(), holes, }) } // Finds the max_holes largest holes, ignoring any that are smaller than MIN_HOLE_LENGTH" async fn get_holes(path: &Utf8Path, max_holes: usize, ctx: &RequestContext) -> Result<Vec<Hole>> { let file = VirtualFile::open(path, ctx).await?; let file_id = page_cache::next_file_id(); let block_reader = FileBlockReader::new(&file, file_id); let summary_blk = block_reader.read_blk(0, ctx).await?; let actual_summary = Summary::des_prefix(summary_blk.as_ref())?; let tree_reader = DiskBtreeReader::<_, DELTA_KEY_SIZE>::new( actual_summary.index_start_blk, actual_summary.index_root_blk, block_reader, ); // min-heap (reserve space for one more element added before eviction) let mut heap: BinaryHeap<Hole> = BinaryHeap::with_capacity(max_holes + 1); let mut prev_key: Option<Key> = None; tree_reader .visit( &[0u8; DELTA_KEY_SIZE], VisitDirection::Forwards, |key, _value| { let curr = Key::from_slice(&key[..KEY_SIZE]); if let Some(prev) = prev_key { if curr.to_i128() - prev.to_i128() >= MIN_HOLE_LENGTH { heap.push(Hole(prev..curr)); if heap.len() > max_holes { heap.pop(); // remove smallest hole } } } prev_key = Some(curr.next()); true }, ctx, ) .await?; let mut holes = heap.into_vec(); holes.sort_by_key(|hole| hole.0.start); Ok(holes) } pub(crate) async fn main(cmd: &AnalyzeLayerMapCmd) -> Result<()> { let storage_path = &cmd.path; let max_holes = cmd.max_holes.unwrap_or(DEFAULT_MAX_HOLES); let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error).with_scope_debug_tools(); // Initialize virtual_file (file desriptor cache) and page cache which are needed to access layer persistent B-Tree. pageserver::virtual_file::init( 10, virtual_file::api::IoEngineKind::StdFs, IoMode::preferred(), virtual_file::SyncMode::Sync, ); pageserver::page_cache::init(100); let mut total_delta_layers = 0usize; let mut total_image_layers = 0usize; let mut total_excess_layers = 0usize; for tenant in fs::read_dir(storage_path.join(TENANTS_SEGMENT_NAME))? { let tenant = tenant?; if !tenant.file_type()?.is_dir() { continue; } for timeline in fs::read_dir(tenant.path().join(TIMELINES_SEGMENT_NAME))? { let timeline = timeline?; if !timeline.file_type()?.is_dir() { continue; } // Collect sorted vec of layers and count deltas let mut layers = Vec::new(); let mut n_deltas = 0usize; for layer in fs::read_dir(timeline.path())? { let layer = layer?; if let Ok(mut layer_file) = parse_filename(&layer.file_name().into_string().unwrap()) { if layer_file.is_delta { let layer_path = Utf8PathBuf::from_path_buf(layer.path()).expect("non-Unicode path"); layer_file.holes = get_holes(&layer_path, max_holes, &ctx).await?; n_deltas += 1; } layers.push(layer_file); } } layers.sort_by_key(|layer| layer.lsn_range.end); // Count the number of holes and number of excess layers. // Excess layer is image layer generated when holes in delta layers are not considered. let mut n_excess_layers = 0usize; let mut n_holes = 0usize; for i in 0..layers.len() { if !layers[i].is_delta { let mut n_deltas_since_last_image = 0usize; let mut n_skipped = 0usize; let img_key_range = &layers[i].key_range; for j in (0..i).rev() { if range_overlaps(img_key_range, &layers[j].key_range) { if layers[j].is_delta { n_deltas_since_last_image += 1; if layers[j].skips(img_key_range) { n_skipped += 1; } } else { // Image layer is always dense, despite to the fact that it doesn't contain all possible // key values in the specified range: there are may be no keys in the storage belonging // to the image layer range but not present in the image layer. break; } } } if n_deltas_since_last_image >= 3 && n_deltas_since_last_image - n_skipped < 3 { // It is just approximation: it doesn't take in account all image coverage. // Moreover the new layer map doesn't count total deltas, but the max stack of overlapping deltas. n_excess_layers += 1; } n_holes += n_skipped; } } println!( "Tenant {} timeline {} delta layers {} image layers {} excess layers {} holes {}", tenant.file_name().into_string().unwrap(), timeline.file_name().into_string().unwrap(), n_deltas, layers.len() - n_deltas, n_excess_layers, n_holes ); total_delta_layers += n_deltas; total_image_layers += layers.len() - n_deltas; total_excess_layers += n_excess_layers; } } println!( "Total delta layers {total_delta_layers} image layers {total_image_layers} excess layers {total_excess_layers}" ); Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/download_remote_object.rs
pageserver/ctl/src/download_remote_object.rs
use camino::Utf8PathBuf; use clap::Parser; use tokio_util::sync::CancellationToken; /// Download a specific object from remote storage to a local file. /// /// The remote storage configuration is supplied via the `REMOTE_STORAGE_CONFIG` environment /// variable, in the same TOML format that the pageserver itself understands. This allows the /// command to work with any cloud supported by the `remote_storage` crate (currently AWS S3, /// Azure Blob Storage and local files), as long as the credentials are available via the /// standard environment variables expected by the underlying SDKs. /// /// Examples for setting the environment variable: /// /// ```bash /// # AWS S3 (region can also be provided via AWS_REGION) /// export REMOTE_STORAGE_CONFIG='remote_storage = { bucket_name = "my-bucket", bucket_region = "us-east-2" }' /// /// # Azure Blob Storage (account key picked up from AZURE_STORAGE_ACCOUNT_KEY) /// export REMOTE_STORAGE_CONFIG='remote_storage = { container = "my-container", account = "my-account" }' /// ``` #[derive(Parser)] pub(crate) struct DownloadRemoteObjectCmd { /// Key / path of the object to download (relative to the remote storage prefix). /// /// Examples: /// "wal/3aa8f.../00000001000000000000000A" /// "pageserver/v1/tenants/<tenant_id>/timelines/<timeline_id>/layer_12345" pub remote_path: String, /// Path of the local file to create. Existing file will be overwritten. /// /// Examples: /// "./segment" /// "/tmp/layer_12345.parquet" pub output_file: Utf8PathBuf, } pub(crate) async fn main(cmd: &DownloadRemoteObjectCmd) -> anyhow::Result<()> { use remote_storage::{DownloadOpts, GenericRemoteStorage, RemotePath, RemoteStorageConfig}; // Fetch remote storage configuration from the environment let config_str = std::env::var("REMOTE_STORAGE_CONFIG").map_err(|_| { anyhow::anyhow!( "'REMOTE_STORAGE_CONFIG' environment variable must be set to a valid remote storage TOML config" ) })?; let config = RemoteStorageConfig::from_toml_str(&config_str)?; // Initialise remote storage client let storage = GenericRemoteStorage::from_config(&config).await?; // RemotePath must be relative – leading slashes confuse the parser. let remote_path_str = cmd.remote_path.trim_start_matches('/'); let remote_path = RemotePath::from_string(remote_path_str)?; let cancel = CancellationToken::new(); println!( "Downloading '{remote_path}' from remote storage bucket {:?} ...", config.storage.bucket_name() ); // Start the actual download let download = storage .download(&remote_path, &DownloadOpts::default(), &cancel) .await?; // Stream to file let mut reader = tokio_util::io::StreamReader::new(download.download_stream); let tmp_path = cmd.output_file.with_extension("tmp"); let mut file = tokio::fs::File::create(&tmp_path).await?; tokio::io::copy(&mut reader, &mut file).await?; file.sync_all().await?; // Atomically move into place tokio::fs::rename(&tmp_path, &cmd.output_file).await?; println!( "Downloaded to '{}'. Last modified: {:?}, etag: {}", cmd.output_file, download.last_modified, download.etag ); Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/draw_timeline_dir.rs
pageserver/ctl/src/draw_timeline_dir.rs
//! A tool for visualizing the arrangement of layerfiles within a timeline. //! //! It reads filenames from stdin and prints a svg on stdout. The image is a plot in //! page-lsn space, where every delta layer is a rectangle and every image layer is a //! thick line. Legend: //! - The x axis (left to right) represents page index. //! - The y axis represents LSN, growing upwards. //! //! Coordinates in both axis are compressed for better readability. //! (see <https://medium.com/algorithms-digest/coordinate-compression-2fff95326fb>) //! //! The plain text API was chosen so that we can easily work with filenames from various //! sources; see the Usage section below for examples. //! //! # Usage //! //! ## Producing the SVG //! //! ```bash //! //! # local timeline dir //! ls test_output/test_pgbench\[neon-45-684\]/repo/tenants/$TENANT/timelines/$TIMELINE | \ //! grep "__" | cargo run --release --bin pagectl draw-timeline > out.svg //! //! # Layer map dump from `/v1/tenant/$TENANT/timeline/$TIMELINE/layer` //! (jq -r '.historic_layers[] | .layer_file_name' | cargo run -p pagectl draw-timeline) < layer-map.json > out.svg //! //! # From an `index_part.json` in S3 //! (jq -r '.layer_metadata | keys[]' | cargo run -p pagectl draw-timeline ) < index_part.json-00000016 > out.svg //! //! # enrich with lines for gc_cutoff and a child branch point //! cat <(jq -r '.historic_layers[] | .layer_file_name' < layers.json) <(echo -e 'gc_cutoff:0000001CE3FE32C9\nbranch:0000001DE3FE32C9') | cargo run --bin pagectl draw-timeline >| out.svg //! ``` //! //! ## Viewing //! //! **Inkscape** is better than the built-in viewers in browsers. //! //! After selecting a layer file rectangle, use "Open XML Editor" (Ctrl|Cmd + Shift + X) //! to see the layer file name in the comment field. //! //! ```bash //! //! # Linux //! inkscape out.svg //! //! # macOS //! /Applications/Inkscape.app/Contents/MacOS/inkscape out.svg //! //! ``` //! use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; use std::io::{self, BufRead}; use std::ops::Range; use std::path::PathBuf; use std::str::FromStr; use anyhow::{Context, Result}; use pageserver_api::key::Key; use svg_fmt::{BeginSvg, EndSvg, Fill, Stroke, rectangle, rgb}; use utils::lsn::Lsn; use utils::project_git_version; project_git_version!(GIT_VERSION); // Map values to their compressed coordinate - the index the value // would have in a sorted and deduplicated list of all values. fn build_coordinate_compression_map<T: Ord + Copy>(coords: Vec<T>) -> BTreeMap<T, usize> { let set: BTreeSet<T> = coords.into_iter().collect(); let mut map: BTreeMap<T, usize> = BTreeMap::new(); for (i, e) in set.iter().enumerate() { map.insert(*e, i); } map } fn parse_filename(name: &str) -> (Range<Key>, Range<Lsn>) { let split: Vec<&str> = name.split("__").collect(); let keys: Vec<&str> = split[0].split('-').collect(); // Remove the temporary file extension, e.g., remove the `.d20a.___temp` part from the following filename: // 000000067F000040490000404A00441B0000-000000067F000040490000404A00441B4000__000043483A34CE00.d20a.___temp let lsns = split[1].split('.').collect::<Vec<&str>>()[0]; let mut lsns: Vec<&str> = lsns.split('-').collect(); // The current format of the layer file name: 000000067F0000000400000B150100000000-000000067F0000000400000D350100000000__00000000014B7AC8-v1-00000001 // Handle generation number `-00000001` part if lsns.last().expect("should").len() == 8 { lsns.pop(); } // Handle version number `-v1` part if lsns.last().expect("should").starts_with('v') { lsns.pop(); } if lsns.len() == 1 { lsns.push(lsns[0]); } let keys = Key::from_hex(keys[0]).unwrap()..Key::from_hex(keys[1]).unwrap(); let lsns = Lsn::from_hex(lsns[0]).unwrap()..Lsn::from_hex(lsns[1]).unwrap(); (keys, lsns) } #[derive(Clone, Copy)] enum LineKind { GcCutoff, Branch, } impl From<LineKind> for Fill { fn from(value: LineKind) -> Self { match value { LineKind::GcCutoff => Fill::Color(rgb(255, 0, 0)), LineKind::Branch => Fill::Color(rgb(0, 255, 0)), } } } impl FromStr for LineKind { type Err = anyhow::Error; fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> { Ok(match s { "gc_cutoff" => LineKind::GcCutoff, "branch" => LineKind::Branch, _ => anyhow::bail!("unsupported linekind: {s}"), }) } } pub fn main() -> Result<()> { // Parse layer filenames from stdin struct Layer { filename: String, key_range: Range<Key>, lsn_range: Range<Lsn>, } let mut files: Vec<Layer> = vec![]; let stdin = io::stdin(); let mut lines: Vec<(Lsn, LineKind)> = vec![]; for (lineno, line) in stdin.lock().lines().enumerate() { let lineno = lineno + 1; let line = line.unwrap(); if let Some((kind, lsn)) = line.split_once(':') { let (kind, lsn) = LineKind::from_str(kind) .context("parse kind") .and_then(|kind| { if lsn.contains('/') { Lsn::from_str(lsn) } else { Lsn::from_hex(lsn) } .map(|lsn| (kind, lsn)) .context("parse lsn") }) .with_context(|| format!("parse {line:?} on {lineno}"))?; lines.push((lsn, kind)); continue; } let line = PathBuf::from_str(&line).unwrap(); let filename = line.file_name().unwrap(); let filename = filename.to_str().unwrap(); let (key_range, lsn_range) = parse_filename(filename); files.push(Layer { filename: filename.to_owned(), key_range, lsn_range, }); } // Collect all coordinates let mut keys: Vec<Key> = Vec::with_capacity(files.len()); let mut lsns: Vec<Lsn> = Vec::with_capacity(files.len() + lines.len()); for Layer { key_range: keyr, lsn_range: lsnr, .. } in &files { keys.push(keyr.start); keys.push(keyr.end); lsns.push(lsnr.start); lsns.push(lsnr.end); } lsns.extend(lines.iter().map(|(lsn, _)| *lsn)); // Analyze let key_map = build_coordinate_compression_map(keys); let lsn_map = build_coordinate_compression_map(lsns); // Initialize stats let mut num_deltas = 0; let mut num_images = 0; // Draw let stretch = 3.0; // Stretch out vertically for better visibility println!( "{}", BeginSvg { w: (key_map.len() + 10) as f32, h: stretch * lsn_map.len() as f32 } ); let xmargin = 0.05; // Height-dependent margin to disambiguate overlapping deltas for Layer { filename, key_range: keyr, lsn_range: lsnr, } in &files { let key_start = *key_map.get(&keyr.start).unwrap(); let key_end = *key_map.get(&keyr.end).unwrap(); let key_diff = key_end - key_start; let lsn_max = lsn_map.len(); if key_start >= key_end { panic!("Invalid key range {key_start}-{key_end}"); } let lsn_start = *lsn_map.get(&lsnr.start).unwrap(); let lsn_end = *lsn_map.get(&lsnr.end).unwrap(); let mut lsn_diff = (lsn_end - lsn_start) as f32; let mut fill = Fill::None; let mut ymargin = 0.05 * lsn_diff; // Height-dependent margin to disambiguate overlapping deltas let mut lsn_offset = 0.0; // Fill in and thicken rectangle if it's an // image layer so that we can see it. match lsn_start.cmp(&lsn_end) { Ordering::Less => num_deltas += 1, Ordering::Equal => { num_images += 1; lsn_diff = 0.3; lsn_offset = -lsn_diff / 2.0; ymargin = 0.05; fill = Fill::Color(rgb(0, 0, 0)); } Ordering::Greater => panic!("Invalid lsn range {lsn_start}-{lsn_end}"), } println!( " {}", rectangle( 5.0 + key_start as f32 + stretch * xmargin, stretch * (lsn_max as f32 - (lsn_end as f32 - ymargin - lsn_offset)), key_diff as f32 - stretch * 2.0 * xmargin, stretch * (lsn_diff - 2.0 * ymargin) ) .fill(fill) .stroke(Stroke::Color(rgb(0, 0, 0), 0.1)) .border_radius(0.4) .comment(filename) ); } for (lsn, kind) in lines { let lsn_start = *lsn_map.get(&lsn).unwrap(); let lsn_end = lsn_start; let stretch = 2.0; let lsn_diff = 0.3; let lsn_offset = -lsn_diff / 2.0; let ymargin = 0.05; println!( "{}", rectangle( 0.0f32 + stretch * xmargin, stretch * (lsn_map.len() as f32 - (lsn_end as f32 - ymargin - lsn_offset)), (key_map.len() + 10) as f32, stretch * (lsn_diff - 2.0 * ymargin) ) .fill(kind) ); } println!("{EndSvg}"); eprintln!("num_images: {num_images}"); eprintln!("num_deltas: {num_deltas}"); Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/main.rs
pageserver/ctl/src/main.rs
//! A helper tool to manage pageserver binary files. //! Accepts a file as an argument, attempts to parse it with all ways possible //! and prints its interpreted context. //! //! Separate, `metadata` subcommand allows to print and update pageserver's metadata file. mod download_remote_object; mod draw_timeline_dir; mod index_part; mod key; mod layer_map_analyzer; mod layers; mod page_trace; use std::str::FromStr; use std::time::{Duration, SystemTime}; use camino::{Utf8Path, Utf8PathBuf}; use clap::{Parser, Subcommand}; use download_remote_object::DownloadRemoteObjectCmd; use index_part::IndexPartCmd; use layers::LayerCmd; use page_trace::PageTraceCmd; use pageserver::context::{DownloadBehavior, RequestContext}; use pageserver::page_cache; use pageserver::task_mgr::TaskKind; use pageserver::tenant::dump_layerfile_from_path; use pageserver::tenant::metadata::TimelineMetadata; use pageserver::virtual_file::api::IoMode; use pageserver::virtual_file::{self}; use pageserver_api::shard::TenantShardId; use postgres_ffi::ControlFileData; use remote_storage::{RemotePath, RemoteStorageConfig}; use tokio_util::sync::CancellationToken; use utils::id::TimelineId; use utils::logging::{self, LogFormat, TracingErrorLayerEnablement}; use utils::lsn::Lsn; use utils::project_git_version; project_git_version!(GIT_VERSION); #[derive(Parser)] #[command( version = GIT_VERSION, about = "Neon Pageserver binutils", long_about = "Reads pageserver (and related) binary files management utility" )] #[command(propagate_version = true)] struct CliOpts { #[command(subcommand)] command: Commands, } #[derive(Subcommand)] enum Commands { Metadata(MetadataCmd), #[command(subcommand)] IndexPart(IndexPartCmd), PrintLayerFile(PrintLayerFileCmd), TimeTravelRemotePrefix(TimeTravelRemotePrefixCmd), DrawTimeline {}, AnalyzeLayerMap(AnalyzeLayerMapCmd), #[command(subcommand)] Layer(LayerCmd), /// Debug print a hex key found from logs Key(key::DescribeKeyCommand), PageTrace(PageTraceCmd), DownloadRemoteObject(DownloadRemoteObjectCmd), } /// Read and update pageserver metadata file #[derive(Parser)] struct MetadataCmd { /// Input metadata file path metadata_path: Utf8PathBuf, /// Replace disk consistent Lsn disk_consistent_lsn: Option<Lsn>, /// Replace previous record Lsn prev_record_lsn: Option<Lsn>, /// Replace latest gc cuttoff latest_gc_cuttoff: Option<Lsn>, } #[derive(Parser)] struct PrintLayerFileCmd { /// Pageserver data path path: Utf8PathBuf, } /// Roll back the time for the specified prefix using S3 history. /// /// The command is fairly low level and powerful. Validation is only very light, /// so it is more powerful, and thus potentially more dangerous. #[derive(Parser)] struct TimeTravelRemotePrefixCmd { /// A configuration string for the remote_storage configuration. /// /// Example: `remote_storage = { bucket_name = "aws-storage-bucket-name", bucket_region = "us-east-2" }` config_toml_str: String, /// remote prefix to time travel recover. For safety reasons, we require it to contain /// a timeline or tenant ID in the prefix. prefix: String, /// Timestamp to travel to. Given in format like `2024-01-20T10:45:45Z`. Assumes UTC and second accuracy. travel_to: String, /// Timestamp of the start of the operation, must be after any changes we want to roll back and after. /// You can use a few seconds before invoking the command. Same format as `travel_to`. done_if_after: Option<String>, } #[derive(Parser)] struct AnalyzeLayerMapCmd { /// Pageserver data path path: Utf8PathBuf, /// Max holes max_holes: Option<usize>, } #[tokio::main] async fn main() -> anyhow::Result<()> { logging::init( LogFormat::Plain, TracingErrorLayerEnablement::EnableWithRustLogFilter, logging::Output::Stdout, )?; logging::replace_panic_hook_with_tracing_panic_hook().forget(); let cli = CliOpts::parse(); match cli.command { Commands::Layer(cmd) => { layers::main(&cmd).await?; } Commands::Metadata(cmd) => { handle_metadata(&cmd)?; } Commands::IndexPart(cmd) => { index_part::main(&cmd).await?; } Commands::DrawTimeline {} => { draw_timeline_dir::main()?; } Commands::AnalyzeLayerMap(cmd) => { layer_map_analyzer::main(&cmd).await?; } Commands::PrintLayerFile(cmd) => { if let Err(e) = read_pg_control_file(&cmd.path) { println!( "Failed to read input file as a pg control one: {e:#}\n\ Attempting to read it as layer file" ); print_layerfile(&cmd.path).await?; } } Commands::TimeTravelRemotePrefix(cmd) => { let timestamp = humantime::parse_rfc3339(&cmd.travel_to) .map_err(|_e| anyhow::anyhow!("Invalid time for travel_to: '{}'", cmd.travel_to))?; let done_if_after = if let Some(done_if_after) = &cmd.done_if_after { humantime::parse_rfc3339(done_if_after).map_err(|_e| { anyhow::anyhow!("Invalid time for done_if_after: '{}'", done_if_after) })? } else { const SAFETY_MARGIN: Duration = Duration::from_secs(3); tokio::time::sleep(SAFETY_MARGIN).await; // Convert to string representation and back to get rid of sub-second values let done_if_after = SystemTime::now(); tokio::time::sleep(SAFETY_MARGIN).await; done_if_after }; let timestamp = strip_subsecond(timestamp); let done_if_after = strip_subsecond(done_if_after); let Some(prefix) = validate_prefix(&cmd.prefix) else { println!("specified prefix '{}' failed validation", cmd.prefix); return Ok(()); }; let config = RemoteStorageConfig::from_toml_str(&cmd.config_toml_str)?; let storage = remote_storage::GenericRemoteStorage::from_config(&config).await; let cancel = CancellationToken::new(); // Complexity limit: as we are running this command locally, we should have a lot of memory available, and we do not // need to limit the number of versions we are going to delete. storage .unwrap() .time_travel_recover(Some(&prefix), timestamp, done_if_after, &cancel, None) .await?; } Commands::Key(dkc) => dkc.execute(), Commands::PageTrace(cmd) => page_trace::main(&cmd)?, Commands::DownloadRemoteObject(cmd) => { download_remote_object::main(&cmd).await?; } }; Ok(()) } fn read_pg_control_file(control_file_path: &Utf8Path) -> anyhow::Result<()> { let control_file = ControlFileData::decode(&std::fs::read(control_file_path)?)?; println!("{control_file:?}"); let control_file_initdb = Lsn(control_file.checkPoint); println!( "pg_initdb_lsn: {}, aligned: {}", control_file_initdb, control_file_initdb.align() ); Ok(()) } async fn print_layerfile(path: &Utf8Path) -> anyhow::Result<()> { // Basic initialization of things that don't change after startup virtual_file::init( 10, virtual_file::api::IoEngineKind::StdFs, IoMode::preferred(), virtual_file::SyncMode::Sync, ); page_cache::init(100); let ctx = RequestContext::new(TaskKind::DebugTool, DownloadBehavior::Error).with_scope_debug_tools(); dump_layerfile_from_path(path, true, &ctx).await } fn handle_metadata( MetadataCmd { metadata_path: path, disk_consistent_lsn, prev_record_lsn, latest_gc_cuttoff, }: &MetadataCmd, ) -> Result<(), anyhow::Error> { let metadata_bytes = std::fs::read(path)?; let mut meta = TimelineMetadata::from_bytes(&metadata_bytes)?; println!("Current metadata:\n{meta:?}"); let mut update_meta = false; // TODO: simplify this part if let Some(disk_consistent_lsn) = disk_consistent_lsn { meta = TimelineMetadata::new( *disk_consistent_lsn, meta.prev_record_lsn(), meta.ancestor_timeline(), meta.ancestor_lsn(), meta.latest_gc_cutoff_lsn(), meta.initdb_lsn(), meta.pg_version(), ); update_meta = true; } if let Some(prev_record_lsn) = prev_record_lsn { meta = TimelineMetadata::new( meta.disk_consistent_lsn(), Some(*prev_record_lsn), meta.ancestor_timeline(), meta.ancestor_lsn(), meta.latest_gc_cutoff_lsn(), meta.initdb_lsn(), meta.pg_version(), ); update_meta = true; } if let Some(latest_gc_cuttoff) = latest_gc_cuttoff { meta = TimelineMetadata::new( meta.disk_consistent_lsn(), meta.prev_record_lsn(), meta.ancestor_timeline(), meta.ancestor_lsn(), *latest_gc_cuttoff, meta.initdb_lsn(), meta.pg_version(), ); update_meta = true; } if update_meta { let metadata_bytes = meta.to_bytes()?; std::fs::write(path, metadata_bytes)?; } Ok(()) } /// Ensures that the given S3 prefix is sufficiently constrained. /// The command is very risky already and we don't want to expose something /// that allows usually unintentional and quite catastrophic time travel of /// an entire bucket, which would be a major catastrophy and away /// by only one character change (similar to "rm -r /home /username/foobar"). fn validate_prefix(prefix: &str) -> Option<RemotePath> { if prefix.is_empty() { // Empty prefix means we want to specify the *whole* bucket return None; } let components = prefix.split('/').collect::<Vec<_>>(); let (last, components) = { let last = components.last()?; if last.is_empty() { ( components.iter().nth_back(1)?, &components[..(components.len() - 1)], ) } else { (last, &components[..]) } }; 'valid: { if let Ok(_timeline_id) = TimelineId::from_str(last) { // Ends in either a tenant or timeline ID break 'valid; } if *last == "timelines" { if let Some(before_last) = components.iter().nth_back(1) { if let Ok(_tenant_id) = TenantShardId::from_str(before_last) { // Has a valid tenant id break 'valid; } } } return None; } RemotePath::from_string(prefix).ok() } fn strip_subsecond(timestamp: SystemTime) -> SystemTime { let ts_str = humantime::format_rfc3339_seconds(timestamp).to_string(); humantime::parse_rfc3339(&ts_str).expect("can't parse just created timestamp") } #[cfg(test)] mod tests { use super::*; #[test] fn test_validate_prefix() { assert_eq!(validate_prefix(""), None); assert_eq!(validate_prefix("/"), None); #[track_caller] fn assert_valid(prefix: &str) { let remote_path = RemotePath::from_string(prefix).unwrap(); assert_eq!(validate_prefix(prefix), Some(remote_path)); } assert_valid("wal/3aa8fcc61f6d357410b7de754b1d9001/641e5342083b2235ee3deb8066819683/"); // Path is not relative but absolute assert_eq!( validate_prefix( "/wal/3aa8fcc61f6d357410b7de754b1d9001/641e5342083b2235ee3deb8066819683/" ), None ); assert_valid("wal/3aa8fcc61f6d357410b7de754b1d9001/"); // Partial tenant IDs should be invalid, S3 will match all tenants with the specific ID prefix assert_eq!(validate_prefix("wal/3aa8fcc61f6d357410b7d"), None); assert_eq!(validate_prefix("wal"), None); assert_eq!(validate_prefix("/wal/"), None); assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001"); // Partial tenant ID assert_eq!( validate_prefix("pageserver/v1/tenants/3aa8fcc61f6d357410b"), None ); assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001/timelines"); assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001-0004/timelines"); assert_valid("pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001/timelines/"); assert_valid( "pageserver/v1/tenants/3aa8fcc61f6d357410b7de754b1d9001/timelines/641e5342083b2235ee3deb8066819683", ); assert_eq!(validate_prefix("pageserver/v1/tenants/"), None); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/ctl/src/page_trace.rs
pageserver/ctl/src/page_trace.rs
use std::collections::HashMap; use std::io::BufReader; use camino::Utf8PathBuf; use clap::Parser; use itertools::Itertools as _; use pageserver_api::key::{CompactKey, Key}; use pageserver_api::models::PageTraceEvent; use pageserver_api::reltag::RelTag; /// Parses a page trace (as emitted by the `page_trace` timeline API), and outputs stats. #[derive(Parser)] pub(crate) struct PageTraceCmd { /// Trace input file. path: Utf8PathBuf, } pub(crate) fn main(cmd: &PageTraceCmd) -> anyhow::Result<()> { let mut file = BufReader::new(std::fs::OpenOptions::new().read(true).open(&cmd.path)?); let mut events: Vec<PageTraceEvent> = Vec::new(); loop { match bincode::deserialize_from(&mut file) { Ok(event) => events.push(event), Err(err) => { if let bincode::ErrorKind::Io(ref err) = *err { if err.kind() == std::io::ErrorKind::UnexpectedEof { break; } } return Err(err.into()); } } } let mut reads_by_relation: HashMap<RelTag, i64> = HashMap::new(); let mut reads_by_key: HashMap<CompactKey, i64> = HashMap::new(); for event in events { let key = Key::from_compact(event.key); let reltag = RelTag { spcnode: key.field2, dbnode: key.field3, relnode: key.field4, forknum: key.field5, }; *reads_by_relation.entry(reltag).or_default() += 1; *reads_by_key.entry(event.key).or_default() += 1; } let multi_read_keys = reads_by_key .into_iter() .filter(|(_, count)| *count > 1) .sorted_by_key(|(key, count)| (-*count, *key)) .collect_vec(); println!("Multi-read keys: {}", multi_read_keys.len()); for (key, count) in multi_read_keys { println!(" {key}: {count}"); } let reads_by_relation = reads_by_relation .into_iter() .sorted_by_key(|(rel, count)| (-*count, *rel)) .collect_vec(); println!("Reads by relation:"); for (reltag, count) in reads_by_relation { println!(" {reltag}: {count}"); } Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client_grpc/src/lib.rs
pageserver/client_grpc/src/lib.rs
mod client; mod pool; mod retry; pub use client::{PageserverClient, ShardSpec};
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client_grpc/src/client.rs
pageserver/client_grpc/src/client.rs
use std::collections::HashMap; use std::num::NonZero; use std::pin::pin; use std::sync::Arc; use std::time::{Duration, Instant}; use anyhow::anyhow; use arc_swap::ArcSwap; use futures::stream::FuturesUnordered; use futures::{FutureExt as _, StreamExt as _}; use tonic::codec::CompressionEncoding; use tracing::{debug, instrument}; use utils::logging::warn_slow; use crate::pool::{ChannelPool, ClientGuard, ClientPool, StreamGuard, StreamPool}; use crate::retry::Retry; use compute_api::spec::PageserverProtocol; use pageserver_page_api as page_api; use pageserver_page_api::GetPageSplitter; use utils::id::{TenantId, TimelineId}; use utils::shard::{ShardCount, ShardIndex, ShardNumber, ShardStripeSize}; /// Max number of concurrent clients per channel (i.e. TCP connection). New channels will be spun up /// when full. /// /// Normal requests are small, and we don't pipeline them, so we can afford a large number of /// streams per connection. /// /// TODO: tune all of these constants, and consider making them configurable. const MAX_CLIENTS_PER_CHANNEL: NonZero<usize> = NonZero::new(64).unwrap(); /// Max number of concurrent bulk GetPage streams per channel (i.e. TCP connection). These use a /// dedicated channel pool with a lower client limit, to avoid TCP-level head-of-line blocking and /// transmission delays. This also concentrates large window sizes on a smaller set of /// streams/connections, presumably reducing memory use. const MAX_BULK_CLIENTS_PER_CHANNEL: NonZero<usize> = NonZero::new(16).unwrap(); /// The batch size threshold at which a GetPage request will use the bulk stream pool. /// /// The gRPC initial window size is 64 KB. Each page is 8 KB, so let's avoid increasing the window /// size for the normal stream pool, and route requests for >= 5 pages (>32 KB) to the bulk pool. const BULK_THRESHOLD_BATCH_SIZE: usize = 5; /// The overall request call timeout, including retries and pool acquisition. /// TODO: should we retry forever? Should the caller decide? const CALL_TIMEOUT: Duration = Duration::from_secs(60); /// The per-request (retry attempt) timeout, including any lazy connection establishment. const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); /// The initial request retry backoff duration. The first retry does not back off. /// TODO: use a different backoff for ResourceExhausted (rate limiting)? Needs server support. const BASE_BACKOFF: Duration = Duration::from_millis(5); /// The maximum request retry backoff duration. const MAX_BACKOFF: Duration = Duration::from_secs(5); /// Threshold and interval for warning about slow operation. const SLOW_THRESHOLD: Duration = Duration::from_secs(3); /// A rich Pageserver gRPC client for a single tenant timeline. This client is more capable than the /// basic `page_api::Client` gRPC client, and supports: /// /// * Sharded tenants across multiple Pageservers. /// * Pooling of connections, clients, and streams for efficient resource use. /// * Concurrent use by many callers. /// * Internal handling of GetPage bidirectional streams. /// * Automatic retries. /// * Observability. /// /// The client has dedicated connection/client/stream pools per shard, for resource reuse. These /// pools are unbounded: we allow scaling out as many concurrent streams as needed to serve all /// concurrent callers, which mostly eliminates head-of-line blocking. Idle streams are fairly /// cheap: the server task currently uses 26 KB of memory, so we can comfortably fit 100,000 /// concurrent idle streams (2.5 GB memory). The worst case degenerates to the old libpq case with /// one stream per backend, but without the TCP connection overhead. In the common case we expect /// significantly lower stream counts due to stream sharing, driven e.g. by idle backends, LFC hits, /// read coalescing, sharding (backends typically only talk to one shard at a time), etc. /// /// TODO: this client does not support base backups or LSN leases, as these are only used by /// compute_ctl. Consider adding this, but LSN leases need concurrent requests on all shards. pub struct PageserverClient { /// The tenant ID. tenant_id: TenantId, /// The timeline ID. timeline_id: TimelineId, /// The JWT auth token for this tenant, if any. auth_token: Option<String>, /// The compression to use, if any. compression: Option<CompressionEncoding>, /// The shards for this tenant. shards: ArcSwap<Shards>, } impl PageserverClient { /// Creates a new Pageserver client for a given tenant and timeline. Uses the Pageservers given /// in the shard spec, which must be complete and must use gRPC URLs. pub fn new( tenant_id: TenantId, timeline_id: TimelineId, shard_spec: ShardSpec, auth_token: Option<String>, compression: Option<CompressionEncoding>, ) -> anyhow::Result<Self> { let shards = Shards::new( tenant_id, timeline_id, shard_spec, auth_token.clone(), compression, )?; Ok(Self { tenant_id, timeline_id, auth_token, compression, shards: ArcSwap::new(Arc::new(shards)), }) } /// Updates the shards from the given shard spec. In-flight requests will complete using the /// existing shards, but may retry with the new shards if they fail. /// /// TODO: verify that in-flight requests are allowed to complete, and that the old pools are /// properly spun down and dropped afterwards. pub fn update_shards(&self, shard_spec: ShardSpec) -> anyhow::Result<()> { // Validate the shard spec. We should really use `ArcSwap::rcu` for this, to avoid races // with concurrent updates, but that involves creating a new `Shards` on every attempt, // which spins up a bunch of Tokio tasks and such. These should already be checked elsewhere // in the stack, and if they're violated then we already have problems elsewhere, so a // best-effort but possibly-racy check is okay here. let old = self.shards.load_full(); if shard_spec.count < old.count { return Err(anyhow!( "can't reduce shard count from {} to {}", old.count, shard_spec.count )); } if !old.count.is_unsharded() && shard_spec.stripe_size != old.stripe_size { return Err(anyhow!( "can't change stripe size from {} to {}", old.stripe_size.expect("always Some when sharded"), shard_spec.stripe_size.expect("always Some when sharded") )); } let shards = Shards::new( self.tenant_id, self.timeline_id, shard_spec, self.auth_token.clone(), self.compression, )?; self.shards.store(Arc::new(shards)); Ok(()) } /// Returns the total size of a database, as # of bytes. #[instrument(skip_all, fields(db_oid=%req.db_oid, lsn=%req.read_lsn))] pub async fn get_db_size( &self, req: page_api::GetDbSizeRequest, ) -> tonic::Result<page_api::GetDbSizeResponse> { debug!("sending request: {req:?}"); let resp = Self::with_retries(CALL_TIMEOUT, async |_| { // Relation metadata is only available on shard 0. let mut client = self.shards.load_full().get_zero().client().await?; Self::with_timeout(REQUEST_TIMEOUT, client.get_db_size(req)).await }) .await?; debug!("received response: {resp:?}"); Ok(resp) } /// Fetches pages. The `request_id` must be unique across all in-flight requests, and the /// `attempt` must be 0 (incremented on retry). Automatically splits requests that straddle /// shard boundaries, and assembles the responses. /// /// Unlike `page_api::Client`, this automatically converts `status_code` into `tonic::Status` /// errors. All responses will have `GetPageStatusCode::Ok`. #[instrument(skip_all, fields( req_id = %req.request_id, class = %req.request_class, rel = %req.rel, blkno = %req.block_numbers[0], blks = %req.block_numbers.len(), lsn = %req.read_lsn, ))] pub async fn get_page( &self, req: page_api::GetPageRequest, ) -> tonic::Result<page_api::GetPageResponse> { // Make sure we have at least one page. if req.block_numbers.is_empty() { return Err(tonic::Status::invalid_argument("no block number")); } // The request attempt must be 0. The client will increment it internally. if req.request_id.attempt != 0 { return Err(tonic::Status::invalid_argument("request attempt must be 0")); } debug!("sending request: {req:?}"); // The shards may change while we're fetching pages. We execute the request using a stable // view of the shards (especially important for requests that span shards), but retry the // top-level (pre-split) request to pick up shard changes. This can lead to unnecessary // retries and re-splits in some cases where requests span shards, but these are expected to // be rare. // // TODO: the gRPC server and client doesn't yet properly support shard splits. Revisit this // once we figure out how to handle these. let resp = Self::with_retries(CALL_TIMEOUT, async |attempt| { let mut req = req.clone(); req.request_id.attempt = attempt as u32; let shards = self.shards.load_full(); Self::with_timeout(REQUEST_TIMEOUT, Self::get_page_with_shards(req, &shards)).await }) .await?; debug!("received response: {resp:?}"); Ok(resp) } /// Fetches pages using the given shards. This uses a stable view of the shards, regardless of /// concurrent shard updates. Does not retry internally, but is retried by `get_page()`. async fn get_page_with_shards( req: page_api::GetPageRequest, shards: &Shards, ) -> tonic::Result<page_api::GetPageResponse> { // Fast path: request is for a single shard. if let Some(shard_id) = GetPageSplitter::for_single_shard(&req, shards.count, shards.stripe_size)? { return Self::get_page_with_shard(req, shards.get(shard_id)?).await; } // Request spans multiple shards. Split it, dispatch concurrent per-shard requests, and // reassemble the responses. let mut splitter = GetPageSplitter::split(req, shards.count, shards.stripe_size)?; let mut shard_requests = FuturesUnordered::new(); for (shard_id, shard_req) in splitter.drain_requests() { let future = Self::get_page_with_shard(shard_req, shards.get(shard_id)?) .map(move |result| result.map(|resp| (shard_id, resp))); shard_requests.push(future); } while let Some((shard_id, shard_response)) = shard_requests.next().await.transpose()? { splitter.add_response(shard_id, shard_response)?; } Ok(splitter.collect_response()?) } /// Fetches pages on the given shard. Does not retry internally. async fn get_page_with_shard( req: page_api::GetPageRequest, shard: &Shard, ) -> tonic::Result<page_api::GetPageResponse> { let mut stream = shard.stream(Self::is_bulk(&req)).await?; let resp = stream.send(req.clone()).await?; // Convert per-request errors into a tonic::Status. if resp.status_code != page_api::GetPageStatusCode::Ok { return Err(tonic::Status::new( resp.status_code.into(), resp.reason.unwrap_or_else(|| String::from("unknown error")), )); } // Check that we received the expected pages. if req.rel != resp.rel { return Err(tonic::Status::internal(format!( "shard {} returned wrong relation, expected {} got {}", shard.id, req.rel, resp.rel ))); } if !req .block_numbers .iter() .copied() .eq(resp.pages.iter().map(|p| p.block_number)) { return Err(tonic::Status::internal(format!( "shard {} returned wrong pages, expected {:?} got {:?}", shard.id, req.block_numbers, resp.pages .iter() .map(|page| page.block_number) .collect::<Vec<_>>() ))); } Ok(resp) } /// Returns the size of a relation, as # of blocks. #[instrument(skip_all, fields(rel=%req.rel, lsn=%req.read_lsn))] pub async fn get_rel_size( &self, req: page_api::GetRelSizeRequest, ) -> tonic::Result<page_api::GetRelSizeResponse> { debug!("sending request: {req:?}"); let resp = Self::with_retries(CALL_TIMEOUT, async |_| { // Relation metadata is only available on shard 0. let mut client = self.shards.load_full().get_zero().client().await?; Self::with_timeout(REQUEST_TIMEOUT, client.get_rel_size(req)).await }) .await?; debug!("received response: {resp:?}"); Ok(resp) } /// Fetches an SLRU segment. #[instrument(skip_all, fields(kind=%req.kind, segno=%req.segno, lsn=%req.read_lsn))] pub async fn get_slru_segment( &self, req: page_api::GetSlruSegmentRequest, ) -> tonic::Result<page_api::GetSlruSegmentResponse> { debug!("sending request: {req:?}"); let resp = Self::with_retries(CALL_TIMEOUT, async |_| { // SLRU segments are only available on shard 0. let mut client = self.shards.load_full().get_zero().client().await?; Self::with_timeout(REQUEST_TIMEOUT, client.get_slru_segment(req)).await }) .await?; debug!("received response: {resp:?}"); Ok(resp) } /// Runs the given async closure with retries up to the given timeout. Only certain gRPC status /// codes are retried, see [`Retry::should_retry`]. Returns `DeadlineExceeded` on timeout. async fn with_retries<T, F, O>(timeout: Duration, f: F) -> tonic::Result<T> where F: FnMut(usize) -> O, // pass attempt number, starting at 0 O: Future<Output = tonic::Result<T>>, { Retry { timeout: Some(timeout), base_backoff: BASE_BACKOFF, max_backoff: MAX_BACKOFF, } .with(f) .await } /// Runs the given future with a timeout. Returns `DeadlineExceeded` on timeout. async fn with_timeout<T>( timeout: Duration, f: impl Future<Output = tonic::Result<T>>, ) -> tonic::Result<T> { let started = Instant::now(); tokio::time::timeout(timeout, f).await.map_err(|_| { tonic::Status::deadline_exceeded(format!( "request timed out after {:.3}s", started.elapsed().as_secs_f64() )) })? } /// Returns true if the request is considered a bulk request and should use the bulk pool. fn is_bulk(req: &page_api::GetPageRequest) -> bool { req.block_numbers.len() >= BULK_THRESHOLD_BATCH_SIZE } } /// Shard specification for a PageserverClient. pub struct ShardSpec { /// Maps shard indices to gRPC URLs. /// /// INVARIANT: every shard 0..count is present, and shard 0 is always present. /// INVARIANT: every URL is valid and uses grpc:// scheme. urls: HashMap<ShardIndex, String>, /// The shard count. /// /// NB: this is 0 for unsharded tenants, following `ShardIndex::unsharded()` convention. count: ShardCount, /// The stripe size for these shards. /// /// INVARIANT: None for unsharded tenants, Some for sharded. stripe_size: Option<ShardStripeSize>, } impl ShardSpec { /// Creates a new shard spec with the given URLs and stripe size. All shards must be given. /// The stripe size must be Some for sharded tenants, or None for unsharded tenants. pub fn new( urls: HashMap<ShardIndex, String>, stripe_size: Option<ShardStripeSize>, ) -> anyhow::Result<Self> { // Compute the shard count. let count = match urls.len() { 0 => return Err(anyhow!("no shards provided")), 1 => ShardCount::new(0), // NB: unsharded tenants use 0, like `ShardIndex::unsharded()` n if n > u8::MAX as usize => return Err(anyhow!("too many shards: {n}")), n => ShardCount::new(n as u8), }; // Validate the stripe size. if stripe_size.is_none() && !count.is_unsharded() { return Err(anyhow!("stripe size must be given for sharded tenants")); } if stripe_size.is_some() && count.is_unsharded() { return Err(anyhow!("stripe size can't be given for unsharded tenants")); } // Validate the shard spec. for (shard_id, url) in &urls { // The shard index must match the computed shard count, even for unsharded tenants. if shard_id.shard_count != count { return Err(anyhow!("invalid shard index {shard_id}, expected {count}")); } // The shard index' number and count must be consistent. if !shard_id.is_unsharded() && shard_id.shard_number.0 >= shard_id.shard_count.0 { return Err(anyhow!("invalid shard index {shard_id}")); } // The above conditions guarantee that we have all shards 0..count: len() matches count, // shard number < count, and numbers are unique (via hashmap). // Validate the URL. if PageserverProtocol::from_connstring(url)? != PageserverProtocol::Grpc { return Err(anyhow!("invalid shard URL {url}: must use gRPC")); } } Ok(Self { urls, count, stripe_size, }) } } /// Tracks the tenant's shards. struct Shards { /// Shards by shard index. /// /// INVARIANT: every shard 0..count is present. /// INVARIANT: shard 0 is always present. by_index: HashMap<ShardIndex, Shard>, /// The shard count. /// /// NB: this is 0 for unsharded tenants, following `ShardIndex::unsharded()` convention. count: ShardCount, /// The stripe size. /// /// INVARIANT: None for unsharded tenants, Some for sharded. stripe_size: Option<ShardStripeSize>, } impl Shards { /// Creates a new set of shards based on a shard spec. fn new( tenant_id: TenantId, timeline_id: TimelineId, shard_spec: ShardSpec, auth_token: Option<String>, compression: Option<CompressionEncoding>, ) -> anyhow::Result<Self> { // NB: the shard spec has already been validated when constructed. let mut shards = HashMap::with_capacity(shard_spec.urls.len()); for (shard_id, url) in shard_spec.urls { shards.insert( shard_id, Shard::new( url, tenant_id, timeline_id, shard_id, auth_token.clone(), compression, )?, ); } Ok(Self { by_index: shards, count: shard_spec.count, stripe_size: shard_spec.stripe_size, }) } /// Looks up the given shard. #[allow(clippy::result_large_err)] // TODO: check perf impact fn get(&self, shard_id: ShardIndex) -> tonic::Result<&Shard> { self.by_index .get(&shard_id) .ok_or_else(|| tonic::Status::not_found(format!("unknown shard {shard_id}"))) } /// Returns shard 0. fn get_zero(&self) -> &Shard { self.get(ShardIndex::new(ShardNumber(0), self.count)) .expect("always present") } } /// A single shard. Has dedicated resource pools with the following structure: /// /// * Channel pool: MAX_CLIENTS_PER_CHANNEL. /// * Client pool: unbounded. /// * Stream pool: unbounded. /// * Bulk channel pool: MAX_BULK_CLIENTS_PER_CHANNEL. /// * Bulk client pool: unbounded. /// * Bulk stream pool: unbounded. /// /// We use a separate bulk channel pool with a lower concurrency limit for large batch requests. /// This avoids TCP-level head-of-line blocking, and also concentrates large window sizes on a /// smaller set of streams/connections, which presumably reduces memory use. Neither of these pools /// are bounded, nor do they pipeline requests, so the latency characteristics should be mostly /// similar (except for TCP transmission time). /// /// TODO: since we never use bounded pools, we could consider removing the pool limiters. However, /// the code is fairly trivial, so we may as well keep them around for now in case we need them. struct Shard { /// The shard ID. id: ShardIndex, /// Unary gRPC client pool. client_pool: Arc<ClientPool>, /// GetPage stream pool. stream_pool: Arc<StreamPool>, /// GetPage stream pool for bulk requests. bulk_stream_pool: Arc<StreamPool>, } impl Shard { /// Creates a new shard. It has its own dedicated resource pools. fn new( url: String, tenant_id: TenantId, timeline_id: TimelineId, shard_id: ShardIndex, auth_token: Option<String>, compression: Option<CompressionEncoding>, ) -> anyhow::Result<Self> { // Shard pools for unary requests and non-bulk GetPage requests. let client_pool = ClientPool::new( ChannelPool::new(url.clone(), MAX_CLIENTS_PER_CHANNEL)?, tenant_id, timeline_id, shard_id, auth_token.clone(), compression, None, // unbounded ); let stream_pool = StreamPool::new(client_pool.clone(), None); // unbounded // Bulk GetPage stream pool for large batches (prefetches, sequential scans, vacuum, etc.). let bulk_stream_pool = StreamPool::new( ClientPool::new( ChannelPool::new(url, MAX_BULK_CLIENTS_PER_CHANNEL)?, tenant_id, timeline_id, shard_id, auth_token, compression, None, // unbounded, ), None, // unbounded ); Ok(Self { id: shard_id, client_pool, stream_pool, bulk_stream_pool, }) } /// Returns a pooled client for this shard. #[instrument(skip_all)] async fn client(&self) -> tonic::Result<ClientGuard> { warn_slow( "client pool acquisition", SLOW_THRESHOLD, pin!(self.client_pool.get()), ) .await } /// Returns a pooled stream for this shard. If `bulk` is `true`, uses the dedicated bulk pool. #[instrument(skip_all, fields(bulk))] async fn stream(&self, bulk: bool) -> tonic::Result<StreamGuard> { let pool = match bulk { false => &self.stream_pool, true => &self.bulk_stream_pool, }; warn_slow("stream pool acquisition", SLOW_THRESHOLD, pin!(pool.get())).await } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client_grpc/src/retry.rs
pageserver/client_grpc/src/retry.rs
use std::time::Duration; use futures::future::pending; use tokio::time::Instant; use tracing::{error, info, warn}; use utils::backoff::exponential_backoff_duration; /// A retry handler for Pageserver gRPC requests. /// /// This is used instead of backoff::retry for better control and observability. pub struct Retry { /// Timeout across all retry attempts. If None, retries forever. pub timeout: Option<Duration>, /// The initial backoff duration. The first retry does not use a backoff. pub base_backoff: Duration, /// The maximum backoff duration. pub max_backoff: Duration, } impl Retry { /// Runs the given async closure with timeouts and retries (exponential backoff). Logs errors, /// using the current tracing span for context. /// /// Only certain gRPC status codes are retried, see [`Self::should_retry`]. pub async fn with<T, F, O>(&self, mut f: F) -> tonic::Result<T> where F: FnMut(usize) -> O, // pass attempt number, starting at 0 O: Future<Output = tonic::Result<T>>, { let started = Instant::now(); let deadline = self.timeout.map(|timeout| started + timeout); let mut last_error = None; let mut retries = 0; loop { // Set up a future to wait for the backoff, if any, and run the closure. let backoff_and_try = async { // NB: sleep() always sleeps 1ms, even when given a 0 argument. See: // https://github.com/tokio-rs/tokio/issues/6866 if let Some(backoff) = self.backoff_duration(retries) { tokio::time::sleep(backoff).await; } f(retries).await }; // Set up a future for the timeout, if any. let timeout = async { match deadline { Some(deadline) => tokio::time::sleep_until(deadline).await, None => pending().await, } }; // Wait for the backoff and request, or bail out if the timeout is exceeded. let result = tokio::select! { result = backoff_and_try => result, _ = timeout => { let last_error = last_error.unwrap_or_else(|| { tonic::Status::deadline_exceeded(format!( "request timed out after {:.3}s", started.elapsed().as_secs_f64() )) }); error!( "giving up after {:.3}s and {retries} retries, last error {:?}: {}", started.elapsed().as_secs_f64(), last_error.code(), last_error.message(), ); return Err(last_error); } }; match result { // Success, return the result. Ok(result) => { if retries > 0 { info!( "request succeeded after {retries} retries in {:.3}s", started.elapsed().as_secs_f64(), ); } return Ok(result); } // Error, retry or bail out. Err(status) => { let (code, message) = (status.code(), status.message()); let attempt = retries + 1; if !Self::should_retry(code) { // NB: include the attempt here too. This isn't necessarily the first // attempt, because the error may change between attempts. error!( "request failed with {code:?}: {message}, not retrying (attempt {attempt})" ); return Err(status); } warn!("request failed with {code:?}: {message}, retrying (attempt {attempt})"); retries += 1; last_error = Some(status); } } } } /// Returns the backoff duration for the given retry attempt, or None for no backoff. The first /// attempt and first retry never backs off, so this returns None for 0 and 1 retries. fn backoff_duration(&self, retries: usize) -> Option<Duration> { let backoff = exponential_backoff_duration( (retries as u32).saturating_sub(1), // first retry does not back off self.base_backoff.as_secs_f64(), self.max_backoff.as_secs_f64(), ); (!backoff.is_zero()).then_some(backoff) } /// Returns true if the given status code should be retries. fn should_retry(code: tonic::Code) -> bool { match code { tonic::Code::Ok => panic!("unexpected Ok status code"), // These codes are transient, so retry them. tonic::Code::Aborted => true, tonic::Code::Cancelled => true, tonic::Code::DeadlineExceeded => true, // maybe transient slowness tonic::Code::ResourceExhausted => true, tonic::Code::Unavailable => true, // The following codes will like continue to fail, so don't retry. tonic::Code::AlreadyExists => false, tonic::Code::DataLoss => false, tonic::Code::FailedPrecondition => false, // NB: don't retry Internal. It is intended for serious errors such as invariant // violations, and is also used for client-side invariant checks that would otherwise // result in retry loops. tonic::Code::Internal => false, tonic::Code::InvalidArgument => false, tonic::Code::NotFound => false, tonic::Code::OutOfRange => false, tonic::Code::PermissionDenied => false, tonic::Code::Unauthenticated => false, tonic::Code::Unimplemented => false, tonic::Code::Unknown => false, } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client_grpc/src/pool.rs
pageserver/client_grpc/src/pool.rs
//! This module provides various Pageserver gRPC client resource pools. //! //! These pools are designed to reuse gRPC resources (connections, clients, and streams) across //! multiple concurrent callers (i.e. Postgres backends). This avoids the resource cost and latency //! of creating dedicated TCP connections and server tasks for every Postgres backend. //! //! Each resource has its own, nested pool. The pools are custom-built for the properties of each //! resource -- they are different enough that a generic pool isn't suitable. //! //! * ChannelPool: manages gRPC channels (TCP connections) to a single Pageserver. Multiple clients //! can acquire and use the same channel concurrently (via HTTP/2 stream multiplexing), up to a //! per-channel client limit. Channels are closed immediately when empty, and indirectly rely on //! client/stream idle timeouts. //! //! * ClientPool: manages gRPC clients for a single tenant shard. Each client acquires a (shared) //! channel from the ChannelPool for the client's lifetime. A client can only be acquired by a //! single caller at a time, and is returned to the pool when dropped. Idle clients are removed //! from the pool after a while to free up resources. //! //! * StreamPool: manages bidirectional gRPC GetPage streams. Each stream acquires a client from the //! ClientPool for the stream's lifetime. A stream can only be acquired by a single caller at a //! time, and is returned to the pool when dropped. Idle streams are removed from the pool after //! a while to free up resources. //! //! The stream only supports sending a single, synchronous request at a time, and does not support //! pipelining multiple requests from different callers onto the same stream -- instead, we scale //! out concurrent streams to improve throughput. There are many reasons for this design choice: //! //! * It (mostly) eliminates head-of-line blocking. A single stream is processed sequentially by //! a single server task, which may block e.g. on layer downloads, LSN waits, etc. //! //! * Cancellation becomes trivial, by closing the stream. Otherwise, if a caller goes away //! (e.g. because of a timeout), the request would still be processed by the server and block //! requests behind it in the stream. It might even block its own timeout retry. //! //! * Stream scheduling becomes significantly simpler and cheaper. //! //! * Individual callers can still use client-side batching for pipelining. //! //! * Idle streams are cheap. Benchmarks show that an idle GetPage stream takes up about 26 KB //! per stream (2.5 GB for 100,000 streams), so we can afford to scale out. //! //! Each channel corresponds to one TCP connection. Each client unary request and each stream //! corresponds to one HTTP/2 stream and server task. //! //! TODO: error handling (including custom error types). //! TODO: observability. use std::collections::BTreeMap; use std::num::NonZero; use std::ops::{Deref, DerefMut}; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; use futures::{Stream, StreamExt as _}; use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch}; use tokio_stream::wrappers::WatchStream; use tokio_util::sync::CancellationToken; use tonic::codec::CompressionEncoding; use tonic::transport::{Channel, Endpoint}; use pageserver_page_api as page_api; use utils::id::{TenantId, TimelineId}; use utils::shard::ShardIndex; /// Reap clients/streams that have been idle for this long. Channels are reaped immediately when /// empty, and indirectly rely on the client/stream idle timeouts. /// /// A stream's client will be reaped after 2x the idle threshold (first stream the client), but /// that's okay -- if the stream closes abruptly (e.g. due to timeout or cancellation), we want to /// keep its client around in the pool for a while. const REAP_IDLE_THRESHOLD: Duration = match cfg!(any(test, feature = "testing")) { false => Duration::from_secs(180), true => Duration::from_secs(1), // exercise reaping in tests }; /// Reap idle resources with this interval. const REAP_IDLE_INTERVAL: Duration = match cfg!(any(test, feature = "testing")) { false => Duration::from_secs(10), true => Duration::from_secs(1), // exercise reaping in tests }; /// A gRPC channel pool, for a single Pageserver. A channel is shared by many clients (via HTTP/2 /// stream multiplexing), up to `clients_per_channel` -- a new channel will be spun up beyond this. /// The pool does not limit the number of channels, and instead relies on `ClientPool` or /// `StreamPool` to limit the number of concurrent clients. /// /// The pool is always wrapped in an outer `Arc`, to allow long-lived guards across tasks/threads. /// /// TODO: consider prewarming a set of channels, to avoid initial connection latency. /// TODO: consider adding a circuit breaker for errors and fail fast. pub struct ChannelPool { /// Pageserver endpoint to connect to. endpoint: Endpoint, /// Max number of clients per channel. Beyond this, a new channel will be created. max_clients_per_channel: NonZero<usize>, /// Open channels. channels: Mutex<BTreeMap<ChannelID, ChannelEntry>>, /// Channel ID generator. next_channel_id: AtomicUsize, } type ChannelID = usize; struct ChannelEntry { /// The gRPC channel (i.e. TCP connection). Shared by multiple clients. channel: Channel, /// Number of clients using this channel. clients: usize, } impl ChannelPool { /// Creates a new channel pool for the given Pageserver endpoint. pub fn new<E>(endpoint: E, max_clients_per_channel: NonZero<usize>) -> anyhow::Result<Arc<Self>> where E: TryInto<Endpoint> + Send + Sync + 'static, <E as TryInto<Endpoint>>::Error: std::error::Error + Send + Sync, { Ok(Arc::new(Self { endpoint: endpoint.try_into()?, max_clients_per_channel, channels: Mutex::default(), next_channel_id: AtomicUsize::default(), })) } /// Acquires a gRPC channel for a client. Multiple clients may acquire the same channel. /// /// This never blocks (except for mutex acquisition). The channel is connected lazily on first /// use, and the `ChannelPool` does not have a channel limit. Channels will be re-established /// automatically on failure (TODO: verify). /// /// Callers should not clone the returned channel, and must hold onto the returned guard as long /// as the channel is in use. It is unfortunately not possible to enforce this: the Protobuf /// client requires an owned `Channel` and we don't have access to the channel's internal /// refcount. /// /// This is not performance-sensitive. It is only called when creating a new client, and clients /// are pooled and reused by `ClientPool`. The total number of channels will also be small. O(n) /// performance is therefore okay. pub fn get(self: &Arc<Self>) -> ChannelGuard { let mut channels = self.channels.lock().unwrap(); // Try to find an existing channel with available capacity. We check entries in BTreeMap // order, to fill up the lower-ordered channels first. The client/stream pools also prefer // clients with lower-ordered channel IDs first. This will cluster clients in lower-ordered // channels, and free up higher-ordered channels such that they can be reaped. for (&id, entry) in channels.iter_mut() { assert!( entry.clients <= self.max_clients_per_channel.get(), "channel overflow" ); assert_ne!(entry.clients, 0, "empty channel not reaped"); if entry.clients < self.max_clients_per_channel.get() { entry.clients += 1; return ChannelGuard { pool: Arc::downgrade(self), id, channel: Some(entry.channel.clone()), }; } } // Create a new channel. We connect lazily on first use, such that we don't block here and // other clients can join onto the same channel while it's connecting. let channel = self.endpoint.connect_lazy(); let id = self.next_channel_id.fetch_add(1, Ordering::Relaxed); let entry = ChannelEntry { channel: channel.clone(), clients: 1, // account for the guard below }; channels.insert(id, entry); ChannelGuard { pool: Arc::downgrade(self), id, channel: Some(channel), } } } /// Tracks a channel acquired from the pool. The owned inner channel can be obtained with `take()`, /// since the gRPC client requires an owned `Channel`. pub struct ChannelGuard { pool: Weak<ChannelPool>, id: ChannelID, channel: Option<Channel>, } impl ChannelGuard { /// Returns the inner owned channel. Panics if called more than once. The caller must hold onto /// the guard as long as the channel is in use, and should not clone it. pub fn take(&mut self) -> Channel { self.channel.take().expect("channel already taken") } } /// Returns the channel to the pool. The channel is closed when empty. impl Drop for ChannelGuard { fn drop(&mut self) { let Some(pool) = self.pool.upgrade() else { return; // pool was dropped }; let mut channels = pool.channels.lock().unwrap(); let entry = channels.get_mut(&self.id).expect("unknown channel"); assert!(entry.clients > 0, "channel underflow"); entry.clients -= 1; // Reap empty channels immediately. if entry.clients == 0 { channels.remove(&self.id); } } } /// A pool of gRPC clients for a single tenant shard. Each client acquires a channel from the inner /// `ChannelPool`. A client is only given out to single caller at a time. The pool limits the total /// number of concurrent clients to `max_clients` via semaphore. /// /// The pool is always wrapped in an outer `Arc`, to allow long-lived guards across tasks/threads. pub struct ClientPool { /// Tenant ID. tenant_id: TenantId, /// Timeline ID. timeline_id: TimelineId, /// Shard ID. shard_id: ShardIndex, /// Authentication token, if any. auth_token: Option<String>, /// Compression to use. compression: Option<CompressionEncoding>, /// Channel pool to acquire channels from. channel_pool: Arc<ChannelPool>, /// Limits the max number of concurrent clients for this pool. None if the pool is unbounded. limiter: Option<Arc<Semaphore>>, /// Idle pooled clients. Acquired clients are removed from here and returned on drop. /// /// The first client in the map will be acquired next. The map is sorted by client ID, which in /// turn is sorted by its channel ID, such that we prefer acquiring idle clients from /// lower-ordered channels. This allows us to free up and reap higher-ordered channels. idle: Mutex<BTreeMap<ClientID, ClientEntry>>, /// Reaps idle clients. idle_reaper: Reaper, /// Unique client ID generator. next_client_id: AtomicUsize, } type ClientID = (ChannelID, usize); struct ClientEntry { /// The pooled gRPC client. client: page_api::Client, /// The channel guard for the channel used by the client. channel_guard: ChannelGuard, /// The client has been idle since this time. All clients in `ClientPool::idle` are idle by /// definition, so this is the time when it was added back to the pool. idle_since: Instant, } impl ClientPool { /// Creates a new client pool for the given tenant shard. Channels are acquired from the given /// `ChannelPool`, which must point to a Pageserver that hosts the tenant shard. Allows up to /// `max_clients` concurrent clients, or unbounded if None. pub fn new( channel_pool: Arc<ChannelPool>, tenant_id: TenantId, timeline_id: TimelineId, shard_id: ShardIndex, auth_token: Option<String>, compression: Option<CompressionEncoding>, max_clients: Option<NonZero<usize>>, ) -> Arc<Self> { let pool = Arc::new(Self { tenant_id, timeline_id, shard_id, auth_token, compression, channel_pool, idle: Mutex::default(), idle_reaper: Reaper::new(REAP_IDLE_THRESHOLD, REAP_IDLE_INTERVAL), limiter: max_clients.map(|max| Arc::new(Semaphore::new(max.get()))), next_client_id: AtomicUsize::default(), }); pool.idle_reaper.spawn(&pool); pool } /// Gets a client from the pool, or creates a new one if necessary. Connections are established /// lazily and do not block, but this call can block if the pool is at `max_clients`. The client /// is returned to the pool when the guard is dropped. /// /// This is moderately performance-sensitive. It is called for every unary request, but these /// establish a new gRPC stream per request so they're already expensive. GetPage requests use /// the `StreamPool` instead. pub async fn get(self: &Arc<Self>) -> tonic::Result<ClientGuard> { // Acquire a permit if the pool is bounded. let mut permit = None; if let Some(limiter) = self.limiter.clone() { permit = Some(limiter.acquire_owned().await.expect("never closed")); } // Fast path: acquire an idle client from the pool. if let Some((id, entry)) = self.idle.lock().unwrap().pop_first() { return Ok(ClientGuard { pool: Arc::downgrade(self), id, client: Some(entry.client), channel_guard: Some(entry.channel_guard), permit, }); } // Construct a new client. let mut channel_guard = self.channel_pool.get(); let client = page_api::Client::new( channel_guard.take(), self.tenant_id, self.timeline_id, self.shard_id, self.auth_token.clone(), self.compression, ) .map_err(|err| tonic::Status::internal(format!("failed to create client: {err}")))?; Ok(ClientGuard { pool: Arc::downgrade(self), id: ( channel_guard.id, self.next_client_id.fetch_add(1, Ordering::Relaxed), ), client: Some(client), channel_guard: Some(channel_guard), permit, }) } } impl Reapable for ClientPool { /// Reaps clients that have been idle since before the cutoff. fn reap_idle(&self, cutoff: Instant) { self.idle .lock() .unwrap() .retain(|_, entry| entry.idle_since >= cutoff) } } /// A client acquired from the pool. The inner client can be accessed via Deref. The client is /// returned to the pool when dropped. pub struct ClientGuard { pool: Weak<ClientPool>, id: ClientID, client: Option<page_api::Client>, // Some until dropped channel_guard: Option<ChannelGuard>, // Some until dropped permit: Option<OwnedSemaphorePermit>, // None if pool is unbounded } impl Deref for ClientGuard { type Target = page_api::Client; fn deref(&self) -> &Self::Target { self.client.as_ref().expect("not dropped") } } impl DerefMut for ClientGuard { fn deref_mut(&mut self) -> &mut Self::Target { self.client.as_mut().expect("not dropped") } } /// Returns the client to the pool. impl Drop for ClientGuard { fn drop(&mut self) { let Some(pool) = self.pool.upgrade() else { return; // pool was dropped }; let entry = ClientEntry { client: self.client.take().expect("dropped once"), channel_guard: self.channel_guard.take().expect("dropped once"), idle_since: Instant::now(), }; pool.idle.lock().unwrap().insert(self.id, entry); _ = self.permit; // returned on drop, referenced for visibility } } /// A pool of bidirectional gRPC streams. Currently only used for GetPage streams. Each stream /// acquires a client from the inner `ClientPool` for the stream's lifetime. /// /// Individual streams only send a single request at a time, and do not pipeline multiple callers /// onto the same stream. Instead, we scale out the number of concurrent streams. This is primarily /// to eliminate head-of-line blocking. See the module documentation for more details. /// /// TODO: consider making this generic over request and response types; not currently needed. pub struct StreamPool { /// The client pool to acquire clients from. Must be unbounded. client_pool: Arc<ClientPool>, /// Idle pooled streams. Acquired streams are removed from here and returned on drop. /// /// The first stream in the map will be acquired next. The map is sorted by stream ID, which is /// equivalent to the client ID and in turn sorted by its channel ID. This way we prefer /// acquiring idle streams from lower-ordered channels, which allows us to free up and reap /// higher-ordered channels. idle: Mutex<BTreeMap<StreamID, StreamEntry>>, /// Limits the max number of concurrent streams. None if the pool is unbounded. limiter: Option<Arc<Semaphore>>, /// Reaps idle streams. idle_reaper: Reaper, } /// The stream ID. Reuses the inner client ID. type StreamID = ClientID; /// A pooled stream. struct StreamEntry { /// The bidirectional stream. stream: BiStream, /// The time when this stream was last used, i.e. when it was put back into `StreamPool::idle`. idle_since: Instant, } /// A bidirectional GetPage stream and its client. Can send requests and receive responses. struct BiStream { /// The owning client. Holds onto the channel slot while the stream is alive. client: ClientGuard, /// Stream for sending requests. Uses a watch channel, so it can only send a single request at a /// time, and the caller must await the response before sending another request. This is /// enforced by `StreamGuard::send`. sender: watch::Sender<page_api::GetPageRequest>, /// Stream for receiving responses. receiver: Pin<Box<dyn Stream<Item = tonic::Result<page_api::GetPageResponse>> + Send>>, } impl StreamPool { /// Creates a new stream pool, using the given client pool. It will use up to `max_streams` /// concurrent streams. /// /// The client pool must be unbounded. The stream pool will enforce its own limits, and because /// streams are long-lived they can cause persistent starvation if they exhaust the client pool. /// The stream pool should generally have its own dedicated client pool (but it can share a /// channel pool with others since these are always unbounded). pub fn new(client_pool: Arc<ClientPool>, max_streams: Option<NonZero<usize>>) -> Arc<Self> { assert!(client_pool.limiter.is_none(), "bounded client pool"); let pool = Arc::new(Self { client_pool, idle: Mutex::default(), limiter: max_streams.map(|max_streams| Arc::new(Semaphore::new(max_streams.get()))), idle_reaper: Reaper::new(REAP_IDLE_THRESHOLD, REAP_IDLE_INTERVAL), }); pool.idle_reaper.spawn(&pool); pool } /// Acquires an available stream from the pool, or spins up a new stream if all streams are /// full. Returns a guard that can be used to send requests and await the responses. Blocks if /// the pool is full. /// /// This is very performance-sensitive, as it is on the GetPage hot path. /// /// TODO: is a `Mutex<BTreeMap>` performant enough? Will it become too contended? We can't /// trivially use e.g. DashMap or sharding, because we want to pop lower-ordered streams first /// to free up higher-ordered channels. pub async fn get(self: &Arc<Self>) -> tonic::Result<StreamGuard> { // Acquire a permit if the pool is bounded. let mut permit = None; if let Some(limiter) = self.limiter.clone() { permit = Some(limiter.acquire_owned().await.expect("never closed")); } // Fast path: acquire an idle stream from the pool. if let Some((_, entry)) = self.idle.lock().unwrap().pop_first() { return Ok(StreamGuard { pool: Arc::downgrade(self), stream: Some(entry.stream), can_reuse: true, permit, }); } // Spin up a new stream. Uses a watch channel to send a single request at a time, since // `StreamGuard::send` enforces this anyway and it avoids unnecessary channel overhead. let mut client = self.client_pool.get().await?; let (req_tx, req_rx) = watch::channel(page_api::GetPageRequest::default()); let req_stream = WatchStream::from_changes(req_rx); let resp_stream = client.get_pages(req_stream).await?; Ok(StreamGuard { pool: Arc::downgrade(self), stream: Some(BiStream { client, sender: req_tx, receiver: Box::pin(resp_stream), }), can_reuse: true, permit, }) } } impl Reapable for StreamPool { /// Reaps streams that have been idle since before the cutoff. fn reap_idle(&self, cutoff: Instant) { self.idle .lock() .unwrap() .retain(|_, entry| entry.idle_since >= cutoff); } } /// A stream acquired from the pool. Returned to the pool when dropped, unless there are still /// in-flight requests on the stream, or the stream failed. pub struct StreamGuard { pool: Weak<StreamPool>, stream: Option<BiStream>, // Some until dropped can_reuse: bool, // returned to pool if true permit: Option<OwnedSemaphorePermit>, // None if pool is unbounded } impl StreamGuard { /// Sends a request on the stream and awaits the response. If the future is dropped before it /// resolves (e.g. due to a timeout or cancellation), the stream will be closed to cancel the /// request and is not returned to the pool. The same is true if the stream errors, in which /// case the caller can't send further requests on the stream. /// /// We only support sending a single request at a time, to eliminate head-of-line blocking. See /// module documentation for details. /// /// NB: errors are often returned as `GetPageResponse::status_code` instead of `tonic::Status` /// to avoid tearing down the stream for per-request errors. Callers must check this. pub async fn send( &mut self, req: page_api::GetPageRequest, ) -> tonic::Result<page_api::GetPageResponse> { let req_id = req.request_id; let stream = self.stream.as_mut().expect("not dropped"); // Mark the stream as not reusable while the request is in flight. We can't return the // stream to the pool until we receive the response, to avoid head-of-line blocking and // stale responses. Failed streams can't be reused either. if !self.can_reuse { return Err(tonic::Status::internal("stream can't be reused")); } self.can_reuse = false; // Send the request and receive the response. // // NB: this uses a watch channel, so it's unsafe to change this code to pipeline requests. stream .sender .send(req) .map_err(|_| tonic::Status::unavailable("stream closed"))?; let resp = stream .receiver .next() .await .ok_or_else(|| tonic::Status::unavailable("stream closed"))??; if resp.request_id != req_id { return Err(tonic::Status::internal(format!( "response ID {} does not match request ID {}", resp.request_id, req_id ))); } // Success, mark the stream as reusable. self.can_reuse = true; Ok(resp) } } impl Drop for StreamGuard { fn drop(&mut self) { let Some(pool) = self.pool.upgrade() else { return; // pool was dropped }; // If the stream isn't reusable, it can't be returned to the pool. if !self.can_reuse { return; } // Place the idle stream back into the pool. let entry = StreamEntry { stream: self.stream.take().expect("dropped once"), idle_since: Instant::now(), }; pool.idle .lock() .unwrap() .insert(entry.stream.client.id, entry); _ = self.permit; // returned on drop, referenced for visibility } } /// Periodically reaps idle resources from a pool. struct Reaper { /// The task check interval. interval: Duration, /// The threshold for reaping idle resources. threshold: Duration, /// Cancels the reaper task. Cancelled when the reaper is dropped. cancel: CancellationToken, } impl Reaper { /// Creates a new reaper. pub fn new(threshold: Duration, interval: Duration) -> Self { Self { cancel: CancellationToken::new(), threshold, interval, } } /// Spawns a task to periodically reap idle resources from the given task pool. The task is /// cancelled when the reaper is dropped. pub fn spawn(&self, pool: &Arc<impl Reapable>) { // NB: hold a weak pool reference, otherwise the task will prevent dropping the pool. let pool = Arc::downgrade(pool); let cancel = self.cancel.clone(); let (interval, threshold) = (self.interval, self.threshold); tokio::spawn(async move { loop { tokio::select! { _ = tokio::time::sleep(interval) => { let Some(pool) = pool.upgrade() else { return; // pool was dropped }; pool.reap_idle(Instant::now() - threshold); } _ = cancel.cancelled() => return, } } }); } } impl Drop for Reaper { fn drop(&mut self) { self.cancel.cancel(); // cancel reaper task } } /// A reapable resource pool. trait Reapable: Send + Sync + 'static { /// Reaps resources that have been idle since before the given cutoff. fn reap_idle(&self, cutoff: Instant); }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client/src/mgmt_api.rs
pageserver/client/src/mgmt_api.rs
use std::collections::{BTreeMap, HashMap}; use std::error::Error as _; use std::time::Duration; use bytes::Bytes; use detach_ancestor::AncestorDetached; use http_utils::error::HttpErrorBody; use pageserver_api::models::*; use pageserver_api::shard::TenantShardId; use postgres_versioninfo::PgMajorVersion; pub use reqwest::Body as ReqwestBody; use reqwest::{IntoUrl, Method, StatusCode, Url}; use utils::id::{TenantId, TimelineId}; use utils::lsn::Lsn; use crate::BlockUnblock; pub mod util; #[derive(Debug, Clone)] pub struct Client { mgmt_api_endpoint: String, authorization_header: Option<String>, client: reqwest::Client, } #[derive(thiserror::Error, Debug)] pub enum Error { #[error("send request: {0}{}", .0.source().map(|e| format!(": {e}")).unwrap_or_default())] SendRequest(reqwest::Error), #[error("receive body: {0}{}", .0.source().map(|e| format!(": {e}")).unwrap_or_default())] ReceiveBody(reqwest::Error), #[error("receive error body: {0}")] ReceiveErrorBody(String), #[error("pageserver API: {1}")] ApiError(StatusCode, String), #[error("Cancelled")] Cancelled, #[error("request timed out: {0}")] Timeout(String), } pub type Result<T> = std::result::Result<T, Error>; pub trait ResponseErrorMessageExt: Sized { fn error_from_body(self) -> impl std::future::Future<Output = Result<Self>> + Send; } impl ResponseErrorMessageExt for reqwest::Response { async fn error_from_body(self) -> Result<Self> { let status = self.status(); if !(status.is_client_error() || status.is_server_error()) { return Ok(self); } let url = self.url().to_owned(); Err(match self.json::<HttpErrorBody>().await { Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg), Err(_) => { Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), url)) } }) } } pub enum ForceAwaitLogicalSize { Yes, No, } impl Client { pub fn new(client: reqwest::Client, mgmt_api_endpoint: String, jwt: Option<&str>) -> Self { Self { mgmt_api_endpoint, authorization_header: jwt.map(|jwt| format!("Bearer {jwt}")), client, } } pub async fn list_tenants(&self) -> Result<Vec<pageserver_api::models::TenantInfo>> { let uri = format!("{}/v1/tenant", self.mgmt_api_endpoint); let resp = self.get(&uri).await?; resp.json().await.map_err(Error::ReceiveBody) } /// Send an HTTP request to an arbitrary path with a desired HTTP method and returning a streaming /// Response. This function is suitable for pass-through/proxy use cases where we don't care /// what the response content looks like. /// /// Use/add one of the properly typed methods below if you know aren't proxying, and /// know what kind of response you expect. pub async fn op_raw(&self, method: Method, path: String) -> Result<reqwest::Response> { debug_assert!(path.starts_with('/')); let uri = format!("{}{}", self.mgmt_api_endpoint, path); let mut req = self.client.request(method, uri); if let Some(value) = &self.authorization_header { req = req.header(reqwest::header::AUTHORIZATION, value); } req.send().await.map_err(Error::ReceiveBody) } pub async fn tenant_details( &self, tenant_shard_id: TenantShardId, ) -> Result<pageserver_api::models::TenantDetails> { let uri = format!("{}/v1/tenant/{tenant_shard_id}", self.mgmt_api_endpoint); self.get(uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn list_timelines( &self, tenant_shard_id: TenantShardId, ) -> Result<Vec<pageserver_api::models::TimelineInfo>> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline", self.mgmt_api_endpoint ); self.get(&uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_info( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, force_await_logical_size: ForceAwaitLogicalSize, ) -> Result<pageserver_api::models::TimelineInfo> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}", self.mgmt_api_endpoint ); let uri = match force_await_logical_size { ForceAwaitLogicalSize::Yes => format!("{}?force-await-logical-size={}", uri, true), ForceAwaitLogicalSize::No => uri, }; self.get(&uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn keyspace( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, ) -> Result<pageserver_api::models::partitioning::Partitioning> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/keyspace", self.mgmt_api_endpoint ); self.get(&uri) .await? .json() .await .map_err(Error::ReceiveBody) } async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> { self.request(Method::GET, uri, ()).await } fn start_request<U: reqwest::IntoUrl>( &self, method: Method, uri: U, ) -> reqwest::RequestBuilder { let req = self.client.request(method, uri); if let Some(value) = &self.authorization_header { req.header(reqwest::header::AUTHORIZATION, value) } else { req } } async fn request_noerror<B: serde::Serialize, U: reqwest::IntoUrl>( &self, method: Method, uri: U, body: B, ) -> Result<reqwest::Response> { self.start_request(method, uri) .json(&body) .send() .await .map_err(Error::ReceiveBody) } async fn request<B: serde::Serialize, U: reqwest::IntoUrl>( &self, method: Method, uri: U, body: B, ) -> Result<reqwest::Response> { let res = self.request_noerror(method, uri, body).await?; let response = res.error_from_body().await?; Ok(response) } pub async fn status(&self) -> Result<()> { let uri = format!("{}/v1/status", self.mgmt_api_endpoint); self.get(&uri).await?; Ok(()) } /// The tenant deletion API can return 202 if deletion is incomplete, or /// 404 if it is complete. Callers are responsible for checking the status /// code and retrying. Error codes other than 404 will return Err(). pub async fn tenant_delete(&self, tenant_shard_id: TenantShardId) -> Result<StatusCode> { let uri = format!("{}/v1/tenant/{tenant_shard_id}", self.mgmt_api_endpoint); match self.request(Method::DELETE, &uri, ()).await { Err(Error::ApiError(status_code, msg)) => { if status_code == StatusCode::NOT_FOUND { Ok(StatusCode::NOT_FOUND) } else { Err(Error::ApiError(status_code, msg)) } } Err(e) => Err(e), Ok(response) => Ok(response.status()), } } pub async fn tenant_time_travel_remote_storage( &self, tenant_shard_id: TenantShardId, timestamp: &str, done_if_after: &str, ) -> Result<()> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/time_travel_remote_storage?travel_to={timestamp}&done_if_after={done_if_after}", self.mgmt_api_endpoint ); self.request(Method::PUT, &uri, ()).await?; Ok(()) } pub async fn tenant_timeline_compact( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, force_image_layer_creation: bool, must_force_image_layer_creation: bool, scheduled: bool, wait_until_done: bool, ) -> Result<()> { let mut path = reqwest::Url::parse(&format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/compact", self.mgmt_api_endpoint )) .expect("Cannot build URL"); if force_image_layer_creation { path.query_pairs_mut() .append_pair("force_image_layer_creation", "true"); } if must_force_image_layer_creation { path.query_pairs_mut() .append_pair("must_force_image_layer_creation", "true"); } if scheduled { path.query_pairs_mut().append_pair("scheduled", "true"); } if wait_until_done { path.query_pairs_mut() .append_pair("wait_until_scheduled_compaction_done", "true"); path.query_pairs_mut() .append_pair("wait_until_uploaded", "true"); } self.request(Method::PUT, path, ()).await?; Ok(()) } /* BEGIN_HADRON */ pub async fn tenant_timeline_describe( &self, tenant_shard_id: &TenantShardId, timeline_id: &TimelineId, ) -> Result<TimelineInfo> { let mut path = reqwest::Url::parse(&format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}", self.mgmt_api_endpoint )) .expect("Cannot build URL"); path.query_pairs_mut() .append_pair("include-image-consistent-lsn", "true"); let response: reqwest::Response = self.request(Method::GET, path, ()).await?; let body = response.json().await.map_err(Error::ReceiveBody)?; Ok(body) } pub async fn list_tenant_visible_size(&self) -> Result<BTreeMap<TenantShardId, u64>> { let uri = format!("{}/v1/list_tenant_visible_size", self.mgmt_api_endpoint); let resp = self.get(&uri).await?; resp.json().await.map_err(Error::ReceiveBody) } /* END_HADRON */ pub async fn tenant_scan_remote_storage( &self, tenant_id: TenantId, ) -> Result<TenantScanRemoteStorageResponse> { let uri = format!( "{}/v1/tenant/{tenant_id}/scan_remote_storage", self.mgmt_api_endpoint ); let response = self.request(Method::GET, &uri, ()).await?; let body = response.json().await.map_err(Error::ReceiveBody)?; Ok(body) } pub async fn set_tenant_config(&self, req: &TenantConfigRequest) -> Result<()> { let uri = format!("{}/v1/tenant/config", self.mgmt_api_endpoint); self.request(Method::PUT, &uri, req).await?; Ok(()) } pub async fn patch_tenant_config(&self, req: &TenantConfigPatchRequest) -> Result<()> { let uri = format!("{}/v1/tenant/config", self.mgmt_api_endpoint); self.request(Method::PATCH, &uri, req).await?; Ok(()) } pub async fn tenant_secondary_download( &self, tenant_id: TenantShardId, wait: Option<std::time::Duration>, ) -> Result<(StatusCode, SecondaryProgress)> { let mut path = reqwest::Url::parse(&format!( "{}/v1/tenant/{}/secondary/download", self.mgmt_api_endpoint, tenant_id )) .expect("Cannot build URL"); if let Some(wait) = wait { path.query_pairs_mut() .append_pair("wait_ms", &format!("{}", wait.as_millis())); } let response = self.request(Method::POST, path, ()).await?; let status = response.status(); let progress: SecondaryProgress = response.json().await.map_err(Error::ReceiveBody)?; Ok((status, progress)) } pub async fn tenant_secondary_status( &self, tenant_shard_id: TenantShardId, ) -> Result<SecondaryProgress> { let path = reqwest::Url::parse(&format!( "{}/v1/tenant/{}/secondary/status", self.mgmt_api_endpoint, tenant_shard_id )) .expect("Cannot build URL"); self.request(Method::GET, path, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn tenant_heatmap_upload(&self, tenant_id: TenantShardId) -> Result<()> { let path = reqwest::Url::parse(&format!( "{}/v1/tenant/{}/heatmap_upload", self.mgmt_api_endpoint, tenant_id )) .expect("Cannot build URL"); self.request(Method::POST, path, ()).await?; Ok(()) } pub async fn location_config( &self, tenant_shard_id: TenantShardId, config: LocationConfig, flush_ms: Option<std::time::Duration>, lazy: bool, ) -> Result<()> { let req_body = TenantLocationConfigRequest { config }; let mut path = reqwest::Url::parse(&format!( "{}/v1/tenant/{}/location_config", self.mgmt_api_endpoint, tenant_shard_id )) // Should always work: mgmt_api_endpoint is configuration, not user input. .expect("Cannot build URL"); if lazy { path.query_pairs_mut().append_pair("lazy", "true"); } if let Some(flush_ms) = flush_ms { path.query_pairs_mut() .append_pair("flush_ms", &format!("{}", flush_ms.as_millis())); } self.request(Method::PUT, path, &req_body).await?; Ok(()) } pub async fn list_location_config(&self) -> Result<LocationConfigListResponse> { let path = format!("{}/v1/location_config", self.mgmt_api_endpoint); self.request(Method::GET, &path, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn get_location_config( &self, tenant_shard_id: TenantShardId, ) -> Result<Option<LocationConfig>> { let path = format!( "{}/v1/location_config/{tenant_shard_id}", self.mgmt_api_endpoint ); self.request(Method::GET, &path, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_create( &self, tenant_shard_id: TenantShardId, req: &TimelineCreateRequest, ) -> Result<TimelineInfo> { let uri = format!( "{}/v1/tenant/{}/timeline", self.mgmt_api_endpoint, tenant_shard_id ); self.request(Method::POST, &uri, req) .await? .json() .await .map_err(Error::ReceiveBody) } /// The timeline deletion API can return 201 if deletion is incomplete, or /// 403 if it is complete. Callers are responsible for checking the status /// code and retrying. Error codes other than 403 will return Err(). pub async fn timeline_delete( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, ) -> Result<StatusCode> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}", self.mgmt_api_endpoint ); match self.request(Method::DELETE, &uri, ()).await { Err(Error::ApiError(status_code, msg)) => { if status_code == StatusCode::NOT_FOUND { Ok(StatusCode::NOT_FOUND) } else { Err(Error::ApiError(status_code, msg)) } } Err(e) => Err(e), Ok(response) => Ok(response.status()), } } pub async fn timeline_detail( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, ) -> Result<TimelineInfo> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}", self.mgmt_api_endpoint ); self.request(Method::GET, &uri, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_archival_config( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, req: &TimelineArchivalConfigRequest, ) -> Result<()> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/archival_config", self.mgmt_api_endpoint ); self.request(Method::PUT, &uri, req) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_detach_ancestor( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, behavior: Option<DetachBehavior>, ) -> Result<AncestorDetached> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/detach_ancestor", self.mgmt_api_endpoint ); let mut uri = Url::parse(&uri) .map_err(|e| Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")))?; if let Some(behavior) = behavior { uri.query_pairs_mut() .append_pair("detach_behavior", &behavior.to_string()); } self.request(Method::PUT, uri, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_block_unblock_gc( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, dir: BlockUnblock, ) -> Result<()> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/{dir}_gc", self.mgmt_api_endpoint, ); self.request(Method::POST, &uri, ()).await.map(|_| ()) } pub async fn timeline_download_heatmap_layers( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, concurrency: Option<usize>, recurse: bool, ) -> Result<()> { let mut path = reqwest::Url::parse(&format!( "{}/v1/tenant/{}/timeline/{}/download_heatmap_layers", self.mgmt_api_endpoint, tenant_shard_id, timeline_id )) .expect("Cannot build URL"); path.query_pairs_mut() .append_pair("recurse", &format!("{recurse}")); if let Some(concurrency) = concurrency { path.query_pairs_mut() .append_pair("concurrency", &format!("{concurrency}")); } self.request(Method::POST, path, ()).await.map(|_| ()) } pub async fn tenant_reset(&self, tenant_shard_id: TenantShardId) -> Result<()> { let uri = format!( "{}/v1/tenant/{}/reset", self.mgmt_api_endpoint, tenant_shard_id ); self.request(Method::POST, &uri, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn tenant_shard_split( &self, tenant_shard_id: TenantShardId, req: TenantShardSplitRequest, ) -> Result<TenantShardSplitResponse> { let uri = format!( "{}/v1/tenant/{}/shard_split", self.mgmt_api_endpoint, tenant_shard_id ); self.request(Method::PUT, &uri, req) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_list( &self, tenant_shard_id: &TenantShardId, ) -> Result<Vec<TimelineInfo>> { let uri = format!( "{}/v1/tenant/{}/timeline", self.mgmt_api_endpoint, tenant_shard_id ); self.get(&uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn tenant_synthetic_size( &self, tenant_shard_id: TenantShardId, ) -> Result<TenantHistorySize> { let uri = format!( "{}/v1/tenant/{}/synthetic_size", self.mgmt_api_endpoint, tenant_shard_id ); self.get(&uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn put_io_engine( &self, engine: &pageserver_api::models::virtual_file::IoEngineKind, ) -> Result<()> { let uri = format!("{}/v1/io_engine", self.mgmt_api_endpoint); self.request(Method::PUT, uri, engine) .await? .json() .await .map_err(Error::ReceiveBody) } /// Configs io mode at runtime. pub async fn put_io_mode( &self, mode: &pageserver_api::models::virtual_file::IoMode, ) -> Result<()> { let uri = format!("{}/v1/io_mode", self.mgmt_api_endpoint); self.request(Method::PUT, uri, mode) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn get_utilization(&self) -> Result<PageserverUtilization> { let uri = format!("{}/v1/utilization", self.mgmt_api_endpoint); self.get(uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn top_tenant_shards( &self, request: TopTenantShardsRequest, ) -> Result<TopTenantShardsResponse> { let uri = format!("{}/v1/top_tenants", self.mgmt_api_endpoint); self.request(Method::POST, uri, request) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn layer_map_info( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, ) -> Result<LayerMapInfo> { let uri = format!( "{}/v1/tenant/{}/timeline/{}/layer", self.mgmt_api_endpoint, tenant_shard_id, timeline_id, ); self.get(&uri) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn layer_evict( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, layer_file_name: &str, ) -> Result<bool> { let uri = format!( "{}/v1/tenant/{}/timeline/{}/layer/{}", self.mgmt_api_endpoint, tenant_shard_id, timeline_id, layer_file_name ); let resp = self.request_noerror(Method::DELETE, &uri, ()).await?; match resp.status() { StatusCode::OK => Ok(true), StatusCode::NOT_MODIFIED => Ok(false), // TODO: dedupe this pattern / introduce separate error variant? status => Err(match resp.json::<HttpErrorBody>().await { Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg), Err(_) => { Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri)) } }), } } pub async fn layer_ondemand_download( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, layer_file_name: &str, ) -> Result<bool> { let uri = format!( "{}/v1/tenant/{}/timeline/{}/layer/{}", self.mgmt_api_endpoint, tenant_shard_id, timeline_id, layer_file_name ); let resp = self.request_noerror(Method::GET, &uri, ()).await?; match resp.status() { StatusCode::OK => Ok(true), StatusCode::NOT_MODIFIED => Ok(false), // TODO: dedupe this pattern / introduce separate error variant? status => Err(match resp.json::<HttpErrorBody>().await { Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg), Err(_) => { Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri)) } }), } } pub async fn ingest_aux_files( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, aux_files: HashMap<String, String>, ) -> Result<bool> { let uri = format!( "{}/v1/tenant/{}/timeline/{}/ingest_aux_files", self.mgmt_api_endpoint, tenant_shard_id, timeline_id ); let resp = self .request_noerror(Method::POST, &uri, IngestAuxFilesRequest { aux_files }) .await?; match resp.status() { StatusCode::OK => Ok(true), status => Err(match resp.json::<HttpErrorBody>().await { Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg), Err(_) => { Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri)) } }), } } pub async fn list_aux_files( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, lsn: Lsn, ) -> Result<HashMap<String, Bytes>> { let uri = format!( "{}/v1/tenant/{}/timeline/{}/list_aux_files", self.mgmt_api_endpoint, tenant_shard_id, timeline_id ); let resp = self .request_noerror(Method::POST, &uri, ListAuxFilesRequest { lsn }) .await?; match resp.status() { StatusCode::OK => { let resp: HashMap<String, Bytes> = resp.json().await.map_err(|e| { Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")) })?; Ok(resp) } status => Err(match resp.json::<HttpErrorBody>().await { Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg), Err(_) => { Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri)) } }), } } pub async fn import_basebackup( &self, tenant_id: TenantId, timeline_id: TimelineId, base_lsn: Lsn, end_lsn: Lsn, pg_version: PgMajorVersion, basebackup_tarball: ReqwestBody, ) -> Result<()> { let pg_version = pg_version.major_version_num(); let uri = format!( "{}/v1/tenant/{tenant_id}/timeline/{timeline_id}/import_basebackup?base_lsn={base_lsn}&end_lsn={end_lsn}&pg_version={pg_version}", self.mgmt_api_endpoint, ); self.start_request(Method::PUT, uri) .body(basebackup_tarball) .send() .await .map_err(Error::SendRequest)? .error_from_body() .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn import_wal( &self, tenant_id: TenantId, timeline_id: TimelineId, start_lsn: Lsn, end_lsn: Lsn, wal_tarball: ReqwestBody, ) -> Result<()> { let uri = format!( "{}/v1/tenant/{tenant_id}/timeline/{timeline_id}/import_wal?start_lsn={start_lsn}&end_lsn={end_lsn}", self.mgmt_api_endpoint, ); self.start_request(Method::PUT, uri) .body(wal_tarball) .send() .await .map_err(Error::SendRequest)? .error_from_body() .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn timeline_init_lsn_lease( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, lsn: Lsn, ) -> Result<LsnLease> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/lsn_lease", self.mgmt_api_endpoint, ); self.request(Method::POST, &uri, LsnLeaseRequest { lsn }) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn reset_alert_gauges(&self) -> Result<()> { let uri = format!( "{}/hadron-internal/reset_alert_gauges", self.mgmt_api_endpoint ); self.start_request(Method::POST, uri) .send() .await .map_err(Error::SendRequest)? .error_from_body() .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn wait_lsn( &self, tenant_shard_id: TenantShardId, request: TenantWaitLsnRequest, ) -> Result<StatusCode> { let uri = format!( "{}/v1/tenant/{tenant_shard_id}/wait_lsn", self.mgmt_api_endpoint, ); self.request_noerror(Method::POST, uri, request) .await .map(|resp| resp.status()) } pub async fn activate_post_import( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, activate_timeline_timeout: Duration, ) -> Result<TimelineInfo> { let uri = format!( "{}/v1/tenant/{}/timeline/{}/activate_post_import?timeline_activate_timeout_ms={}", self.mgmt_api_endpoint, tenant_shard_id, timeline_id, activate_timeline_timeout.as_millis() ); self.request(Method::PUT, uri, ()) .await? .json() .await .map_err(Error::ReceiveBody) } pub async fn update_feature_flag_spec(&self, spec: String) -> Result<()> { let uri = format!("{}/v1/feature_flag_spec", self.mgmt_api_endpoint); self.request(Method::POST, uri, spec) .await? .json() .await .map_err(Error::ReceiveBody) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client/src/lib.rs
pageserver/client/src/lib.rs
pub mod mgmt_api; pub mod page_service; /// For timeline_block_unblock_gc, distinguish the two different operations. This could be a bool. // If file structure is per-kind not per-feature then where to put this? #[derive(Clone, Copy)] pub enum BlockUnblock { Block, Unblock, } impl std::fmt::Display for BlockUnblock { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match self { BlockUnblock::Block => "block", BlockUnblock::Unblock => "unblock", }; f.write_str(s) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client/src/page_service.rs
pageserver/client/src/page_service.rs
use std::sync::{Arc, Mutex}; use futures::stream::{SplitSink, SplitStream}; use futures::{SinkExt, StreamExt}; use pageserver_api::pagestream_api::{ PagestreamBeMessage, PagestreamFeMessage, PagestreamGetPageRequest, PagestreamGetPageResponse, }; use pageserver_api::reltag::RelTag; use tokio::task::JoinHandle; use tokio_postgres::CopyOutStream; use tokio_util::sync::CancellationToken; use utils::id::{TenantId, TimelineId}; use utils::lsn::Lsn; pub struct Client { client: tokio_postgres::Client, cancel_on_client_drop: Option<tokio_util::sync::DropGuard>, conn_task: JoinHandle<()>, } pub struct BasebackupRequest { pub tenant_id: TenantId, pub timeline_id: TimelineId, pub lsn: Option<Lsn>, pub gzip: bool, } impl Client { pub async fn new(connstring: String) -> anyhow::Result<Self> { let (client, connection) = tokio_postgres::connect(&connstring, tokio_postgres::NoTls).await?; let conn_task_cancel = CancellationToken::new(); let conn_task = tokio::spawn({ let conn_task_cancel = conn_task_cancel.clone(); async move { tokio::select! { _ = conn_task_cancel.cancelled() => { } res = connection => { res.unwrap(); } } } }); Ok(Self { cancel_on_client_drop: Some(conn_task_cancel.drop_guard()), conn_task, client, }) } pub async fn pagestream( self, tenant_id: TenantId, timeline_id: TimelineId, ) -> anyhow::Result<PagestreamClient> { let copy_both: tokio_postgres::CopyBothDuplex<bytes::Bytes> = self .client .copy_both_simple(&format!("pagestream_v3 {tenant_id} {timeline_id}")) .await?; let (sink, stream) = copy_both.split(); // TODO: actually support splitting of the CopyBothDuplex so the lock inside this split adaptor goes away. let Client { cancel_on_client_drop, conn_task, client: _, } = self; let shared = Arc::new(Mutex::new(PagestreamShared::ConnTaskRunning( ConnTaskRunning { cancel_on_client_drop, conn_task, }, ))); Ok(PagestreamClient { sink: PagestreamSender { shared: shared.clone(), sink, }, stream: PagestreamReceiver { shared: shared.clone(), stream, }, shared, }) } pub async fn basebackup(&self, req: &BasebackupRequest) -> anyhow::Result<CopyOutStream> { let BasebackupRequest { tenant_id, timeline_id, lsn, gzip, } = req; let mut args = Vec::with_capacity(5); args.push("basebackup".to_string()); args.push(format!("{tenant_id}")); args.push(format!("{timeline_id}")); if let Some(lsn) = lsn { args.push(format!("{lsn}")); } if *gzip { args.push("--gzip".to_string()) } Ok(self.client.copy_out(&args.join(" ")).await?) } } /// Create using [`Client::pagestream`]. pub struct PagestreamClient { shared: Arc<Mutex<PagestreamShared>>, sink: PagestreamSender, stream: PagestreamReceiver, } pub struct PagestreamSender { #[allow(dead_code)] shared: Arc<Mutex<PagestreamShared>>, sink: SplitSink<tokio_postgres::CopyBothDuplex<bytes::Bytes>, bytes::Bytes>, } pub struct PagestreamReceiver { #[allow(dead_code)] shared: Arc<Mutex<PagestreamShared>>, stream: SplitStream<tokio_postgres::CopyBothDuplex<bytes::Bytes>>, } enum PagestreamShared { ConnTaskRunning(ConnTaskRunning), ConnTaskCancelledJoinHandleReturnedOrDropped, } struct ConnTaskRunning { cancel_on_client_drop: Option<tokio_util::sync::DropGuard>, conn_task: JoinHandle<()>, } pub struct RelTagBlockNo { pub rel_tag: RelTag, pub block_no: u32, } impl PagestreamClient { pub async fn shutdown(self) { let Self { shared, sink, stream, } = { self }; // The `copy_both` split into `sink` and `stream` contains internal channel sender, the receiver of which is polled by `conn_task`. // When `conn_task` observes the sender has been dropped, it sends a `FeMessage::CopyFail` into the connection. // (see https://github.com/neondatabase/rust-postgres/blob/2005bf79573b8add5cf205b52a2b208e356cc8b0/tokio-postgres/src/copy_both.rs#L56). // // If we drop(copy_both) first, but then immediately drop the `cancel_on_client_drop`, // the CopyFail mesage only makes it to the socket sometimes (i.e., it's a race). // // Further, the pageserver makes a lot of noise when it receives CopyFail. // Computes don't send it in practice, they just hard-close the connection. // // So, let's behave like the computes and suppress the CopyFail as follows: // kill the socket first, then drop copy_both. // // See also: https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-COPY // // NB: page_service doesn't have a use case to exit the `pagestream` mode currently. // => https://github.com/neondatabase/neon/issues/6390 let ConnTaskRunning { cancel_on_client_drop, conn_task, } = { let mut guard = shared.lock().unwrap(); match std::mem::replace( &mut *guard, PagestreamShared::ConnTaskCancelledJoinHandleReturnedOrDropped, ) { PagestreamShared::ConnTaskRunning(conn_task_running) => conn_task_running, PagestreamShared::ConnTaskCancelledJoinHandleReturnedOrDropped => unreachable!(), } }; let _ = cancel_on_client_drop.unwrap(); conn_task.await.unwrap(); // Now drop the split copy_both. drop(sink); drop(stream); } pub fn split(self) -> (PagestreamSender, PagestreamReceiver) { let Self { shared: _, sink, stream, } = self; (sink, stream) } pub async fn getpage( &mut self, req: PagestreamGetPageRequest, ) -> anyhow::Result<PagestreamGetPageResponse> { self.getpage_send(req).await?; self.getpage_recv().await } pub async fn getpage_send(&mut self, req: PagestreamGetPageRequest) -> anyhow::Result<()> { self.sink.getpage_send(req).await } pub async fn getpage_recv(&mut self) -> anyhow::Result<PagestreamGetPageResponse> { self.stream.getpage_recv().await } } impl PagestreamSender { // TODO: maybe make this impl Sink instead for better composability? pub async fn send(&mut self, msg: PagestreamFeMessage) -> anyhow::Result<()> { let msg = msg.serialize(); self.sink.send_all(&mut tokio_stream::once(Ok(msg))).await?; Ok(()) } pub async fn getpage_send(&mut self, req: PagestreamGetPageRequest) -> anyhow::Result<()> { self.send(PagestreamFeMessage::GetPage(req)).await } } impl PagestreamReceiver { // TODO: maybe make this impl Stream instead for better composability? pub async fn recv(&mut self) -> anyhow::Result<PagestreamBeMessage> { let next: Option<Result<bytes::Bytes, _>> = self.stream.next().await; let next: bytes::Bytes = next.unwrap()?; PagestreamBeMessage::deserialize(next) } pub async fn getpage_recv(&mut self) -> anyhow::Result<PagestreamGetPageResponse> { let next: PagestreamBeMessage = self.recv().await?; match next { PagestreamBeMessage::GetPage(p) => Ok(p), PagestreamBeMessage::Error(e) => anyhow::bail!("Error: {:?}", e), PagestreamBeMessage::Exists(_) | PagestreamBeMessage::Nblocks(_) | PagestreamBeMessage::DbSize(_) | PagestreamBeMessage::GetSlruSegment(_) => { anyhow::bail!( "unexpected be message kind in response to getpage request: {}", next.kind() ) } #[cfg(feature = "testing")] PagestreamBeMessage::Test(_) => { anyhow::bail!( "unexpected be message kind in response to getpage request: {}", next.kind() ) } } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/client/src/mgmt_api/util.rs
pageserver/client/src/mgmt_api/util.rs
//! Helpers to do common higher-level tasks with the [`Client`]. use std::sync::Arc; use pageserver_api::shard::TenantShardId; use tokio::task::JoinSet; use utils::id::{TenantId, TenantTimelineId}; use super::Client; /// Retrieve a list of all of the pageserver's timelines. /// /// Fails if there are sharded tenants present on the pageserver. pub async fn get_pageserver_tenant_timelines_unsharded( api_client: &Arc<Client>, ) -> anyhow::Result<Vec<TenantTimelineId>> { let mut timelines: Vec<TenantTimelineId> = Vec::new(); let mut tenants: Vec<TenantId> = Vec::new(); for ti in api_client.list_tenants().await? { if !ti.id.is_unsharded() { anyhow::bail!( "only unsharded tenants are supported at this time: {}", ti.id ); } tenants.push(ti.id.tenant_id) } let mut js = JoinSet::new(); for tenant_id in tenants { js.spawn({ let mgmt_api_client = Arc::clone(api_client); async move { ( tenant_id, mgmt_api_client .tenant_details(TenantShardId::unsharded(tenant_id)) .await .unwrap(), ) } }); } while let Some(res) = js.join_next().await { let (tenant_id, details) = res.unwrap(); for timeline_id in details.timelines { timelines.push(TenantTimelineId { tenant_id, timeline_id, }); } } Ok(timelines) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/main.rs
pageserver/pagebench/src/main.rs
use std::fs::File; use clap::Parser; use tracing::info; use utils::logging; /// Re-usable pieces of code that aren't CLI-specific. mod util { pub(crate) mod request_stats; #[macro_use] pub(crate) mod tokio_thread_local_stats; /// Re-usable pieces of CLI-specific code. pub(crate) mod cli { pub(crate) mod targets; } } /// The pagebench CLI sub-commands, dispatched in [`main`] below. mod cmd { pub(super) mod aux_files; pub(super) mod basebackup; pub(super) mod getpage_latest_lsn; pub(super) mod idle_streams; pub(super) mod ondemand_download_churn; pub(super) mod trigger_initial_size_calculation; } /// Component-level performance test for pageserver. #[derive(clap::Parser)] struct Args { /// Takes a client CPU profile into profile.svg. The benchmark must exit cleanly before it's /// written, e.g. via --runtime. #[arg(long)] profile: bool, #[command(subcommand)] subcommand: Subcommand, } #[derive(clap::Subcommand)] enum Subcommand { Basebackup(cmd::basebackup::Args), GetPageLatestLsn(cmd::getpage_latest_lsn::Args), TriggerInitialSizeCalculation(cmd::trigger_initial_size_calculation::Args), OndemandDownloadChurn(cmd::ondemand_download_churn::Args), AuxFiles(cmd::aux_files::Args), IdleStreams(cmd::idle_streams::Args), } fn main() -> anyhow::Result<()> { logging::init( logging::LogFormat::Plain, logging::TracingErrorLayerEnablement::Disabled, logging::Output::Stderr, )?; logging::replace_panic_hook_with_tracing_panic_hook().forget(); let args = Args::parse(); // Start a CPU profile if requested. let mut profiler = None; if args.profile { profiler = Some( pprof::ProfilerGuardBuilder::default() .frequency(1000) .blocklist(&["libc", "libgcc", "pthread", "vdso"]) .build()?, ); } match args.subcommand { Subcommand::Basebackup(args) => cmd::basebackup::main(args), Subcommand::GetPageLatestLsn(args) => cmd::getpage_latest_lsn::main(args), Subcommand::TriggerInitialSizeCalculation(args) => { cmd::trigger_initial_size_calculation::main(args) } Subcommand::OndemandDownloadChurn(args) => cmd::ondemand_download_churn::main(args), Subcommand::AuxFiles(args) => cmd::aux_files::main(args), Subcommand::IdleStreams(args) => cmd::idle_streams::main(args), }?; // Generate a CPU flamegraph if requested. if let Some(profiler) = profiler { let report = profiler.report().build()?; drop(profiler); // stop profiling let file = File::create("profile.svg")?; report.flamegraph(file)?; info!("wrote CPU profile flamegraph to profile.svg") } Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/util/tokio_thread_local_stats.rs
pageserver/pagebench/src/util/tokio_thread_local_stats.rs
pub(crate) type ThreadLocalStats<T> = Arc<Mutex<T>>; pub(crate) type AllThreadLocalStats<T> = Arc<Mutex<Vec<ThreadLocalStats<T>>>>; macro_rules! declare { ($THREAD_LOCAL_NAME:ident: $T:ty) => { thread_local! { pub static $THREAD_LOCAL_NAME: std::cell::RefCell<crate::util::tokio_thread_local_stats::ThreadLocalStats<$T>> = std::cell::RefCell::new( std::sync::Arc::new(std::sync::Mutex::new(Default::default())) ); } }; } use std::sync::{Arc, Mutex}; pub(crate) use declare; macro_rules! main { ($THREAD_LOCAL_NAME:ident, $main_impl:expr) => {{ let main_impl = $main_impl; let all = Arc::new(Mutex::new(Vec::new())); let rt = tokio::runtime::Builder::new_multi_thread() .on_thread_start({ let all = Arc::clone(&all); move || { // pre-initialize the thread local stats by accessesing them // (some stats like requests_stats::Stats are quite costly to initialize, // we don't want to pay that cost during the measurement period) $THREAD_LOCAL_NAME.with(|stats| { let stats: Arc<_> = Arc::clone(&*stats.borrow()); all.lock().unwrap().push(stats); }); } }) .enable_all() .build() .unwrap(); let main_task = rt.spawn(main_impl(all)); rt.block_on(main_task).unwrap() }}; } pub(crate) use main;
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/util/request_stats.rs
pageserver/pagebench/src/util/request_stats.rs
use std::time::Duration; use anyhow::Context; pub(crate) struct Stats { latency_histo: hdrhistogram::Histogram<u64>, } impl Stats { pub(crate) fn new() -> Self { Self { // Initialize with fixed bounds so that we panic at runtime instead of resizing the histogram, // which would skew the benchmark results. latency_histo: hdrhistogram::Histogram::new_with_bounds(1, 1_000_000_000, 3).unwrap(), } } pub(crate) fn observe(&mut self, latency: Duration) -> anyhow::Result<()> { let micros: u64 = latency .as_micros() .try_into() .context("latency greater than u64")?; self.latency_histo .record(micros) .context("add to histogram")?; Ok(()) } pub(crate) fn output(&self) -> Output { let latency_percentiles = std::array::from_fn(|idx| { let micros = self .latency_histo .value_at_percentile(LATENCY_PERCENTILES[idx]); Duration::from_micros(micros) }); Output { request_count: self.latency_histo.len(), latency_mean: Duration::from_micros(self.latency_histo.mean() as u64), latency_percentiles: LatencyPercentiles { latency_percentiles, }, } } pub(crate) fn add(&mut self, other: &Self) { let Self { latency_histo } = self; latency_histo.add(&other.latency_histo).unwrap(); } } impl Default for Stats { fn default() -> Self { Self::new() } } const LATENCY_PERCENTILES: [f64; 4] = [95.0, 99.00, 99.90, 99.99]; struct LatencyPercentiles { latency_percentiles: [Duration; 4], } impl serde::Serialize for LatencyPercentiles { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { use serde::ser::SerializeMap; let mut ser = serializer.serialize_map(Some(LATENCY_PERCENTILES.len()))?; for (p, v) in LATENCY_PERCENTILES.iter().zip(&self.latency_percentiles) { ser.serialize_entry( &format!("p{p}"), &format!("{}", humantime::format_duration(*v)), )?; } ser.end() } } #[derive(serde::Serialize)] pub(crate) struct Output { request_count: u64, #[serde(with = "humantime_serde")] latency_mean: Duration, latency_percentiles: LatencyPercentiles, }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/util/cli/targets.rs
pageserver/pagebench/src/util/cli/targets.rs
use std::sync::Arc; use pageserver_client::mgmt_api; use tracing::info; use utils::id::TenantTimelineId; pub(crate) struct Spec { pub(crate) limit_to_first_n_targets: Option<usize>, pub(crate) targets: Option<Vec<TenantTimelineId>>, } pub(crate) async fn discover( api_client: &Arc<mgmt_api::Client>, spec: Spec, ) -> anyhow::Result<Vec<TenantTimelineId>> { let mut timelines = if let Some(targets) = spec.targets { targets } else { mgmt_api::util::get_pageserver_tenant_timelines_unsharded(api_client).await? }; if let Some(limit) = spec.limit_to_first_n_targets { timelines.sort(); // for determinism timelines.truncate(limit); if timelines.len() < limit { anyhow::bail!("pageserver has less than limit_to_first_n_targets={limit} tenants"); } } info!("timelines:\n{:?}", timelines); info!("number of timelines:\n{:?}", timelines.len()); Ok(timelines) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/cmd/basebackup.rs
pageserver/pagebench/src/cmd/basebackup.rs
use std::collections::HashMap; use std::num::NonZeroUsize; use std::ops::Range; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; use anyhow::anyhow; use futures::TryStreamExt as _; use pageserver_api::shard::TenantShardId; use pageserver_client::mgmt_api::ForceAwaitLogicalSize; use pageserver_client::page_service::BasebackupRequest; use pageserver_page_api as page_api; use rand::prelude::*; use tokio::io::AsyncRead; use tokio::sync::Barrier; use tokio::task::JoinSet; use tokio_util::compat::{TokioAsyncReadCompatExt as _, TokioAsyncWriteCompatExt as _}; use tokio_util::io::StreamReader; use tonic::async_trait; use tracing::{info, instrument}; use url::Url; use utils::id::TenantTimelineId; use utils::lsn::Lsn; use utils::shard::ShardIndex; use crate::util::tokio_thread_local_stats::AllThreadLocalStats; use crate::util::{request_stats, tokio_thread_local_stats}; /// basebackup@LatestLSN #[derive(clap::Parser)] pub(crate) struct Args { #[clap(long, default_value = "http://localhost:9898")] mgmt_api_endpoint: String, /// The Pageserver to connect to. Use postgresql:// for libpq, or grpc:// for gRPC. #[clap(long, default_value = "postgresql://postgres@localhost:64000")] page_service_connstring: String, #[clap(long)] pageserver_jwt: Option<String>, #[clap(long, default_value = "1")] num_clients: NonZeroUsize, #[clap(long)] no_compression: bool, #[clap(long)] runtime: Option<humantime::Duration>, #[clap(long)] limit_to_first_n_targets: Option<usize>, targets: Option<Vec<TenantTimelineId>>, } #[derive(Debug, Default)] struct LiveStats { completed_requests: AtomicU64, } impl LiveStats { fn inc(&self) { self.completed_requests.fetch_add(1, Ordering::Relaxed); } } struct Target { timeline: TenantTimelineId, lsn_range: Option<Range<Lsn>>, } #[derive(serde::Serialize)] struct Output { total: request_stats::Output, } tokio_thread_local_stats::declare!(STATS: request_stats::Stats); pub(crate) fn main(args: Args) -> anyhow::Result<()> { tokio_thread_local_stats::main!(STATS, move |thread_local_stats| { main_impl(args, thread_local_stats) }) } async fn main_impl( args: Args, all_thread_local_stats: AllThreadLocalStats<request_stats::Stats>, ) -> anyhow::Result<()> { let args: &'static Args = Box::leak(Box::new(args)); let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new( reqwest::Client::new(), // TODO: support ssl_ca_file for https APIs in pagebench. args.mgmt_api_endpoint.clone(), args.pageserver_jwt.as_deref(), )); // discover targets let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover( &mgmt_api_client, crate::util::cli::targets::Spec { limit_to_first_n_targets: args.limit_to_first_n_targets, targets: args.targets.clone(), }, ) .await?; let mut js = JoinSet::new(); for timeline in &timelines { js.spawn({ let timeline = *timeline; let info = mgmt_api_client .timeline_info( TenantShardId::unsharded(timeline.tenant_id), timeline.timeline_id, ForceAwaitLogicalSize::No, ) .await .unwrap(); async move { anyhow::Ok(Target { timeline, // TODO: support lsn_range != latest LSN lsn_range: Some(info.last_record_lsn..(info.last_record_lsn + 1)), }) } }); } let mut all_targets: Vec<Target> = Vec::new(); while let Some(res) = js.join_next().await { all_targets.push(res.unwrap().unwrap()); } let live_stats = Arc::new(LiveStats::default()); let num_client_tasks = timelines.len(); let num_live_stats_dump = 1; let num_work_sender_tasks = 1; let start_work_barrier = Arc::new(tokio::sync::Barrier::new( num_client_tasks + num_live_stats_dump + num_work_sender_tasks, )); let all_work_done_barrier = Arc::new(tokio::sync::Barrier::new(num_client_tasks)); tokio::spawn({ let stats = Arc::clone(&live_stats); let start_work_barrier = Arc::clone(&start_work_barrier); async move { start_work_barrier.wait().await; loop { let start = std::time::Instant::now(); tokio::time::sleep(std::time::Duration::from_secs(1)).await; let completed_requests = stats.completed_requests.swap(0, Ordering::Relaxed); let elapsed = start.elapsed(); info!( "RPS: {:.0}", completed_requests as f64 / elapsed.as_secs_f64() ); } } }); let mut work_senders = HashMap::new(); let mut tasks = Vec::new(); let scheme = match Url::parse(&args.page_service_connstring) { Ok(url) => url.scheme().to_lowercase().to_string(), Err(url::ParseError::RelativeUrlWithoutBase) => "postgresql".to_string(), Err(err) => return Err(anyhow!("invalid connstring: {err}")), }; for &tl in &timelines { let (sender, receiver) = tokio::sync::mpsc::channel(1); // TODO: not sure what the implications of this are work_senders.insert(tl, sender); let client: Box<dyn Client> = match scheme.as_str() { "postgresql" | "postgres" => Box::new( LibpqClient::new(&args.page_service_connstring, tl, !args.no_compression).await?, ), "grpc" => Box::new( GrpcClient::new(&args.page_service_connstring, tl, !args.no_compression).await?, ), scheme => return Err(anyhow!("invalid scheme {scheme}")), }; tasks.push(tokio::spawn(run_worker( client, Arc::clone(&start_work_barrier), receiver, Arc::clone(&all_work_done_barrier), Arc::clone(&live_stats), ))); } let work_sender = async move { start_work_barrier.wait().await; loop { let (timeline, work) = { let mut rng = rand::rng(); let target = all_targets.choose(&mut rng).unwrap(); let lsn = target.lsn_range.clone().map(|r| rng.random_range(r)); (target.timeline, Work { lsn }) }; let sender = work_senders.get(&timeline).unwrap(); // TODO: what if this blocks? sender.send(work).await.ok().unwrap(); } }; if let Some(runtime) = args.runtime { match tokio::time::timeout(runtime.into(), work_sender).await { Ok(()) => unreachable!("work sender never terminates"), Err(_timeout) => { // this implicitly drops the work_senders, making all the clients exit } } } else { work_sender.await; unreachable!("work sender never terminates"); } for t in tasks { t.await.unwrap(); } let output = Output { total: { let mut agg_stats = request_stats::Stats::new(); for stats in all_thread_local_stats.lock().unwrap().iter() { let stats = stats.lock().unwrap(); agg_stats.add(&stats); } agg_stats.output() }, }; let output = serde_json::to_string_pretty(&output).unwrap(); println!("{output}"); anyhow::Ok(()) } #[derive(Copy, Clone)] struct Work { lsn: Option<Lsn>, } #[instrument(skip_all)] async fn run_worker( mut client: Box<dyn Client>, start_work_barrier: Arc<Barrier>, mut work: tokio::sync::mpsc::Receiver<Work>, all_work_done_barrier: Arc<Barrier>, live_stats: Arc<LiveStats>, ) { start_work_barrier.wait().await; while let Some(Work { lsn }) = work.recv().await { let start = Instant::now(); let stream = client.basebackup(lsn).await.unwrap(); let size = futures::io::copy(stream.compat(), &mut tokio::io::sink().compat_write()) .await .unwrap(); info!("basebackup size is {size} bytes"); let elapsed = start.elapsed(); live_stats.inc(); STATS.with(|stats| { stats.borrow().lock().unwrap().observe(elapsed).unwrap(); }); } all_work_done_barrier.wait().await; } /// A basebackup client. This allows switching out the client protocol implementation. #[async_trait] trait Client: Send { async fn basebackup( &mut self, lsn: Option<Lsn>, ) -> anyhow::Result<Pin<Box<dyn AsyncRead + Send>>>; } /// A libpq-based Pageserver client. struct LibpqClient { inner: pageserver_client::page_service::Client, ttid: TenantTimelineId, compression: bool, } impl LibpqClient { async fn new( connstring: &str, ttid: TenantTimelineId, compression: bool, ) -> anyhow::Result<Self> { Ok(Self { inner: pageserver_client::page_service::Client::new(connstring.to_string()).await?, ttid, compression, }) } } #[async_trait] impl Client for LibpqClient { async fn basebackup( &mut self, lsn: Option<Lsn>, ) -> anyhow::Result<Pin<Box<dyn AsyncRead + Send + 'static>>> { let req = BasebackupRequest { tenant_id: self.ttid.tenant_id, timeline_id: self.ttid.timeline_id, lsn, gzip: self.compression, }; let stream = self.inner.basebackup(&req).await?; Ok(Box::pin(StreamReader::new( stream.map_err(std::io::Error::other), ))) } } /// A gRPC Pageserver client. struct GrpcClient { inner: page_api::Client, compression: page_api::BaseBackupCompression, } impl GrpcClient { async fn new( connstring: &str, ttid: TenantTimelineId, compression: bool, ) -> anyhow::Result<Self> { let inner = page_api::Client::connect( connstring.to_string(), ttid.tenant_id, ttid.timeline_id, ShardIndex::unsharded(), None, None, // NB: uses payload compression ) .await?; let compression = match compression { true => page_api::BaseBackupCompression::Gzip, false => page_api::BaseBackupCompression::None, }; Ok(Self { inner, compression }) } } #[async_trait] impl Client for GrpcClient { async fn basebackup( &mut self, lsn: Option<Lsn>, ) -> anyhow::Result<Pin<Box<dyn AsyncRead + Send + 'static>>> { let req = page_api::GetBaseBackupRequest { lsn, replica: false, full: false, compression: self.compression, }; Ok(Box::pin(self.inner.get_base_backup(req).await?)) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/cmd/ondemand_download_churn.rs
pageserver/pagebench/src/cmd/ondemand_download_churn.rs
use std::f64; use std::num::NonZeroUsize; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; use pageserver_api::models::HistoricLayerInfo; use pageserver_api::shard::TenantShardId; use pageserver_client::mgmt_api; use rand::seq::IndexedMutRandom; use tokio::sync::{OwnedSemaphorePermit, mpsc}; use tokio::task::JoinSet; use tokio_util::sync::CancellationToken; use tracing::{debug, info}; use utils::id::{TenantTimelineId, TimelineId}; /// Evict & on-demand download random layers. #[derive(clap::Parser)] pub(crate) struct Args { #[clap(long, default_value = "http://localhost:9898")] mgmt_api_endpoint: String, #[clap(long)] pageserver_jwt: Option<String>, #[clap(long)] runtime: Option<humantime::Duration>, #[clap(long, default_value = "1")] tasks_per_target: NonZeroUsize, #[clap(long, default_value = "1")] concurrency_per_target: NonZeroUsize, /// Probability for sending `latest=true` in the request (uniform distribution). #[clap(long)] limit_to_first_n_targets: Option<usize>, /// Before starting the benchmark, live-reconfigure the pageserver to use the given /// [`pageserver_api::models::virtual_file::IoEngineKind`]. #[clap(long)] set_io_engine: Option<pageserver_api::models::virtual_file::IoEngineKind>, targets: Option<Vec<TenantTimelineId>>, } pub(crate) fn main(args: Args) -> anyhow::Result<()> { let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; let task = rt.spawn(main_impl(args)); rt.block_on(task).unwrap().unwrap(); Ok(()) } #[derive(serde::Serialize)] struct Output { downloads_count: u64, downloads_bytes: u64, evictions_count: u64, timeline_restarts: u64, #[serde(with = "humantime_serde")] runtime: Duration, } #[derive(Debug, Default)] struct LiveStats { evictions_count: AtomicU64, downloads_count: AtomicU64, downloads_bytes: AtomicU64, timeline_restarts: AtomicU64, } impl LiveStats { fn eviction_done(&self) { self.evictions_count.fetch_add(1, Ordering::Relaxed); } fn download_done(&self, size: u64) { self.downloads_count.fetch_add(1, Ordering::Relaxed); self.downloads_bytes.fetch_add(size, Ordering::Relaxed); } fn timeline_restart_done(&self) { self.timeline_restarts.fetch_add(1, Ordering::Relaxed); } } async fn main_impl(args: Args) -> anyhow::Result<()> { let args: &'static Args = Box::leak(Box::new(args)); let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new( reqwest::Client::new(), // TODO: support ssl_ca_file for https APIs in pagebench. args.mgmt_api_endpoint.clone(), args.pageserver_jwt.as_deref(), )); if let Some(engine_str) = &args.set_io_engine { mgmt_api_client.put_io_engine(engine_str).await?; } // discover targets let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover( &mgmt_api_client, crate::util::cli::targets::Spec { limit_to_first_n_targets: args.limit_to_first_n_targets, targets: args.targets.clone(), }, ) .await?; let token = CancellationToken::new(); let mut tasks = JoinSet::new(); let periodic_stats = Arc::new(LiveStats::default()); let total_stats = Arc::new(LiveStats::default()); let start = Instant::now(); tasks.spawn({ let periodic_stats = Arc::clone(&periodic_stats); let total_stats = Arc::clone(&total_stats); let cloned_token = token.clone(); async move { let mut last_at = Instant::now(); loop { if cloned_token.is_cancelled() { return; } tokio::time::sleep_until((last_at + Duration::from_secs(1)).into()).await; let now = Instant::now(); let delta: Duration = now - last_at; last_at = now; let LiveStats { evictions_count, downloads_count, downloads_bytes, timeline_restarts, } = &*periodic_stats; let evictions_count = evictions_count.swap(0, Ordering::Relaxed); let downloads_count = downloads_count.swap(0, Ordering::Relaxed); let downloads_bytes = downloads_bytes.swap(0, Ordering::Relaxed); let timeline_restarts = timeline_restarts.swap(0, Ordering::Relaxed); total_stats.evictions_count.fetch_add(evictions_count, Ordering::Relaxed); total_stats.downloads_count.fetch_add(downloads_count, Ordering::Relaxed); total_stats.downloads_bytes.fetch_add(downloads_bytes, Ordering::Relaxed); total_stats.timeline_restarts.fetch_add(timeline_restarts, Ordering::Relaxed); let evictions_per_s = evictions_count as f64 / delta.as_secs_f64(); let downloads_per_s = downloads_count as f64 / delta.as_secs_f64(); let downloads_mibs_per_s = downloads_bytes as f64 / delta.as_secs_f64() / ((1 << 20) as f64); info!("evictions={evictions_per_s:.2}/s downloads={downloads_per_s:.2}/s download_bytes={downloads_mibs_per_s:.2}MiB/s timeline_restarts={timeline_restarts}"); } } }); for tl in timelines { for _ in 0..args.tasks_per_target.get() { tasks.spawn(timeline_actor( args, Arc::clone(&mgmt_api_client), tl, Arc::clone(&periodic_stats), token.clone(), )); } } if let Some(runtime) = args.runtime { tokio::spawn(async move { tokio::time::sleep(runtime.into()).await; token.cancel(); }); } while let Some(res) = tasks.join_next().await { res.unwrap(); } let end = Instant::now(); let duration: Duration = end - start; let output = { let LiveStats { evictions_count, downloads_count, downloads_bytes, timeline_restarts, } = &*total_stats; Output { downloads_count: downloads_count.load(Ordering::Relaxed), downloads_bytes: downloads_bytes.load(Ordering::Relaxed), evictions_count: evictions_count.load(Ordering::Relaxed), timeline_restarts: timeline_restarts.load(Ordering::Relaxed), runtime: duration, } }; let output = serde_json::to_string_pretty(&output).unwrap(); println!("{output}"); Ok(()) } async fn timeline_actor( args: &'static Args, mgmt_api_client: Arc<pageserver_client::mgmt_api::Client>, timeline: TenantTimelineId, live_stats: Arc<LiveStats>, token: CancellationToken, ) { // TODO: support sharding let tenant_shard_id = TenantShardId::unsharded(timeline.tenant_id); struct Timeline { joinset: JoinSet<()>, layers: Vec<mpsc::Sender<OwnedSemaphorePermit>>, concurrency: Arc<tokio::sync::Semaphore>, } while !token.is_cancelled() { debug!("restarting timeline"); let layer_map_info = mgmt_api_client .layer_map_info(tenant_shard_id, timeline.timeline_id) .await .unwrap(); let concurrency = Arc::new(tokio::sync::Semaphore::new( args.concurrency_per_target.get(), )); let mut joinset = JoinSet::new(); let layers = layer_map_info .historic_layers .into_iter() .map(|historic_layer| { let (tx, rx) = mpsc::channel(1); joinset.spawn(layer_actor( tenant_shard_id, timeline.timeline_id, historic_layer, rx, Arc::clone(&mgmt_api_client), Arc::clone(&live_stats), )); tx }) .collect::<Vec<_>>(); let mut timeline = Timeline { joinset, layers, concurrency, }; live_stats.timeline_restart_done(); while !token.is_cancelled() { assert!(!timeline.joinset.is_empty()); if let Some(res) = timeline.joinset.try_join_next() { debug!(?res, "a layer actor exited, should not happen"); timeline.joinset.shutdown().await; break; } let mut permit = Some( Arc::clone(&timeline.concurrency) .acquire_owned() .await .unwrap(), ); loop { let layer_tx = { let mut rng = rand::rng(); timeline.layers.choose_mut(&mut rng).expect("no layers") }; match layer_tx.try_send(permit.take().unwrap()) { Ok(_) => break, Err(e) => match e { mpsc::error::TrySendError::Full(back) => { // TODO: retrying introduces bias away from slow downloaders permit.replace(back); } mpsc::error::TrySendError::Closed(_) => panic!(), }, } } } } } async fn layer_actor( tenant_shard_id: TenantShardId, timeline_id: TimelineId, mut layer: HistoricLayerInfo, mut rx: mpsc::Receiver<tokio::sync::OwnedSemaphorePermit>, mgmt_api_client: Arc<mgmt_api::Client>, live_stats: Arc<LiveStats>, ) { #[derive(Clone, Copy)] enum Action { Evict, OnDemandDownload, } while let Some(_permit) = rx.recv().await { let action = if layer.is_remote() { Action::OnDemandDownload } else { Action::Evict }; let did_it = match action { Action::Evict => { let did_it = mgmt_api_client .layer_evict(tenant_shard_id, timeline_id, layer.layer_file_name()) .await .unwrap(); live_stats.eviction_done(); did_it } Action::OnDemandDownload => { let did_it = mgmt_api_client .layer_ondemand_download(tenant_shard_id, timeline_id, layer.layer_file_name()) .await .unwrap(); live_stats.download_done(layer.layer_file_size()); did_it } }; if !did_it { debug!("local copy of layer map appears out of sync, re-downloading"); return; } debug!("did it"); layer.set_remote(match action { Action::Evict => true, Action::OnDemandDownload => false, }); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/cmd/idle_streams.rs
pageserver/pagebench/src/cmd/idle_streams.rs
use std::sync::Arc; use anyhow::anyhow; use futures::StreamExt; use tonic::transport::Endpoint; use tracing::info; use pageserver_page_api::{GetPageClass, GetPageRequest, GetPageStatusCode, ReadLsn, RelTag}; use utils::id::TenantTimelineId; use utils::lsn::Lsn; use utils::shard::ShardIndex; /// Starts a large number of idle gRPC GetPage streams. #[derive(clap::Parser)] pub(crate) struct Args { /// The Pageserver to connect to. Must use grpc://. #[clap(long, default_value = "grpc://localhost:51051")] server: String, /// The Pageserver HTTP API. #[clap(long, default_value = "http://localhost:9898")] http_server: String, /// The number of streams to open. #[clap(long, default_value = "100000")] count: usize, /// Number of streams per connection. #[clap(long, default_value = "100")] per_connection: usize, /// Send a single GetPage request on each stream. #[clap(long, default_value_t = false)] send_request: bool, } pub(crate) fn main(args: Args) -> anyhow::Result<()> { let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; rt.block_on(main_impl(args)) } async fn main_impl(args: Args) -> anyhow::Result<()> { // Discover a tenant and timeline to use. let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new( reqwest::Client::new(), args.http_server.clone(), None, )); let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover( &mgmt_api_client, crate::util::cli::targets::Spec { limit_to_first_n_targets: Some(1), targets: None, }, ) .await?; let ttid = timelines .first() .ok_or_else(|| anyhow!("no timelines found"))?; // Set up the initial client. let endpoint = Endpoint::from_shared(args.server.clone())?; let connect = async || { pageserver_page_api::Client::new( endpoint.connect().await?, ttid.tenant_id, ttid.timeline_id, ShardIndex::unsharded(), None, None, ) }; let mut client = connect().await?; let mut streams = Vec::with_capacity(args.count); // Create streams. for i in 0..args.count { if i % 100 == 0 { info!("opened {}/{} streams", i, args.count); } if i % args.per_connection == 0 && i > 0 { client = connect().await?; } let (req_tx, req_rx) = tokio::sync::mpsc::unbounded_channel(); let req_stream = tokio_stream::wrappers::UnboundedReceiverStream::new(req_rx); let mut resp_stream = client.get_pages(req_stream).await?; // Send request if specified. if args.send_request { req_tx.send(GetPageRequest { request_id: 1.into(), request_class: GetPageClass::Normal, read_lsn: ReadLsn { request_lsn: Lsn::MAX, not_modified_since_lsn: Some(Lsn(1)), }, rel: RelTag { spcnode: 1664, // pg_global dbnode: 0, // shared database relnode: 1262, // pg_authid forknum: 0, // init }, block_numbers: vec![0], })?; let resp = resp_stream .next() .await .transpose()? .ok_or_else(|| anyhow!("no response"))?; if resp.status_code != GetPageStatusCode::Ok { return Err(anyhow!("{} response", resp.status_code)); } } // Hold onto streams to avoid closing them. streams.push((req_tx, resp_stream)); } info!("opened {} streams, sleeping", args.count); // Block forever, to hold the idle streams open for inspection. futures::future::pending::<()>().await; Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/cmd/aux_files.rs
pageserver/pagebench/src/cmd/aux_files.rs
use std::collections::HashMap; use std::sync::Arc; use std::time::Instant; use pageserver_api::models::{TenantConfig, TenantConfigRequest}; use pageserver_api::shard::TenantShardId; use utils::id::TenantTimelineId; use utils::lsn::Lsn; /// Ingest aux files into the pageserver. #[derive(clap::Parser)] pub(crate) struct Args { #[clap(long, default_value = "http://localhost:9898")] mgmt_api_endpoint: String, #[clap(long, default_value = "postgres://postgres@localhost:64000")] page_service_connstring: String, #[clap(long)] pageserver_jwt: Option<String>, targets: Option<Vec<TenantTimelineId>>, } pub(crate) fn main(args: Args) -> anyhow::Result<()> { let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(); let main_task = rt.spawn(main_impl(args)); rt.block_on(main_task).unwrap() } async fn main_impl(args: Args) -> anyhow::Result<()> { let args: &'static Args = Box::leak(Box::new(args)); let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new( reqwest::Client::new(), // TODO: support ssl_ca_file for https APIs in pagebench. args.mgmt_api_endpoint.clone(), args.pageserver_jwt.as_deref(), )); // discover targets let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover( &mgmt_api_client, crate::util::cli::targets::Spec { limit_to_first_n_targets: None, targets: { if let Some(targets) = &args.targets { if targets.len() != 1 { anyhow::bail!("must specify exactly one target"); } Some(targets.clone()) } else { None } }, }, ) .await?; let timeline = timelines[0]; let tenant_shard_id = TenantShardId::unsharded(timeline.tenant_id); let timeline_id = timeline.timeline_id; println!("operating on timeline {timeline}"); mgmt_api_client .set_tenant_config(&TenantConfigRequest { tenant_id: timeline.tenant_id, config: TenantConfig::default(), }) .await?; for batch in 0..100 { let items = (0..100) .map(|id| { ( format!("pg_logical/mappings/{batch:03}.{id:03}"), format!("{id:08}"), ) }) .collect::<HashMap<_, _>>(); let file_cnt = items.len(); mgmt_api_client .ingest_aux_files(tenant_shard_id, timeline_id, items) .await?; println!("ingested {file_cnt} files"); } for _ in 0..100 { let start = Instant::now(); let files = mgmt_api_client .list_aux_files(tenant_shard_id, timeline_id, Lsn(Lsn::MAX.0 - 1)) .await?; println!( "{} files found in {}s", files.len(), start.elapsed().as_secs_f64() ); } anyhow::Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/cmd/trigger_initial_size_calculation.rs
pageserver/pagebench/src/cmd/trigger_initial_size_calculation.rs
use std::sync::Arc; use humantime::Duration; use pageserver_api::shard::TenantShardId; use pageserver_client::mgmt_api::ForceAwaitLogicalSize; use tokio::task::JoinSet; use utils::id::TenantTimelineId; #[derive(clap::Parser)] pub(crate) struct Args { #[clap(long, default_value = "http://localhost:9898")] mgmt_api_endpoint: String, #[clap(long, default_value = "localhost:64000")] page_service_host_port: String, #[clap(long)] pageserver_jwt: Option<String>, #[clap( long, help = "if specified, poll mgmt api to check whether init logical size calculation has completed" )] poll_for_completion: Option<Duration>, #[clap(long)] limit_to_first_n_targets: Option<usize>, targets: Option<Vec<TenantTimelineId>>, } pub(crate) fn main(args: Args) -> anyhow::Result<()> { let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(); let main_task = rt.spawn(main_impl(args)); rt.block_on(main_task).unwrap() } async fn main_impl(args: Args) -> anyhow::Result<()> { let args: &'static Args = Box::leak(Box::new(args)); let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new( reqwest::Client::new(), // TODO: support ssl_ca_file for https APIs in pagebench. args.mgmt_api_endpoint.clone(), args.pageserver_jwt.as_deref(), )); // discover targets let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover( &mgmt_api_client, crate::util::cli::targets::Spec { limit_to_first_n_targets: args.limit_to_first_n_targets, targets: args.targets.clone(), }, ) .await?; // kick it off let mut js = JoinSet::new(); for tl in timelines { let mgmt_api_client = Arc::clone(&mgmt_api_client); js.spawn(async move { let info = mgmt_api_client .timeline_info( TenantShardId::unsharded(tl.tenant_id), tl.timeline_id, ForceAwaitLogicalSize::Yes, ) .await .unwrap(); // Polling should not be strictly required here since we await // for the initial logical size, however it's possible for the request // to land before the timeline is initialised. This results in an approximate // logical size. if let Some(period) = args.poll_for_completion { let mut ticker = tokio::time::interval(period.into()); ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); let mut info = info; while !info.current_logical_size_is_accurate { ticker.tick().await; info = mgmt_api_client .timeline_info( TenantShardId::unsharded(tl.tenant_id), tl.timeline_id, ForceAwaitLogicalSize::Yes, ) .await .unwrap(); } } }); } while let Some(res) = js.join_next().await { let _: () = res.unwrap(); } Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/pageserver/pagebench/src/cmd/getpage_latest_lsn.rs
pageserver/pagebench/src/cmd/getpage_latest_lsn.rs
use std::collections::{HashMap, HashSet, VecDeque}; use std::future::Future; use std::num::NonZeroUsize; use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::Context; use async_trait::async_trait; use bytes::Bytes; use camino::Utf8PathBuf; use futures::stream::FuturesUnordered; use futures::{Stream, StreamExt as _}; use pageserver_api::key::Key; use pageserver_api::keyspace::KeySpaceAccum; use pageserver_api::pagestream_api::{PagestreamGetPageRequest, PagestreamRequest}; use pageserver_api::reltag::RelTag; use pageserver_api::shard::TenantShardId; use pageserver_client_grpc::{self as client_grpc, ShardSpec}; use pageserver_page_api as page_api; use rand::prelude::*; use tokio::task::JoinSet; use tokio_util::sync::CancellationToken; use tracing::info; use url::Url; use utils::id::TenantTimelineId; use utils::lsn::Lsn; use utils::shard::ShardIndex; use crate::util::tokio_thread_local_stats::AllThreadLocalStats; use crate::util::{request_stats, tokio_thread_local_stats}; /// GetPage@LatestLSN, uniformly distributed across the compute-accessible keyspace. #[derive(clap::Parser)] pub(crate) struct Args { #[clap(long, default_value = "http://localhost:9898")] mgmt_api_endpoint: String, /// Pageserver connection string. Supports postgresql:// and grpc:// protocols. #[clap(long, default_value = "postgres://postgres@localhost:64000")] page_service_connstring: String, /// Use the rich gRPC Pageserver client `client_grpc::PageserverClient`, rather than the basic /// no-frills `page_api::Client`. Only valid with grpc:// connstrings. #[clap(long)] rich_client: bool, #[clap(long)] pageserver_jwt: Option<String>, #[clap(long, default_value = "1")] num_clients: NonZeroUsize, #[clap(long)] runtime: Option<humantime::Duration>, /// If true, enable compression (only for gRPC). #[clap(long)] compression: bool, /// Each client sends requests at the given rate. /// /// If a request takes too long and we should be issuing a new request already, /// we skip that request and account it as `MISSED`. #[clap(long)] per_client_rate: Option<usize>, /// Probability for sending `latest=true` in the request (uniform distribution). #[clap(long, default_value = "1")] req_latest_probability: f64, #[clap(long)] limit_to_first_n_targets: Option<usize>, /// For large pageserver installations, enumerating the keyspace takes a lot of time. /// If specified, the specified path is used to maintain a cache of the keyspace enumeration result. /// The cache is tagged and auto-invalided by the tenant/timeline ids only. /// It doesn't get invalidated if the keyspace changes under the hood, e.g., due to new ingested data or compaction. #[clap(long)] keyspace_cache: Option<Utf8PathBuf>, /// Before starting the benchmark, live-reconfigure the pageserver to use the given /// [`pageserver_api::models::virtual_file::IoEngineKind`]. #[clap(long)] set_io_engine: Option<pageserver_api::models::virtual_file::IoEngineKind>, /// Before starting the benchmark, live-reconfigure the pageserver to use specified io mode (buffered vs. direct). #[clap(long)] set_io_mode: Option<pageserver_api::models::virtual_file::IoMode>, /// Queue depth generated in each client. #[clap(long, default_value = "1")] queue_depth: NonZeroUsize, /// Batch size of contiguous pages generated by each client. This is equivalent to how Postgres /// will request page batches (e.g. prefetches or vectored reads). A batch counts as 1 RPS and /// 1 queue depth. /// /// The libpq protocol does not support client-side batching, and will submit batches as many /// individual requests, in the hope that the server will batch them. Each batch still counts as /// 1 RPS and 1 queue depth. #[clap(long, default_value = "1")] batch_size: NonZeroUsize, #[clap(long)] only_relnode: Option<u32>, targets: Option<Vec<TenantTimelineId>>, } /// State shared by all clients #[derive(Debug)] struct SharedState { start_work_barrier: tokio::sync::Barrier, live_stats: LiveStats, } #[derive(Debug, Default)] struct LiveStats { completed_requests: AtomicU64, missed: AtomicU64, } impl LiveStats { fn request_done(&self) { self.completed_requests.fetch_add(1, Ordering::Relaxed); } fn missed(&self, n: u64) { self.missed.fetch_add(n, Ordering::Relaxed); } } #[derive(Clone, serde::Serialize, serde::Deserialize)] struct KeyRange { timeline: TenantTimelineId, timeline_lsn: Lsn, start: i128, end: i128, } impl KeyRange { fn len(&self) -> i128 { self.end - self.start } } #[derive(PartialEq, Eq, Hash, Copy, Clone)] struct WorkerId { timeline: TenantTimelineId, num_client: usize, // from 0..args.num_clients } #[derive(serde::Serialize)] struct Output { total: request_stats::Output, } tokio_thread_local_stats::declare!(STATS: request_stats::Stats); pub(crate) fn main(args: Args) -> anyhow::Result<()> { tokio_thread_local_stats::main!(STATS, move |thread_local_stats| { main_impl(args, thread_local_stats) }) } async fn main_impl( args: Args, all_thread_local_stats: AllThreadLocalStats<request_stats::Stats>, ) -> anyhow::Result<()> { let args: &'static Args = Box::leak(Box::new(args)); let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new( reqwest::Client::new(), // TODO: support ssl_ca_file for https APIs in pagebench. args.mgmt_api_endpoint.clone(), args.pageserver_jwt.as_deref(), )); if let Some(engine_str) = &args.set_io_engine { mgmt_api_client.put_io_engine(engine_str).await?; } if let Some(mode) = &args.set_io_mode { mgmt_api_client.put_io_mode(mode).await?; } // discover targets let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover( &mgmt_api_client, crate::util::cli::targets::Spec { limit_to_first_n_targets: args.limit_to_first_n_targets, targets: args.targets.clone(), }, ) .await?; #[derive(serde::Deserialize)] struct KeyspaceCacheDe { tag: Vec<TenantTimelineId>, data: Vec<KeyRange>, } #[derive(serde::Serialize)] struct KeyspaceCacheSer<'a> { tag: &'a [TenantTimelineId], data: &'a [KeyRange], } let cache = args .keyspace_cache .as_ref() .map(|keyspace_cache_file| { let contents = match std::fs::read(keyspace_cache_file) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => { return anyhow::Ok(None); } x => x.context("read keyspace cache file")?, }; let cache: KeyspaceCacheDe = serde_json::from_slice(&contents).context("deserialize cache file")?; let tag_ok = HashSet::<TenantTimelineId>::from_iter(cache.tag.into_iter()) == HashSet::from_iter(timelines.iter().cloned()); info!("keyspace cache file matches tag: {tag_ok}"); anyhow::Ok(if tag_ok { Some(cache.data) } else { None }) }) .transpose()? .flatten(); let all_ranges: Vec<KeyRange> = if let Some(cached) = cache { info!("using keyspace cache file"); cached } else { let mut js = JoinSet::new(); for timeline in &timelines { js.spawn({ let mgmt_api_client = Arc::clone(&mgmt_api_client); let timeline = *timeline; async move { let partitioning = mgmt_api_client .keyspace( TenantShardId::unsharded(timeline.tenant_id), timeline.timeline_id, ) .await?; let lsn = partitioning.at_lsn; let start = Instant::now(); let mut filtered = KeySpaceAccum::new(); // let's hope this is inlined and vectorized... // TODO: turn this loop into a is_rel_block_range() function. for r in partitioning.keys.ranges.iter() { let mut i = r.start; while i != r.end { let mut include = true; include &= i.is_rel_block_key(); if let Some(only_relnode) = args.only_relnode { include &= i.is_rel_block_of_rel(only_relnode); } if include { filtered.add_key(i); } i = i.next(); } } let filtered = filtered.to_keyspace(); let filter_duration = start.elapsed(); anyhow::Ok(( filter_duration, filtered.ranges.into_iter().map(move |r| KeyRange { timeline, timeline_lsn: lsn, start: r.start.to_i128(), end: r.end.to_i128(), }), )) } }); } let mut total_filter_duration = Duration::from_secs(0); let mut all_ranges: Vec<KeyRange> = Vec::new(); while let Some(res) = js.join_next().await { let (filter_duration, range) = res.unwrap().unwrap(); all_ranges.extend(range); total_filter_duration += filter_duration; } info!("filter duration: {}", total_filter_duration.as_secs_f64()); if let Some(cachefile) = args.keyspace_cache.as_ref() { let cache = KeyspaceCacheSer { tag: &timelines, data: &all_ranges, }; let bytes = serde_json::to_vec(&cache).context("serialize keyspace for cache file")?; std::fs::write(cachefile, bytes).context("write keyspace cache file to disk")?; info!("successfully wrote keyspace cache file"); } all_ranges }; let num_live_stats_dump = 1; let num_work_sender_tasks = args.num_clients.get() * timelines.len(); let num_main_impl = 1; let shared_state = Arc::new(SharedState { start_work_barrier: tokio::sync::Barrier::new( num_live_stats_dump + num_work_sender_tasks + num_main_impl, ), live_stats: LiveStats::default(), }); let cancel = CancellationToken::new(); let ss = shared_state.clone(); tokio::spawn({ async move { ss.start_work_barrier.wait().await; loop { let start = std::time::Instant::now(); tokio::time::sleep(std::time::Duration::from_secs(1)).await; let stats = &ss.live_stats; let completed_requests = stats.completed_requests.swap(0, Ordering::Relaxed); let missed = stats.missed.swap(0, Ordering::Relaxed); let elapsed = start.elapsed(); info!( "RPS: {:.0} MISSED: {:.0}", completed_requests as f64 / elapsed.as_secs_f64(), missed as f64 / elapsed.as_secs_f64() ); } } }); let rps_period = args .per_client_rate .map(|rps_limit| Duration::from_secs_f64(1.0 / (rps_limit as f64))); let make_worker: &dyn Fn(WorkerId) -> Pin<Box<dyn Send + Future<Output = ()>>> = &|worker_id| { let ss = shared_state.clone(); let cancel = cancel.clone(); let ranges: Vec<KeyRange> = all_ranges .iter() .filter(|r| r.timeline == worker_id.timeline) .cloned() .collect(); let weights = rand::distr::weighted::WeightedIndex::new(ranges.iter().map(|v| v.len())).unwrap(); Box::pin(async move { let scheme = match Url::parse(&args.page_service_connstring) { Ok(url) => url.scheme().to_lowercase().to_string(), Err(url::ParseError::RelativeUrlWithoutBase) => "postgresql".to_string(), Err(err) => panic!("invalid connstring: {err}"), }; let client: Box<dyn Client> = match scheme.as_str() { "postgresql" | "postgres" => { assert!(!args.compression, "libpq does not support compression"); assert!(!args.rich_client, "rich client requires grpc://"); Box::new( LibpqClient::new(&args.page_service_connstring, worker_id.timeline) .await .unwrap(), ) } "grpc" if args.rich_client => Box::new( RichGrpcClient::new( &args.page_service_connstring, worker_id.timeline, args.compression, ) .await .unwrap(), ), "grpc" => Box::new( GrpcClient::new( &args.page_service_connstring, worker_id.timeline, args.compression, ) .await .unwrap(), ), scheme => panic!("unsupported scheme {scheme}"), }; run_worker(args, client, ss, cancel, rps_period, ranges, weights).await }) }; info!("spawning workers"); let mut workers = JoinSet::new(); for timeline in timelines.iter().cloned() { for num_client in 0..args.num_clients.get() { let worker_id = WorkerId { timeline, num_client, }; workers.spawn(make_worker(worker_id)); } } let workers = async move { while let Some(res) = workers.join_next().await { res.unwrap(); } }; info!("waiting for everything to become ready"); shared_state.start_work_barrier.wait().await; info!("work started"); if let Some(runtime) = args.runtime { tokio::time::sleep(runtime.into()).await; info!("runtime over, signalling cancellation"); cancel.cancel(); workers.await; info!("work sender exited"); } else { workers.await; unreachable!("work sender never terminates"); } let output = Output { total: { let mut agg_stats = request_stats::Stats::new(); for stats in all_thread_local_stats.lock().unwrap().iter() { let stats = stats.lock().unwrap(); agg_stats.add(&stats); } agg_stats.output() }, }; let output = serde_json::to_string_pretty(&output).unwrap(); println!("{output}"); anyhow::Ok(()) } async fn run_worker( args: &Args, mut client: Box<dyn Client>, shared_state: Arc<SharedState>, cancel: CancellationToken, rps_period: Option<Duration>, ranges: Vec<KeyRange>, weights: rand::distr::weighted::WeightedIndex<i128>, ) { shared_state.start_work_barrier.wait().await; let client_start = Instant::now(); let mut ticks_processed = 0; let mut req_id = 0; let batch_size: usize = args.batch_size.into(); // Track inflight requests by request ID and start time. This times the request duration, and // ensures responses match requests. We don't expect responses back in any particular order. // // NB: this does not check that all requests received a response, because we don't wait for the // inflight requests to complete when the duration elapses. let mut inflight: HashMap<u64, Instant> = HashMap::new(); while !cancel.is_cancelled() { // Detect if a request took longer than the RPS rate if let Some(period) = &rps_period { let periods_passed_until_now = usize::try_from(client_start.elapsed().as_micros() / period.as_micros()).unwrap(); if periods_passed_until_now > ticks_processed { shared_state .live_stats .missed((periods_passed_until_now - ticks_processed) as u64); } ticks_processed = periods_passed_until_now; } while inflight.len() < args.queue_depth.get() { req_id += 1; let start = Instant::now(); let (req_lsn, mod_lsn, rel, blks) = { /// Converts a compact i128 key to a relation tag and block number. fn key_to_block(key: i128) -> (RelTag, u32) { let key = Key::from_i128(key); assert!(key.is_rel_block_key()); key.to_rel_block() .expect("we filter non-rel-block keys out above") } // Pick a random page from a random relation. let mut rng = rand::rng(); let r = &ranges[weights.sample(&mut rng)]; let key: i128 = rng.random_range(r.start..r.end); let (rel_tag, block_no) = key_to_block(key); let mut blks = VecDeque::with_capacity(batch_size); blks.push_back(block_no); // If requested, populate a batch of sequential pages. This is how Postgres will // request page batches (e.g. prefetches). If we hit the end of the relation, we // grow the batch towards the start too. for i in 1..batch_size { let (r, b) = key_to_block(key + i as i128); if r != rel_tag { break; // went outside relation } blks.push_back(b) } if blks.len() < batch_size { // Grow batch backwards if needed. for i in 1..batch_size { let (r, b) = key_to_block(key - i as i128); if r != rel_tag { break; // went outside relation } blks.push_front(b) } } // We assume that the entire batch can fit within the relation. assert_eq!(blks.len(), batch_size, "incomplete batch"); let req_lsn = if rng.random_bool(args.req_latest_probability) { Lsn::MAX } else { r.timeline_lsn }; (req_lsn, r.timeline_lsn, rel_tag, blks.into()) }; client .send_get_page(req_id, req_lsn, mod_lsn, rel, blks) .await .unwrap(); let old = inflight.insert(req_id, start); assert!(old.is_none(), "duplicate request ID {req_id}"); } let (req_id, pages) = client.recv_get_page().await.unwrap(); assert_eq!(pages.len(), batch_size, "unexpected page count"); assert!(pages.iter().all(|p| !p.is_empty()), "empty page"); let start = inflight .remove(&req_id) .expect("response for unknown request ID"); let end = Instant::now(); shared_state.live_stats.request_done(); ticks_processed += 1; STATS.with(|stats| { stats .borrow() .lock() .unwrap() .observe(end.duration_since(start)) .unwrap(); }); if let Some(period) = &rps_period { let next_at = client_start + Duration::from_micros( (ticks_processed) as u64 * u64::try_from(period.as_micros()).unwrap(), ); tokio::time::sleep_until(next_at.into()).await; } } } /// A benchmark client, to allow switching out the transport protocol. /// /// For simplicity, this just uses separate asynchronous send/recv methods. The send method could /// return a future that resolves when the response is received, but we don't really need it. #[async_trait] trait Client: Send { /// Sends an asynchronous GetPage request to the pageserver. async fn send_get_page( &mut self, req_id: u64, req_lsn: Lsn, mod_lsn: Lsn, rel: RelTag, blks: Vec<u32>, ) -> anyhow::Result<()>; /// Receives the next GetPage response from the pageserver. async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)>; } /// A libpq-based Pageserver client. struct LibpqClient { inner: pageserver_client::page_service::PagestreamClient, // Track sent batches, so we know how many responses to expect. batch_sizes: VecDeque<usize>, } impl LibpqClient { async fn new(connstring: &str, ttid: TenantTimelineId) -> anyhow::Result<Self> { let inner = pageserver_client::page_service::Client::new(connstring.to_string()) .await? .pagestream(ttid.tenant_id, ttid.timeline_id) .await?; Ok(Self { inner, batch_sizes: VecDeque::new(), }) } } #[async_trait] impl Client for LibpqClient { async fn send_get_page( &mut self, req_id: u64, req_lsn: Lsn, mod_lsn: Lsn, rel: RelTag, blks: Vec<u32>, ) -> anyhow::Result<()> { // libpq doesn't support client-side batches, so we send a bunch of individual requests // instead in the hope that the server will batch them for us. We use the same request ID // for all, because we'll return a single batch response. self.batch_sizes.push_back(blks.len()); for blkno in blks { let req = PagestreamGetPageRequest { hdr: PagestreamRequest { reqid: req_id, request_lsn: req_lsn, not_modified_since: mod_lsn, }, rel, blkno, }; self.inner.getpage_send(req).await?; } Ok(()) } async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)> { let batch_size = self.batch_sizes.pop_front().unwrap(); let mut batch = Vec::with_capacity(batch_size); let mut req_id = None; for _ in 0..batch_size { let resp = self.inner.getpage_recv().await?; if req_id.is_none() { req_id = Some(resp.req.hdr.reqid); } assert_eq!(req_id, Some(resp.req.hdr.reqid), "request ID mismatch"); batch.push(resp.page); } Ok((req_id.unwrap(), batch)) } } /// A gRPC Pageserver client. struct GrpcClient { req_tx: tokio::sync::mpsc::Sender<page_api::GetPageRequest>, resp_rx: Pin<Box<dyn Stream<Item = Result<page_api::GetPageResponse, tonic::Status>> + Send>>, } impl GrpcClient { async fn new( connstring: &str, ttid: TenantTimelineId, compression: bool, ) -> anyhow::Result<Self> { let mut client = page_api::Client::connect( connstring.to_string(), ttid.tenant_id, ttid.timeline_id, ShardIndex::unsharded(), None, compression.then_some(tonic::codec::CompressionEncoding::Zstd), ) .await?; // The channel has a buffer size of 1, since 0 is not allowed. It does not matter, since the // benchmark will control the queue depth (i.e. in-flight requests) anyway, and requests are // buffered by Tonic and the OS too. let (req_tx, req_rx) = tokio::sync::mpsc::channel(1); let req_stream = tokio_stream::wrappers::ReceiverStream::new(req_rx); let resp_rx = Box::pin(client.get_pages(req_stream).await?); Ok(Self { req_tx, resp_rx }) } } #[async_trait] impl Client for GrpcClient { async fn send_get_page( &mut self, req_id: u64, req_lsn: Lsn, mod_lsn: Lsn, rel: RelTag, blks: Vec<u32>, ) -> anyhow::Result<()> { let req = page_api::GetPageRequest { request_id: req_id.into(), request_class: page_api::GetPageClass::Normal, read_lsn: page_api::ReadLsn { request_lsn: req_lsn, not_modified_since_lsn: Some(mod_lsn), }, rel, block_numbers: blks, }; self.req_tx.send(req).await?; Ok(()) } async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)> { let resp = self.resp_rx.next().await.unwrap().unwrap(); anyhow::ensure!( resp.status_code == page_api::GetPageStatusCode::Ok, "unexpected status code: {}", resp.status_code, ); Ok(( resp.request_id.id, resp.pages.into_iter().map(|p| p.image).collect(), )) } } /// A rich gRPC Pageserver client. struct RichGrpcClient { inner: Arc<client_grpc::PageserverClient>, requests: FuturesUnordered< Pin<Box<dyn Future<Output = anyhow::Result<page_api::GetPageResponse>> + Send>>, >, } impl RichGrpcClient { async fn new( connstring: &str, ttid: TenantTimelineId, compression: bool, ) -> anyhow::Result<Self> { let inner = Arc::new(client_grpc::PageserverClient::new( ttid.tenant_id, ttid.timeline_id, ShardSpec::new( [(ShardIndex::unsharded(), connstring.to_string())].into(), None, )?, None, compression.then_some(tonic::codec::CompressionEncoding::Zstd), )?); Ok(Self { inner, requests: FuturesUnordered::new(), }) } } #[async_trait] impl Client for RichGrpcClient { async fn send_get_page( &mut self, req_id: u64, req_lsn: Lsn, mod_lsn: Lsn, rel: RelTag, blks: Vec<u32>, ) -> anyhow::Result<()> { let req = page_api::GetPageRequest { request_id: req_id.into(), request_class: page_api::GetPageClass::Normal, read_lsn: page_api::ReadLsn { request_lsn: req_lsn, not_modified_since_lsn: Some(mod_lsn), }, rel, block_numbers: blks, }; let inner = self.inner.clone(); self.requests.push(Box::pin(async move { inner .get_page(req) .await .map_err(|err| anyhow::anyhow!("{err}")) })); Ok(()) } async fn recv_get_page(&mut self) -> anyhow::Result<(u64, Vec<Bytes>)> { let resp = self.requests.next().await.unwrap()?; Ok(( resp.request_id.id, resp.pages.into_iter().map(|p| p.image).collect(), )) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/branch_mappings.rs
control_plane/src/branch_mappings.rs
//! Branch mappings for convenience use std::collections::HashMap; use std::fs; use std::path::Path; use anyhow::{bail, Context}; use serde::{Deserialize, Serialize}; use utils::id::{TenantId, TenantTimelineId, TimelineId}; /// Keep human-readable aliases in memory (and persist them to config XXX), to hide tenant/timeline hex strings from the user. #[derive(PartialEq, Eq, Clone, Debug, Default, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct BranchMappings { /// Default tenant ID to use with the 'neon_local' command line utility, when /// --tenant_id is not explicitly specified. This comes from the branches. pub default_tenant_id: Option<TenantId>, // A `HashMap<String, HashMap<TenantId, TimelineId>>` would be more appropriate here, // but deserialization into a generic toml object as `toml::Value::try_from` fails with an error. // https://toml.io/en/v1.0.0 does not contain a concept of "a table inside another table". pub mappings: HashMap<String, Vec<(TenantId, TimelineId)>>, } impl BranchMappings { pub fn register_branch_mapping( &mut self, branch_name: String, tenant_id: TenantId, timeline_id: TimelineId, ) -> anyhow::Result<()> { let existing_values = self.mappings.entry(branch_name.clone()).or_default(); let existing_ids = existing_values .iter() .find(|(existing_tenant_id, _)| existing_tenant_id == &tenant_id); if let Some((_, old_timeline_id)) = existing_ids { if old_timeline_id == &timeline_id { Ok(()) } else { bail!("branch '{branch_name}' is already mapped to timeline {old_timeline_id}, cannot map to another timeline {timeline_id}"); } } else { existing_values.push((tenant_id, timeline_id)); Ok(()) } } pub fn get_branch_timeline_id( &self, branch_name: &str, tenant_id: TenantId, ) -> Option<TimelineId> { // If it looks like a timeline ID, return it as it is if let Ok(timeline_id) = branch_name.parse::<TimelineId>() { return Some(timeline_id); } self.mappings .get(branch_name)? .iter() .find(|(mapped_tenant_id, _)| mapped_tenant_id == &tenant_id) .map(|&(_, timeline_id)| timeline_id) .map(TimelineId::from) } pub fn timeline_name_mappings(&self) -> HashMap<TenantTimelineId, String> { self.mappings .iter() .flat_map(|(name, tenant_timelines)| { tenant_timelines.iter().map(|&(tenant_id, timeline_id)| { (TenantTimelineId::new(tenant_id, timeline_id), name.clone()) }) }) .collect() } pub fn persist(&self, path: &Path) -> anyhow::Result<()> { let content = &toml::to_string_pretty(self)?; fs::write(path, content).with_context(|| { format!( "Failed to write branch information into path '{}'", path.display() ) }) } pub fn load(path: &Path) -> anyhow::Result<BranchMappings> { let branches_file_contents = fs::read_to_string(path)?; Ok(toml::from_str(branches_file_contents.as_str())?) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/postgresql_conf.rs
control_plane/src/postgresql_conf.rs
use std::collections::HashMap; use std::fmt; /// /// Module for parsing postgresql.conf file. /// /// NOTE: This doesn't implement the full, correct postgresql.conf syntax. Just /// enough to extract a few settings we need in Neon, assuming you don't do /// funny stuff like include-directives or funny escaping. use once_cell::sync::Lazy; use regex::Regex; /// In-memory representation of a postgresql.conf file #[derive(Default, Debug)] pub struct PostgresConf { lines: Vec<String>, hash: HashMap<String, String>, } impl PostgresConf { pub fn new() -> PostgresConf { PostgresConf::default() } /// Return the current value of 'option' pub fn get(&self, option: &str) -> Option<&str> { self.hash.get(option).map(|x| x.as_ref()) } /// /// Note: if you call this multiple times for the same option, the config /// file will a line for each call. It would be nice to have a function /// to change an existing line, but that's a TODO. /// pub fn append(&mut self, option: &str, value: &str) { self.lines .push(format!("{}={}\n", option, escape_str(value))); self.hash.insert(option.to_string(), value.to_string()); } /// Append an arbitrary non-setting line to the config file pub fn append_line(&mut self, line: &str) { self.lines.push(line.to_string()); } } impl fmt::Display for PostgresConf { /// Return the whole configuration file as a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.lines.iter() { f.write_str(line)?; } Ok(()) } } /// Escape a value for putting in postgresql.conf. fn escape_str(s: &str) -> String { // If the string doesn't contain anything that needs quoting or escaping, return it // as it is. // // The first part of the regex, before the '|', matches the INTEGER rule in the // PostgreSQL flex grammar (guc-file.l). It matches plain integers like "123" and // "-123", and also accepts units like "10MB". The second part of the regex matches // the UNQUOTED_STRING rule, and accepts strings that contain a single word, beginning // with a letter. That covers words like "off" or "posix". Everything else is quoted. // // This regex is a bit more conservative than the rules in guc-file.l, so we quote some // strings that PostgreSQL would accept without quoting, but that's OK. static UNQUOTED_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(^[-+]?[0-9]+[a-zA-Z]*$)|(^[a-zA-Z][a-zA-Z0-9]*$)").unwrap()); if UNQUOTED_RE.is_match(s) { s.to_string() } else { // Otherwise escape and quote it let s = s .replace('\\', "\\\\") .replace('\n', "\\n") .replace('\'', "''"); "\'".to_owned() + &s + "\'" } } #[test] fn test_postgresql_conf_escapes() -> anyhow::Result<()> { assert_eq!(escape_str("foo bar"), "'foo bar'"); // these don't need to be quoted assert_eq!(escape_str("foo"), "foo"); assert_eq!(escape_str("123"), "123"); assert_eq!(escape_str("+123"), "+123"); assert_eq!(escape_str("-10"), "-10"); assert_eq!(escape_str("1foo"), "1foo"); assert_eq!(escape_str("foo1"), "foo1"); assert_eq!(escape_str("10MB"), "10MB"); assert_eq!(escape_str("-10kB"), "-10kB"); // these need quoting and/or escaping assert_eq!(escape_str("foo bar"), "'foo bar'"); assert_eq!(escape_str("fo'o"), "'fo''o'"); assert_eq!(escape_str("fo\no"), "'fo\\no'"); assert_eq!(escape_str("fo\\o"), "'fo\\\\o'"); assert_eq!(escape_str("10 cats"), "'10 cats'"); Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/lib.rs
control_plane/src/lib.rs
//! Local control plane. //! //! Can start, configure and stop postgres instances running as a local processes. //! //! Intended to be used in integration tests and in CLI tools for //! local installations. #![deny(clippy::undocumented_unsafe_blocks)] mod background_process; pub mod broker; pub mod endpoint; pub mod endpoint_storage; pub mod local_env; pub mod pageserver; pub mod postgresql_conf; pub mod safekeeper; pub mod storage_controller;
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/pageserver.rs
control_plane/src/pageserver.rs
//! Code to manage pageservers //! //! In the local test environment, the data for each pageserver is stored in //! //! ```text //! .neon/pageserver_<pageserver_id> //! ``` //! use std::collections::HashMap; use std::io; use std::io::Write; use std::num::NonZeroU64; use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; use anyhow::{Context, bail}; use camino::Utf8PathBuf; use pageserver_api::config::{DEFAULT_GRPC_LISTEN_PORT, DEFAULT_HTTP_LISTEN_PORT}; use pageserver_api::models::{self, TenantInfo, TimelineInfo}; use pageserver_api::shard::TenantShardId; use pageserver_client::mgmt_api; use postgres_backend::AuthType; use postgres_connection::{PgConnectionConfig, parse_host_port}; use safekeeper_api::PgMajorVersion; use utils::auth::{Claims, Scope}; use utils::id::{NodeId, TenantId, TimelineId}; use utils::lsn::Lsn; use crate::background_process; use crate::local_env::{LocalEnv, NeonLocalInitPageserverConf, PageServerConf}; /// Directory within .neon which will be used by default for LocalFs remote storage. pub const PAGESERVER_REMOTE_STORAGE_DIR: &str = "local_fs_remote_storage/pageserver"; // // Control routines for pageserver. // // Used in CLI and tests. // #[derive(Debug)] pub struct PageServerNode { pub pg_connection_config: PgConnectionConfig, pub conf: PageServerConf, pub env: LocalEnv, pub http_client: mgmt_api::Client, } impl PageServerNode { pub fn from_env(env: &LocalEnv, conf: &PageServerConf) -> PageServerNode { let (host, port) = parse_host_port(&conf.listen_pg_addr).expect("Unable to parse listen_pg_addr"); let port = port.unwrap_or(5432); let endpoint = if env.storage_controller.use_https_pageserver_api { format!( "https://{}", conf.listen_https_addr.as_ref().expect( "listen https address should be specified if use_https_pageserver_api is on" ) ) } else { format!("http://{}", conf.listen_http_addr) }; Self { pg_connection_config: PgConnectionConfig::new_host_port(host, port), conf: conf.clone(), env: env.clone(), http_client: mgmt_api::Client::new( env.create_http_client(), endpoint, { match conf.http_auth_type { AuthType::Trust => None, AuthType::NeonJWT => Some( env.generate_auth_token(&Claims::new(None, Scope::PageServerApi)) .unwrap(), ), } } .as_deref(), ), } } fn pageserver_make_identity_toml(&self, node_id: NodeId) -> toml_edit::DocumentMut { toml_edit::DocumentMut::from_str(&format!("id={node_id}")).unwrap() } fn pageserver_init_make_toml( &self, conf: NeonLocalInitPageserverConf, ) -> anyhow::Result<toml_edit::DocumentMut> { assert_eq!( &PageServerConf::from(&conf), &self.conf, "during neon_local init, we derive the runtime state of ps conf (self.conf) from the --config flag fully" ); // TODO(christian): instead of what we do here, create a pageserver_api::config::ConfigToml (PR #7656) // FIXME: the paths should be shell-escaped to handle paths with spaces, quotas etc. let pg_distrib_dir_param = format!( "pg_distrib_dir='{}'", self.env.pg_distrib_dir_raw().display() ); let broker_endpoint_param = format!("broker_endpoint='{}'", self.env.broker.client_url()); let mut overrides = vec![pg_distrib_dir_param, broker_endpoint_param]; overrides.push(format!( "control_plane_api='{}'", self.env.control_plane_api.as_str() )); // Storage controller uses the same auth as pageserver: if JWT is enabled // for us, we will also need it to talk to them. if matches!(conf.http_auth_type, AuthType::NeonJWT) { let jwt_token = self .env .generate_auth_token(&Claims::new(None, Scope::GenerationsApi)) .unwrap(); overrides.push(format!("control_plane_api_token='{jwt_token}'")); } if !conf.other.contains_key("remote_storage") { overrides.push(format!( "remote_storage={{local_path='../{PAGESERVER_REMOTE_STORAGE_DIR}'}}" )); } if [conf.http_auth_type, conf.pg_auth_type, conf.grpc_auth_type] .contains(&AuthType::NeonJWT) { // Keys are generated in the toplevel repo dir, pageservers' workdirs // are one level below that, so refer to keys with ../ overrides.push("auth_validation_public_key_path='../auth_public_key.pem'".to_owned()); } if let Some(ssl_ca_file) = self.env.ssl_ca_cert_path() { overrides.push(format!("ssl_ca_file='{}'", ssl_ca_file.to_str().unwrap())); } // Apply the user-provided overrides overrides.push({ let mut doc = toml_edit::ser::to_document(&conf).expect("we deserialized this from toml earlier"); // `id` is written out to `identity.toml` instead of `pageserver.toml` doc.remove("id").expect("it's part of the struct"); doc.to_string() }); // Turn `overrides` into a toml document. // TODO: above code is legacy code, it should be refactored to use toml_edit directly. let mut config_toml = toml_edit::DocumentMut::new(); for fragment_str in overrides { let fragment = toml_edit::DocumentMut::from_str(&fragment_str) .expect("all fragments in `overrides` are valid toml documents, this function controls that"); for (key, item) in fragment.iter() { config_toml.insert(key, item.clone()); } } Ok(config_toml) } /// Initializes a pageserver node by creating its config with the overrides provided. pub fn initialize(&self, conf: NeonLocalInitPageserverConf) -> anyhow::Result<()> { self.pageserver_init(conf) .with_context(|| format!("Failed to run init for pageserver node {}", self.conf.id)) } pub fn repo_path(&self) -> PathBuf { self.env.pageserver_data_dir(self.conf.id) } /// The pid file is created by the pageserver process, with its pid stored inside. /// Other pageservers cannot lock the same file and overwrite it for as long as the current /// pageserver runs. (Unless someone removes the file manually; never do that!) fn pid_file(&self) -> Utf8PathBuf { Utf8PathBuf::from_path_buf(self.repo_path().join("pageserver.pid")) .expect("non-Unicode path") } pub async fn start(&self, retry_timeout: &Duration) -> anyhow::Result<()> { self.start_node(retry_timeout).await } fn pageserver_init(&self, conf: NeonLocalInitPageserverConf) -> anyhow::Result<()> { let datadir = self.repo_path(); let node_id = self.conf.id; println!( "Initializing pageserver node {} at '{}' in {:?}", node_id, self.pg_connection_config.raw_address(), datadir ); io::stdout().flush()?; // If the config file we got as a CLI argument includes the `availability_zone` // config, then use that to populate the `metadata.json` file for the pageserver. // In production the deployment orchestrator does this for us. let az_id = conf .other .get("availability_zone") .map(|toml| { let az_str = toml.to_string(); // Trim the (") chars from the toml representation if az_str.starts_with('"') && az_str.ends_with('"') { az_str[1..az_str.len() - 1].to_string() } else { az_str } }) .unwrap_or("local".to_string()); let config = self .pageserver_init_make_toml(conf) .context("make pageserver toml")?; let config_file_path = datadir.join("pageserver.toml"); let mut config_file = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&config_file_path) .with_context(|| format!("open pageserver toml for write: {config_file_path:?}"))?; config_file .write_all(config.to_string().as_bytes()) .context("write pageserver toml")?; drop(config_file); let identity_file_path = datadir.join("identity.toml"); let mut identity_file = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&identity_file_path) .with_context(|| format!("open identity toml for write: {identity_file_path:?}"))?; let identity_toml = self.pageserver_make_identity_toml(node_id); identity_file .write_all(identity_toml.to_string().as_bytes()) .context("write identity toml")?; drop(identity_toml); if self.env.generate_local_ssl_certs { self.env.generate_ssl_cert( datadir.join("server.crt").as_path(), datadir.join("server.key").as_path(), )?; } // TODO: invoke a TBD config-check command to validate that pageserver will start with the written config // Write metadata file, used by pageserver on startup to register itself with // the storage controller let metadata_path = datadir.join("metadata.json"); let http_host = "localhost".to_string(); let (_, http_port) = parse_host_port(&self.conf.listen_http_addr).expect("Unable to parse listen_http_addr"); let http_port = http_port.unwrap_or(DEFAULT_HTTP_LISTEN_PORT); let https_port = match self.conf.listen_https_addr.as_ref() { Some(https_addr) => { let (_https_host, https_port) = parse_host_port(https_addr).expect("Unable to parse listen_https_addr"); Some(https_port.unwrap_or(9899)) } None => None, }; let (mut grpc_host, mut grpc_port) = (None, None); if let Some(grpc_addr) = &self.conf.listen_grpc_addr { let (_, port) = parse_host_port(grpc_addr).expect("Unable to parse listen_grpc_addr"); grpc_host = Some("localhost".to_string()); grpc_port = Some(port.unwrap_or(DEFAULT_GRPC_LISTEN_PORT)); } // Intentionally hand-craft JSON: this acts as an implicit format compat test // in case the pageserver-side structure is edited, and reflects the real life // situation: the metadata is written by some other script. std::fs::write( metadata_path, serde_json::to_vec(&pageserver_api::config::NodeMetadata { postgres_host: "localhost".to_string(), postgres_port: self.pg_connection_config.port(), grpc_host, grpc_port, http_host, http_port, https_port, other: HashMap::from([( "availability_zone_id".to_string(), serde_json::json!(az_id), )]), }) .unwrap(), ) .expect("Failed to write metadata file"); Ok(()) } async fn start_node(&self, retry_timeout: &Duration) -> anyhow::Result<()> { // TODO: using a thread here because start_process() is not async but we need to call check_status() let datadir = self.repo_path(); println!( "Starting pageserver node {} at '{}' in {:?}, retrying for {:?}", self.conf.id, self.pg_connection_config.raw_address(), datadir, retry_timeout ); io::stdout().flush().context("flush stdout")?; let datadir_path_str = datadir.to_str().with_context(|| { format!( "Cannot start pageserver node {} in path that has no string representation: {:?}", self.conf.id, datadir, ) })?; let args = vec!["-D", datadir_path_str]; background_process::start_process( "pageserver", &datadir, &self.env.pageserver_bin(), args, self.pageserver_env_variables()?, background_process::InitialPidFile::Expect(self.pid_file()), retry_timeout, || async { let st = self.check_status().await; match st { Ok(()) => Ok(true), Err(mgmt_api::Error::ReceiveBody(_)) => Ok(false), Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")), } }, ) .await?; Ok(()) } fn pageserver_env_variables(&self) -> anyhow::Result<Vec<(String, String)>> { // FIXME: why is this tied to pageserver's auth type? Whether or not the safekeeper // needs a token, and how to generate that token, seems independent to whether // the pageserver requires a token in incoming requests. Ok(if self.conf.http_auth_type != AuthType::Trust { // Generate a token to connect from the pageserver to a safekeeper let token = self .env .generate_auth_token(&Claims::new(None, Scope::SafekeeperData))?; vec![("NEON_AUTH_TOKEN".to_owned(), token)] } else { Vec::new() }) } /// /// Stop the server. /// /// If 'immediate' is true, we use SIGQUIT, killing the process immediately. /// Otherwise we use SIGTERM, triggering a clean shutdown /// /// If the server is not running, returns success /// pub fn stop(&self, immediate: bool) -> anyhow::Result<()> { background_process::stop_process(immediate, "pageserver", &self.pid_file()) } pub async fn check_status(&self) -> mgmt_api::Result<()> { self.http_client.status().await } pub async fn tenant_list(&self) -> mgmt_api::Result<Vec<TenantInfo>> { self.http_client.list_tenants().await } pub fn parse_config(mut settings: HashMap<&str, &str>) -> anyhow::Result<models::TenantConfig> { let result = models::TenantConfig { checkpoint_distance: settings .remove("checkpoint_distance") .map(|x| x.parse::<u64>()) .transpose() .context("Failed to parse 'checkpoint_distance' as an integer")?, checkpoint_timeout: settings .remove("checkpoint_timeout") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'checkpoint_timeout' as duration")?, compaction_target_size: settings .remove("compaction_target_size") .map(|x| x.parse::<u64>()) .transpose() .context("Failed to parse 'compaction_target_size' as an integer")?, compaction_period: settings .remove("compaction_period") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'compaction_period' as duration")?, compaction_threshold: settings .remove("compaction_threshold") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'compaction_threshold' as an integer")?, compaction_upper_limit: settings .remove("compaction_upper_limit") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'compaction_upper_limit' as an integer")?, compaction_algorithm: settings .remove("compaction_algorithm") .map(serde_json::from_str) .transpose() .context("Failed to parse 'compaction_algorithm' json")?, compaction_shard_ancestor: settings .remove("compaction_shard_ancestor") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'compaction_shard_ancestor' as a bool")?, compaction_l0_first: settings .remove("compaction_l0_first") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'compaction_l0_first' as a bool")?, compaction_l0_semaphore: settings .remove("compaction_l0_semaphore") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'compaction_l0_semaphore' as a bool")?, l0_flush_delay_threshold: settings .remove("l0_flush_delay_threshold") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'l0_flush_delay_threshold' as an integer")?, l0_flush_stall_threshold: settings .remove("l0_flush_stall_threshold") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'l0_flush_stall_threshold' as an integer")?, gc_horizon: settings .remove("gc_horizon") .map(|x| x.parse::<u64>()) .transpose() .context("Failed to parse 'gc_horizon' as an integer")?, gc_period: settings.remove("gc_period") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'gc_period' as duration")?, image_creation_threshold: settings .remove("image_creation_threshold") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'image_creation_threshold' as non zero integer")?, // HADRON image_layer_force_creation_period: settings .remove("image_layer_force_creation_period") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'image_layer_force_creation_period' as duration")?, image_layer_creation_check_threshold: settings .remove("image_layer_creation_check_threshold") .map(|x| x.parse::<u8>()) .transpose() .context("Failed to parse 'image_creation_check_threshold' as integer")?, image_creation_preempt_threshold: settings .remove("image_creation_preempt_threshold") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'image_creation_preempt_threshold' as integer")?, pitr_interval: settings.remove("pitr_interval") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'pitr_interval' as duration")?, walreceiver_connect_timeout: settings .remove("walreceiver_connect_timeout") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'walreceiver_connect_timeout' as duration")?, lagging_wal_timeout: settings .remove("lagging_wal_timeout") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'lagging_wal_timeout' as duration")?, max_lsn_wal_lag: settings .remove("max_lsn_wal_lag") .map(|x| x.parse::<NonZeroU64>()) .transpose() .context("Failed to parse 'max_lsn_wal_lag' as non zero integer")?, eviction_policy: settings .remove("eviction_policy") .map(serde_json::from_str) .transpose() .context("Failed to parse 'eviction_policy' json")?, min_resident_size_override: settings .remove("min_resident_size_override") .map(|x| x.parse::<u64>()) .transpose() .context("Failed to parse 'min_resident_size_override' as integer")?, evictions_low_residence_duration_metric_threshold: settings .remove("evictions_low_residence_duration_metric_threshold") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'evictions_low_residence_duration_metric_threshold' as duration")?, heatmap_period: settings .remove("heatmap_period") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'heatmap_period' as duration")?, lazy_slru_download: settings .remove("lazy_slru_download") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'lazy_slru_download' as bool")?, timeline_get_throttle: settings .remove("timeline_get_throttle") .map(serde_json::from_str) .transpose() .context("parse `timeline_get_throttle` from json")?, lsn_lease_length: settings.remove("lsn_lease_length") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'lsn_lease_length' as duration")?, lsn_lease_length_for_ts: settings .remove("lsn_lease_length_for_ts") .map(humantime::parse_duration) .transpose() .context("Failed to parse 'lsn_lease_length_for_ts' as duration")?, timeline_offloading: settings .remove("timeline_offloading") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'timeline_offloading' as bool")?, rel_size_v2_enabled: settings .remove("rel_size_v2_enabled") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'rel_size_v2_enabled' as bool")?, gc_compaction_enabled: settings .remove("gc_compaction_enabled") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'gc_compaction_enabled' as bool")?, gc_compaction_verification: settings .remove("gc_compaction_verification") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'gc_compaction_verification' as bool")?, gc_compaction_initial_threshold_kb: settings .remove("gc_compaction_initial_threshold_kb") .map(|x| x.parse::<u64>()) .transpose() .context("Failed to parse 'gc_compaction_initial_threshold_kb' as integer")?, gc_compaction_ratio_percent: settings .remove("gc_compaction_ratio_percent") .map(|x| x.parse::<u64>()) .transpose() .context("Failed to parse 'gc_compaction_ratio_percent' as integer")?, sampling_ratio: settings .remove("sampling_ratio") .map(serde_json::from_str) .transpose() .context("Failed to parse 'sampling_ratio'")?, relsize_snapshot_cache_capacity: settings .remove("relsize snapshot cache capacity") .map(|x| x.parse::<usize>()) .transpose() .context("Failed to parse 'relsize_snapshot_cache_capacity' as integer")?, basebackup_cache_enabled: settings .remove("basebackup_cache_enabled") .map(|x| x.parse::<bool>()) .transpose() .context("Failed to parse 'basebackup_cache_enabled' as bool")?, }; if !settings.is_empty() { bail!("Unrecognized tenant settings: {settings:?}") } else { Ok(result) } } pub async fn tenant_config( &self, tenant_id: TenantId, settings: HashMap<&str, &str>, ) -> anyhow::Result<()> { let config = Self::parse_config(settings)?; self.http_client .set_tenant_config(&models::TenantConfigRequest { tenant_id, config }) .await?; Ok(()) } pub async fn timeline_list( &self, tenant_shard_id: &TenantShardId, ) -> anyhow::Result<Vec<TimelineInfo>> { Ok(self.http_client.list_timelines(*tenant_shard_id).await?) } /// Import a basebackup prepared using either: /// a) `pg_basebackup -F tar`, or /// b) The `fullbackup` pageserver endpoint /// /// # Arguments /// * `tenant_id` - tenant to import into. Created if not exists /// * `timeline_id` - id to assign to imported timeline /// * `base` - (start lsn of basebackup, path to `base.tar` file) /// * `pg_wal` - if there's any wal to import: (end lsn, path to `pg_wal.tar`) pub async fn timeline_import( &self, tenant_id: TenantId, timeline_id: TimelineId, base: (Lsn, PathBuf), pg_wal: Option<(Lsn, PathBuf)>, pg_version: PgMajorVersion, ) -> anyhow::Result<()> { // Init base reader let (start_lsn, base_tarfile_path) = base; let base_tarfile = tokio::fs::File::open(base_tarfile_path).await?; let base_tarfile = mgmt_api::ReqwestBody::wrap_stream(tokio_util::io::ReaderStream::new(base_tarfile)); // Init wal reader if necessary let (end_lsn, wal_reader) = if let Some((end_lsn, wal_tarfile_path)) = pg_wal { let wal_tarfile = tokio::fs::File::open(wal_tarfile_path).await?; let wal_reader = mgmt_api::ReqwestBody::wrap_stream(tokio_util::io::ReaderStream::new(wal_tarfile)); (end_lsn, Some(wal_reader)) } else { (start_lsn, None) }; // Import base self.http_client .import_basebackup( tenant_id, timeline_id, start_lsn, end_lsn, pg_version, base_tarfile, ) .await?; // Import wal if necessary if let Some(wal_reader) = wal_reader { self.http_client .import_wal(tenant_id, timeline_id, start_lsn, end_lsn, wal_reader) .await?; } Ok(()) } pub async fn timeline_info( &self, tenant_shard_id: TenantShardId, timeline_id: TimelineId, force_await_logical_size: mgmt_api::ForceAwaitLogicalSize, ) -> anyhow::Result<TimelineInfo> { let timeline_info = self .http_client .timeline_info(tenant_shard_id, timeline_id, force_await_logical_size) .await?; Ok(timeline_info) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/endpoint_storage.rs
control_plane/src/endpoint_storage.rs
use crate::background_process::{self, start_process, stop_process}; use crate::local_env::LocalEnv; use anyhow::{Context, Result}; use camino::Utf8PathBuf; use std::io::Write; use std::net::SocketAddr; use std::time::Duration; /// Directory within .neon which will be used by default for LocalFs remote storage. pub const ENDPOINT_STORAGE_REMOTE_STORAGE_DIR: &str = "local_fs_remote_storage/endpoint_storage"; pub const ENDPOINT_STORAGE_DEFAULT_ADDR: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 9993); pub struct EndpointStorage { pub bin: Utf8PathBuf, pub data_dir: Utf8PathBuf, pub pemfile: Utf8PathBuf, pub addr: SocketAddr, } impl EndpointStorage { pub fn from_env(env: &LocalEnv) -> EndpointStorage { EndpointStorage { bin: Utf8PathBuf::from_path_buf(env.endpoint_storage_bin()).unwrap(), data_dir: Utf8PathBuf::from_path_buf(env.endpoint_storage_data_dir()).unwrap(), pemfile: Utf8PathBuf::from_path_buf(env.public_key_path.clone()).unwrap(), addr: env.endpoint_storage.listen_addr, } } fn config_path(&self) -> Utf8PathBuf { self.data_dir.join("endpoint_storage.json") } fn listen_addr(&self) -> Utf8PathBuf { format!("{}:{}", self.addr.ip(), self.addr.port()).into() } pub fn init(&self) -> Result<()> { println!("Initializing object storage in {:?}", self.data_dir); let parent = self.data_dir.parent().unwrap(); #[derive(serde::Serialize)] struct Cfg { listen: Utf8PathBuf, pemfile: Utf8PathBuf, local_path: Utf8PathBuf, r#type: String, } let cfg = Cfg { listen: self.listen_addr(), pemfile: parent.join(self.pemfile.clone()), local_path: parent.join(ENDPOINT_STORAGE_REMOTE_STORAGE_DIR), r#type: "LocalFs".to_string(), }; std::fs::create_dir_all(self.config_path().parent().unwrap())?; std::fs::write(self.config_path(), serde_json::to_string(&cfg)?) .context("write object storage config")?; Ok(()) } pub async fn start(&self, retry_timeout: &Duration) -> Result<()> { println!("Starting endpoint_storage at {}", self.listen_addr()); std::io::stdout().flush().context("flush stdout")?; let process_status_check = || async { let res = reqwest::Client::new().get(format!("http://{}/metrics", self.listen_addr())); match res.send().await { Ok(res) => Ok(res.status().is_success()), Err(_) => Ok(false), } }; let res = start_process( "endpoint_storage", &self.data_dir.clone().into_std_path_buf(), &self.bin.clone().into_std_path_buf(), vec![self.config_path().to_string()], vec![("RUST_LOG".into(), "debug".into())], background_process::InitialPidFile::Create(self.pid_file()), retry_timeout, process_status_check, ) .await; if res.is_err() { eprintln!("Logs:\n{}", std::fs::read_to_string(self.log_file())?); } res } pub fn stop(&self, immediate: bool) -> anyhow::Result<()> { stop_process(immediate, "endpoint_storage", &self.pid_file()) } fn log_file(&self) -> Utf8PathBuf { self.data_dir.join("endpoint_storage.log") } fn pid_file(&self) -> Utf8PathBuf { self.data_dir.join("endpoint_storage.pid") } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/safekeeper.rs
control_plane/src/safekeeper.rs
//! Code to manage safekeepers //! //! In the local test environment, the data for each safekeeper is stored in //! //! ```text //! .neon/safekeepers/<safekeeper id> //! ``` use std::error::Error as _; use std::io::Write; use std::path::PathBuf; use std::time::Duration; use std::{io, result}; use anyhow::Context; use camino::Utf8PathBuf; use postgres_connection::PgConnectionConfig; use safekeeper_api::models::TimelineCreateRequest; use safekeeper_client::mgmt_api; use thiserror::Error; use utils::auth::{Claims, Scope}; use utils::id::NodeId; use crate::background_process; use crate::local_env::{LocalEnv, SafekeeperConf}; #[derive(Error, Debug)] pub enum SafekeeperHttpError { #[error("request error: {0}{}", .0.source().map(|e| format!(": {e}")).unwrap_or_default())] Transport(#[from] reqwest::Error), #[error("Error: {0}")] Response(String), } type Result<T> = result::Result<T, SafekeeperHttpError>; fn err_from_client_err(err: mgmt_api::Error) -> SafekeeperHttpError { use mgmt_api::Error::*; match err { ApiError(_, str) => SafekeeperHttpError::Response(str), Cancelled => SafekeeperHttpError::Response("Cancelled".to_owned()), ReceiveBody(err) => SafekeeperHttpError::Transport(err), ReceiveErrorBody(err) => SafekeeperHttpError::Response(err), Timeout(str) => SafekeeperHttpError::Response(format!("timeout: {str}")), } } // // Control routines for safekeeper. // // Used in CLI and tests. // #[derive(Debug)] pub struct SafekeeperNode { pub id: NodeId, pub conf: SafekeeperConf, pub pg_connection_config: PgConnectionConfig, pub env: LocalEnv, pub http_client: mgmt_api::Client, pub listen_addr: String, } impl SafekeeperNode { pub fn from_env(env: &LocalEnv, conf: &SafekeeperConf) -> SafekeeperNode { let listen_addr = if let Some(ref listen_addr) = conf.listen_addr { listen_addr.clone() } else { "127.0.0.1".to_string() }; let jwt = None; let http_base_url = format!("http://{}:{}", listen_addr, conf.http_port); SafekeeperNode { id: conf.id, conf: conf.clone(), pg_connection_config: Self::safekeeper_connection_config(&listen_addr, conf.pg_port), env: env.clone(), http_client: mgmt_api::Client::new(env.create_http_client(), http_base_url, jwt), listen_addr, } } /// Construct libpq connection string for connecting to this safekeeper. fn safekeeper_connection_config(addr: &str, port: u16) -> PgConnectionConfig { PgConnectionConfig::new_host_port(url::Host::parse(addr).unwrap(), port) } pub fn datadir_path_by_id(env: &LocalEnv, sk_id: NodeId) -> PathBuf { env.safekeeper_data_dir(&format!("sk{sk_id}")) } pub fn datadir_path(&self) -> PathBuf { SafekeeperNode::datadir_path_by_id(&self.env, self.id) } pub fn pid_file(&self) -> Utf8PathBuf { Utf8PathBuf::from_path_buf(self.datadir_path().join("safekeeper.pid")) .expect("non-Unicode path") } /// Initializes a safekeeper node by creating all necessary files, /// e.g. SSL certificates and JWT token file. pub fn initialize(&self) -> anyhow::Result<()> { if self.env.generate_local_ssl_certs { self.env.generate_ssl_cert( &self.datadir_path().join("server.crt"), &self.datadir_path().join("server.key"), )?; } // Generate a token file for authentication with other safekeepers if self.conf.auth_enabled { let token = self .env .generate_auth_token(&Claims::new(None, Scope::SafekeeperData))?; let token_path = self.datadir_path().join("peer_jwt_token"); std::fs::write(token_path, token)?; } Ok(()) } pub async fn start( &self, extra_opts: &[String], retry_timeout: &Duration, ) -> anyhow::Result<()> { println!( "Starting safekeeper at '{}' in '{}', retrying for {:?}", self.pg_connection_config.raw_address(), self.datadir_path().display(), retry_timeout, ); io::stdout().flush().unwrap(); let listen_pg = format!("{}:{}", self.listen_addr, self.conf.pg_port); let listen_http = format!("{}:{}", self.listen_addr, self.conf.http_port); let id = self.id; let datadir = self.datadir_path(); let id_string = id.to_string(); // TODO: add availability_zone to the config. // Right now we just specify any value here and use it to check metrics in tests. let availability_zone = format!("sk-{id_string}"); let mut args = vec![ "-D".to_owned(), datadir .to_str() .with_context(|| { format!("Datadir path {datadir:?} cannot be represented as a unicode string") })? .to_owned(), "--id".to_owned(), id_string, "--listen-pg".to_owned(), listen_pg, "--listen-http".to_owned(), listen_http, "--availability-zone".to_owned(), availability_zone, ]; if let Some(pg_tenant_only_port) = self.conf.pg_tenant_only_port { let listen_pg_tenant_only = format!("{}:{}", self.listen_addr, pg_tenant_only_port); args.extend(["--listen-pg-tenant-only".to_owned(), listen_pg_tenant_only]); } if !self.conf.sync { args.push("--no-sync".to_owned()); } let broker_endpoint = format!("{}", self.env.broker.client_url()); args.extend(["--broker-endpoint".to_owned(), broker_endpoint]); let mut backup_threads = String::new(); if let Some(threads) = self.conf.backup_threads { backup_threads = threads.to_string(); args.extend(["--backup-threads".to_owned(), backup_threads]); } else { drop(backup_threads); } if let Some(ref remote_storage) = self.conf.remote_storage { args.extend(["--remote-storage".to_owned(), remote_storage.clone()]); } let key_path = self.env.base_data_dir.join("auth_public_key.pem"); if self.conf.auth_enabled { let key_path_string = key_path .to_str() .with_context(|| { format!("Key path {key_path:?} cannot be represented as a unicode string") })? .to_owned(); args.extend([ "--pg-auth-public-key-path".to_owned(), key_path_string.clone(), ]); args.extend([ "--pg-tenant-only-auth-public-key-path".to_owned(), key_path_string.clone(), ]); args.extend([ "--http-auth-public-key-path".to_owned(), key_path_string.clone(), ]); } if let Some(https_port) = self.conf.https_port { args.extend([ "--listen-https".to_owned(), format!("{}:{}", self.listen_addr, https_port), ]); } if let Some(ssl_ca_file) = self.env.ssl_ca_cert_path() { args.push(format!("--ssl-ca-file={}", ssl_ca_file.to_str().unwrap())); } if self.conf.auth_enabled { let token_path = self.datadir_path().join("peer_jwt_token"); let token_path_str = token_path .to_str() .with_context(|| { format!("Token path {token_path:?} cannot be represented as a unicode string") })? .to_owned(); args.extend(["--auth-token-path".to_owned(), token_path_str]); } args.extend_from_slice(extra_opts); let env_variables = Vec::new(); background_process::start_process( &format!("safekeeper-{id}"), &datadir, &self.env.safekeeper_bin(), &args, env_variables, background_process::InitialPidFile::Expect(self.pid_file()), retry_timeout, || async { match self.check_status().await { Ok(()) => Ok(true), Err(SafekeeperHttpError::Transport(_)) => Ok(false), Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")), } }, ) .await } /// /// Stop the server. /// /// If 'immediate' is true, we use SIGQUIT, killing the process immediately. /// Otherwise we use SIGTERM, triggering a clean shutdown /// /// If the server is not running, returns success /// pub fn stop(&self, immediate: bool) -> anyhow::Result<()> { background_process::stop_process( immediate, &format!("safekeeper {}", self.id), &self.pid_file(), ) } pub async fn check_status(&self) -> Result<()> { self.http_client .status() .await .map_err(err_from_client_err)?; Ok(()) } pub async fn create_timeline(&self, req: &TimelineCreateRequest) -> Result<()> { self.http_client .create_timeline(req) .await .map_err(err_from_client_err)?; Ok(()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/local_env.rs
control_plane/src/local_env.rs
//! This module is responsible for locating and loading paths in a local setup. //! //! Now it also provides init method which acts like a stub for proper installation //! script which will use local paths. use std::collections::HashMap; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::Duration; use std::{env, fs}; use anyhow::{Context, bail}; use clap::ValueEnum; use pageserver_api::config::PostHogConfig; use pem::Pem; use postgres_backend::AuthType; use reqwest::{Certificate, Url}; use safekeeper_api::PgMajorVersion; use serde::{Deserialize, Serialize}; use utils::auth::encode_from_key_file; use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId}; use crate::broker::StorageBroker; use crate::endpoint_storage::{ ENDPOINT_STORAGE_DEFAULT_ADDR, ENDPOINT_STORAGE_REMOTE_STORAGE_DIR, EndpointStorage, }; use crate::pageserver::{PAGESERVER_REMOTE_STORAGE_DIR, PageServerNode}; use crate::safekeeper::SafekeeperNode; pub const DEFAULT_PG_VERSION: u32 = 17; // // This data structures represents neon_local CLI config // // It is deserialized from the .neon/config file, or the config file passed // to 'neon_local init --config=<path>' option. See control_plane/simple.conf for // an example. // #[derive(PartialEq, Eq, Clone, Debug)] pub struct LocalEnv { // Base directory for all the nodes (the pageserver, safekeepers and // compute endpoints). // // This is not stored in the config file. Rather, this is the path where the // config file itself is. It is read from the NEON_REPO_DIR env variable which // must be an absolute path. If the env var is not set, $PWD/.neon is used. pub base_data_dir: PathBuf, // Path to postgres distribution. It's expected that "bin", "include", // "lib", "share" from postgres distribution are there. If at some point // in time we will be able to run against vanilla postgres we may split that // to four separate paths and match OS-specific installation layout. pub pg_distrib_dir: PathBuf, // Path to pageserver binary. pub neon_distrib_dir: PathBuf, // Default tenant ID to use with the 'neon_local' command line utility, when // --tenant_id is not explicitly specified. pub default_tenant_id: Option<TenantId>, // used to issue tokens during e.g pg start pub private_key_path: PathBuf, /// Path to environment's public key pub public_key_path: PathBuf, pub broker: NeonBroker, // Configuration for the storage controller (1 per neon_local environment) pub storage_controller: NeonStorageControllerConf, /// This Vec must always contain at least one pageserver /// Populdated by [`Self::load_config`] from the individual `pageserver.toml`s. /// NB: not used anymore except for informing users that they need to change their `.neon/config`. pub pageservers: Vec<PageServerConf>, pub safekeepers: Vec<SafekeeperConf>, pub endpoint_storage: EndpointStorageConf, // Control plane upcall API for pageserver: if None, we will not run storage_controller If set, this will // be propagated into each pageserver's configuration. pub control_plane_api: Url, // Control plane upcall APIs for storage controller. If set, this will be propagated into the // storage controller's configuration. pub control_plane_hooks_api: Option<Url>, /// Keep human-readable aliases in memory (and persist them to config), to hide ZId hex strings from the user. // A `HashMap<String, HashMap<TenantId, TimelineId>>` would be more appropriate here, // but deserialization into a generic toml object as `toml::Value::try_from` fails with an error. // https://toml.io/en/v1.0.0 does not contain a concept of "a table inside another table". pub branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>, /// Flag to generate SSL certificates for components that need it. /// Also generates root CA certificate that is used to sign all other certificates. pub generate_local_ssl_certs: bool, } /// On-disk state stored in `.neon/config`. #[derive(PartialEq, Eq, Clone, Debug, Default, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct OnDiskConfig { pub pg_distrib_dir: PathBuf, pub neon_distrib_dir: PathBuf, pub default_tenant_id: Option<TenantId>, pub private_key_path: PathBuf, pub public_key_path: PathBuf, pub broker: NeonBroker, pub storage_controller: NeonStorageControllerConf, #[serde( skip_serializing, deserialize_with = "fail_if_pageservers_field_specified" )] pub pageservers: Vec<PageServerConf>, pub safekeepers: Vec<SafekeeperConf>, pub endpoint_storage: EndpointStorageConf, pub control_plane_api: Option<Url>, pub control_plane_hooks_api: Option<Url>, pub control_plane_compute_hook_api: Option<Url>, branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>, // Note: skip serializing because in compat tests old storage controller fails // to load new config file. May be removed after this field is in release branch. #[serde(skip_serializing_if = "std::ops::Not::not")] pub generate_local_ssl_certs: bool, } fn fail_if_pageservers_field_specified<'de, D>(_: D) -> Result<Vec<PageServerConf>, D::Error> where D: serde::Deserializer<'de>, { Err(serde::de::Error::custom( "The 'pageservers' field is no longer used; pageserver.toml is now authoritative; \ Please remove the `pageservers` from your .neon/config.", )) } /// The description of the neon_local env to be initialized by `neon_local init --config`. #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct NeonLocalInitConf { // TODO: do we need this? Seems unused pub pg_distrib_dir: Option<PathBuf>, // TODO: do we need this? Seems unused pub neon_distrib_dir: Option<PathBuf>, pub default_tenant_id: TenantId, pub broker: NeonBroker, pub storage_controller: Option<NeonStorageControllerConf>, pub pageservers: Vec<NeonLocalInitPageserverConf>, pub safekeepers: Vec<SafekeeperConf>, pub endpoint_storage: EndpointStorageConf, pub control_plane_api: Option<Url>, pub control_plane_hooks_api: Option<Url>, pub generate_local_ssl_certs: bool, } #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)] #[serde(default)] pub struct EndpointStorageConf { pub listen_addr: SocketAddr, } /// Broker config for cluster internal communication. #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Default)] #[serde(default)] pub struct NeonBroker { /// Broker listen HTTP address for storage nodes coordination, e.g. '127.0.0.1:50051'. /// At least one of listen_addr or listen_https_addr must be set. pub listen_addr: Option<SocketAddr>, /// Broker listen HTTPS address for storage nodes coordination, e.g. '127.0.0.1:50051'. /// At least one of listen_addr or listen_https_addr must be set. /// listen_https_addr is preferred over listen_addr in neon_local. pub listen_https_addr: Option<SocketAddr>, } /// A part of storage controller's config the neon_local knows about. #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)] #[serde(default)] pub struct NeonStorageControllerConf { /// Heartbeat timeout before marking a node offline #[serde(with = "humantime_serde")] pub max_offline: Duration, #[serde(with = "humantime_serde")] pub max_warming_up: Duration, pub start_as_candidate: bool, /// Database url used when running multiple storage controller instances pub database_url: Option<SocketAddr>, /// Thresholds for auto-splitting a tenant into shards. pub split_threshold: Option<u64>, pub max_split_shards: Option<u8>, pub initial_split_threshold: Option<u64>, pub initial_split_shards: Option<u8>, pub max_secondary_lag_bytes: Option<u64>, #[serde(with = "humantime_serde")] pub heartbeat_interval: Duration, #[serde(with = "humantime_serde")] pub long_reconcile_threshold: Option<Duration>, pub use_https_pageserver_api: bool, pub timelines_onto_safekeepers: bool, pub use_https_safekeeper_api: bool, pub use_local_compute_notifications: bool, pub timeline_safekeeper_count: Option<usize>, pub posthog_config: Option<PostHogConfig>, pub kick_secondary_downloads: Option<bool>, #[serde(with = "humantime_serde")] pub shard_split_request_timeout: Option<Duration>, } impl NeonStorageControllerConf { // Use a shorter pageserver unavailability interval than the default to speed up tests. const DEFAULT_MAX_OFFLINE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10); const DEFAULT_MAX_WARMING_UP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30); // Very tight heartbeat interval to speed up tests const DEFAULT_HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000); } impl Default for NeonStorageControllerConf { fn default() -> Self { Self { max_offline: Self::DEFAULT_MAX_OFFLINE_INTERVAL, max_warming_up: Self::DEFAULT_MAX_WARMING_UP_INTERVAL, start_as_candidate: false, database_url: None, split_threshold: None, max_split_shards: None, initial_split_threshold: None, initial_split_shards: None, max_secondary_lag_bytes: None, heartbeat_interval: Self::DEFAULT_HEARTBEAT_INTERVAL, long_reconcile_threshold: None, use_https_pageserver_api: false, timelines_onto_safekeepers: true, use_https_safekeeper_api: false, use_local_compute_notifications: true, timeline_safekeeper_count: None, posthog_config: None, kick_secondary_downloads: None, shard_split_request_timeout: None, } } } impl Default for EndpointStorageConf { fn default() -> Self { Self { listen_addr: ENDPOINT_STORAGE_DEFAULT_ADDR, } } } impl NeonBroker { pub fn client_url(&self) -> Url { let url = if let Some(addr) = self.listen_https_addr { format!("https://{addr}") } else { format!( "http://{}", self.listen_addr .expect("at least one address should be set") ) }; Url::parse(&url).expect("failed to construct url") } } // neon_local needs to know this subset of pageserver configuration. // For legacy reasons, this information is duplicated from `pageserver.toml` into `.neon/config`. // It can get stale if `pageserver.toml` is changed. // TODO(christian): don't store this at all in `.neon/config`, always load it from `pageserver.toml` #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)] #[serde(default, deny_unknown_fields)] pub struct PageServerConf { pub id: NodeId, pub listen_pg_addr: String, pub listen_http_addr: String, pub listen_https_addr: Option<String>, pub listen_grpc_addr: Option<String>, pub pg_auth_type: AuthType, pub http_auth_type: AuthType, pub grpc_auth_type: AuthType, pub no_sync: bool, } impl Default for PageServerConf { fn default() -> Self { Self { id: NodeId(0), listen_pg_addr: String::new(), listen_http_addr: String::new(), listen_https_addr: None, listen_grpc_addr: None, pg_auth_type: AuthType::Trust, http_auth_type: AuthType::Trust, grpc_auth_type: AuthType::Trust, no_sync: false, } } } /// The toml that can be passed to `neon_local init --config`. /// This is a subset of the `pageserver.toml` configuration. // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656) #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct NeonLocalInitPageserverConf { pub id: NodeId, pub listen_pg_addr: String, pub listen_http_addr: String, pub listen_https_addr: Option<String>, pub listen_grpc_addr: Option<String>, pub pg_auth_type: AuthType, pub http_auth_type: AuthType, pub grpc_auth_type: AuthType, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub no_sync: bool, #[serde(flatten)] pub other: HashMap<String, toml::Value>, } impl From<&NeonLocalInitPageserverConf> for PageServerConf { fn from(conf: &NeonLocalInitPageserverConf) -> Self { let NeonLocalInitPageserverConf { id, listen_pg_addr, listen_http_addr, listen_https_addr, listen_grpc_addr, pg_auth_type, http_auth_type, grpc_auth_type, no_sync, other: _, } = conf; Self { id: *id, listen_pg_addr: listen_pg_addr.clone(), listen_http_addr: listen_http_addr.clone(), listen_https_addr: listen_https_addr.clone(), listen_grpc_addr: listen_grpc_addr.clone(), pg_auth_type: *pg_auth_type, grpc_auth_type: *grpc_auth_type, http_auth_type: *http_auth_type, no_sync: *no_sync, } } } #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)] #[serde(default)] pub struct SafekeeperConf { pub id: NodeId, pub pg_port: u16, pub pg_tenant_only_port: Option<u16>, pub http_port: u16, pub https_port: Option<u16>, pub sync: bool, pub remote_storage: Option<String>, pub backup_threads: Option<u32>, pub auth_enabled: bool, pub listen_addr: Option<String>, } impl Default for SafekeeperConf { fn default() -> Self { Self { id: NodeId(0), pg_port: 0, pg_tenant_only_port: None, http_port: 0, https_port: None, sync: true, remote_storage: None, backup_threads: None, auth_enabled: false, listen_addr: None, } } } #[derive(Clone, Copy)] pub enum InitForceMode { MustNotExist, EmptyDirOk, RemoveAllContents, } impl ValueEnum for InitForceMode { fn value_variants<'a>() -> &'a [Self] { &[ Self::MustNotExist, Self::EmptyDirOk, Self::RemoveAllContents, ] } fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> { Some(clap::builder::PossibleValue::new(match self { InitForceMode::MustNotExist => "must-not-exist", InitForceMode::EmptyDirOk => "empty-dir-ok", InitForceMode::RemoveAllContents => "remove-all-contents", })) } } impl SafekeeperConf { /// Compute is served by port on which only tenant scoped tokens allowed, if /// it is configured. pub fn get_compute_port(&self) -> u16 { self.pg_tenant_only_port.unwrap_or(self.pg_port) } } impl LocalEnv { pub fn pg_distrib_dir_raw(&self) -> PathBuf { self.pg_distrib_dir.clone() } pub fn pg_distrib_dir(&self, pg_version: PgMajorVersion) -> anyhow::Result<PathBuf> { let path = self.pg_distrib_dir.clone(); Ok(path.join(pg_version.v_str())) } pub fn pg_dir(&self, pg_version: PgMajorVersion, dir_name: &str) -> anyhow::Result<PathBuf> { Ok(self.pg_distrib_dir(pg_version)?.join(dir_name)) } pub fn pg_bin_dir(&self, pg_version: PgMajorVersion) -> anyhow::Result<PathBuf> { self.pg_dir(pg_version, "bin") } pub fn pg_lib_dir(&self, pg_version: PgMajorVersion) -> anyhow::Result<PathBuf> { self.pg_dir(pg_version, "lib") } pub fn endpoint_storage_bin(&self) -> PathBuf { self.neon_distrib_dir.join("endpoint_storage") } pub fn pageserver_bin(&self) -> PathBuf { self.neon_distrib_dir.join("pageserver") } pub fn storage_controller_bin(&self) -> PathBuf { // Irrespective of configuration, storage controller binary is always // run from the same location as neon_local. This means that for compatibility // tests that run old pageserver/safekeeper, they still run latest storage controller. let neon_local_bin_dir = env::current_exe().unwrap().parent().unwrap().to_owned(); neon_local_bin_dir.join("storage_controller") } pub fn safekeeper_bin(&self) -> PathBuf { self.neon_distrib_dir.join("safekeeper") } pub fn storage_broker_bin(&self) -> PathBuf { self.neon_distrib_dir.join("storage_broker") } pub fn endpoints_path(&self) -> PathBuf { self.base_data_dir.join("endpoints") } pub fn storage_broker_data_dir(&self) -> PathBuf { self.base_data_dir.join("storage_broker") } pub fn pageserver_data_dir(&self, pageserver_id: NodeId) -> PathBuf { self.base_data_dir .join(format!("pageserver_{pageserver_id}")) } pub fn safekeeper_data_dir(&self, data_dir_name: &str) -> PathBuf { self.base_data_dir.join("safekeepers").join(data_dir_name) } pub fn endpoint_storage_data_dir(&self) -> PathBuf { self.base_data_dir.join("endpoint_storage") } pub fn get_pageserver_conf(&self, id: NodeId) -> anyhow::Result<&PageServerConf> { if let Some(conf) = self.pageservers.iter().find(|node| node.id == id) { Ok(conf) } else { let have_ids = self .pageservers .iter() .map(|node| format!("{}:{}", node.id, node.listen_http_addr)) .collect::<Vec<_>>(); let joined = have_ids.join(","); bail!("could not find pageserver {id}, have ids {joined}") } } pub fn ssl_ca_cert_path(&self) -> Option<PathBuf> { if self.generate_local_ssl_certs { Some(self.base_data_dir.join("rootCA.crt")) } else { None } } pub fn ssl_ca_key_path(&self) -> Option<PathBuf> { if self.generate_local_ssl_certs { Some(self.base_data_dir.join("rootCA.key")) } else { None } } pub fn generate_ssl_ca_cert(&self) -> anyhow::Result<()> { let cert_path = self.ssl_ca_cert_path().unwrap(); let key_path = self.ssl_ca_key_path().unwrap(); if !fs::exists(cert_path.as_path())? { generate_ssl_ca_cert(cert_path.as_path(), key_path.as_path())?; } Ok(()) } pub fn generate_ssl_cert(&self, cert_path: &Path, key_path: &Path) -> anyhow::Result<()> { self.generate_ssl_ca_cert()?; generate_ssl_cert( cert_path, key_path, self.ssl_ca_cert_path().unwrap().as_path(), self.ssl_ca_key_path().unwrap().as_path(), ) } /// Creates HTTP client with local SSL CA certificates. pub fn create_http_client(&self) -> reqwest::Client { let ssl_ca_certs = self.ssl_ca_cert_path().map(|ssl_ca_file| { let buf = std::fs::read(ssl_ca_file).expect("SSL CA file should exist"); Certificate::from_pem_bundle(&buf).expect("SSL CA file should be valid") }); let mut http_client = reqwest::Client::builder(); for ssl_ca_cert in ssl_ca_certs.unwrap_or_default() { http_client = http_client.add_root_certificate(ssl_ca_cert); } http_client .build() .expect("HTTP client should construct with no error") } /// Inspect the base data directory and extract the instance id and instance directory path /// for all storage controller instances pub async fn storage_controller_instances(&self) -> std::io::Result<Vec<(u8, PathBuf)>> { let mut instances = Vec::default(); let dir = std::fs::read_dir(self.base_data_dir.clone())?; for dentry in dir { let dentry = dentry?; let is_dir = dentry.metadata()?.is_dir(); let filename = dentry.file_name().into_string().unwrap(); let parsed_instance_id = match filename.strip_prefix("storage_controller_") { Some(suffix) => suffix.parse::<u8>().ok(), None => None, }; let is_instance_dir = is_dir && parsed_instance_id.is_some(); if !is_instance_dir { continue; } instances.push(( parsed_instance_id.expect("Checked previously"), dentry.path(), )); } Ok(instances) } pub fn register_branch_mapping( &mut self, branch_name: String, tenant_id: TenantId, timeline_id: TimelineId, ) -> anyhow::Result<()> { let existing_values = self .branch_name_mappings .entry(branch_name.clone()) .or_default(); let existing_ids = existing_values .iter() .find(|(existing_tenant_id, _)| existing_tenant_id == &tenant_id); if let Some((_, old_timeline_id)) = existing_ids { if old_timeline_id == &timeline_id { Ok(()) } else { bail!( "branch '{branch_name}' is already mapped to timeline {old_timeline_id}, cannot map to another timeline {timeline_id}" ); } } else { existing_values.push((tenant_id, timeline_id)); Ok(()) } } pub fn get_branch_timeline_id( &self, branch_name: &str, tenant_id: TenantId, ) -> Option<TimelineId> { self.branch_name_mappings .get(branch_name)? .iter() .find(|(mapped_tenant_id, _)| mapped_tenant_id == &tenant_id) .map(|&(_, timeline_id)| timeline_id) } pub fn timeline_name_mappings(&self) -> HashMap<TenantTimelineId, String> { self.branch_name_mappings .iter() .flat_map(|(name, tenant_timelines)| { tenant_timelines.iter().map(|&(tenant_id, timeline_id)| { (TenantTimelineId::new(tenant_id, timeline_id), name.clone()) }) }) .collect() } /// Construct `Self` from on-disk state. pub fn load_config(repopath: &Path) -> anyhow::Result<Self> { if !repopath.exists() { bail!( "Neon config is not found in {}. You need to run 'neon_local init' first", repopath.to_str().unwrap() ); } // TODO: check that it looks like a neon repository // load and parse file let config_file_contents = fs::read_to_string(repopath.join("config"))?; let on_disk_config: OnDiskConfig = toml::from_str(config_file_contents.as_str())?; let mut env = { let OnDiskConfig { pg_distrib_dir, neon_distrib_dir, default_tenant_id, private_key_path, public_key_path, broker, storage_controller, pageservers, safekeepers, control_plane_api, control_plane_hooks_api, control_plane_compute_hook_api: _, branch_name_mappings, generate_local_ssl_certs, endpoint_storage, } = on_disk_config; LocalEnv { base_data_dir: repopath.to_owned(), pg_distrib_dir, neon_distrib_dir, default_tenant_id, private_key_path, public_key_path, broker, storage_controller, pageservers, safekeepers, control_plane_api: control_plane_api.unwrap(), control_plane_hooks_api, branch_name_mappings, generate_local_ssl_certs, endpoint_storage, } }; // The source of truth for pageserver configuration is the pageserver.toml. assert!( env.pageservers.is_empty(), "we ensure this during deserialization" ); env.pageservers = { let iter = std::fs::read_dir(repopath).context("open dir")?; let mut pageservers = Vec::new(); for res in iter { let dentry = res?; const PREFIX: &str = "pageserver_"; let dentry_name = dentry .file_name() .into_string() .ok() .with_context(|| format!("non-utf8 dentry: {:?}", dentry.path())) .unwrap(); if !dentry_name.starts_with(PREFIX) { continue; } if !dentry.file_type().context("determine file type")?.is_dir() { anyhow::bail!("expected a directory, got {:?}", dentry.path()); } let id = dentry_name[PREFIX.len()..] .parse::<NodeId>() .with_context(|| format!("parse id from {:?}", dentry.path()))?; // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656) #[derive(serde::Serialize, serde::Deserialize)] // (allow unknown fields, unlike PageServerConf) struct PageserverConfigTomlSubset { listen_pg_addr: String, listen_http_addr: String, listen_https_addr: Option<String>, listen_grpc_addr: Option<String>, pg_auth_type: AuthType, http_auth_type: AuthType, grpc_auth_type: AuthType, #[serde(default)] no_sync: bool, } let config_toml_path = dentry.path().join("pageserver.toml"); let config_toml: PageserverConfigTomlSubset = toml_edit::de::from_str( &std::fs::read_to_string(&config_toml_path) .with_context(|| format!("read {config_toml_path:?}"))?, ) .context("parse pageserver.toml")?; let identity_toml_path = dentry.path().join("identity.toml"); #[derive(serde::Serialize, serde::Deserialize)] struct IdentityTomlSubset { id: NodeId, } let identity_toml: IdentityTomlSubset = toml_edit::de::from_str( &std::fs::read_to_string(&identity_toml_path) .with_context(|| format!("read {identity_toml_path:?}"))?, ) .context("parse identity.toml")?; let PageserverConfigTomlSubset { listen_pg_addr, listen_http_addr, listen_https_addr, listen_grpc_addr, pg_auth_type, http_auth_type, grpc_auth_type, no_sync, } = config_toml; let IdentityTomlSubset { id: identity_toml_id, } = identity_toml; let conf = PageServerConf { id: { anyhow::ensure!( identity_toml_id == id, "id mismatch: identity.toml:id={identity_toml_id} pageserver_(.*) id={id}", ); id }, listen_pg_addr, listen_http_addr, listen_https_addr, listen_grpc_addr, pg_auth_type, http_auth_type, grpc_auth_type, no_sync, }; pageservers.push(conf); } pageservers }; Ok(env) } pub fn persist_config(&self) -> anyhow::Result<()> { Self::persist_config_impl( &self.base_data_dir, &OnDiskConfig { pg_distrib_dir: self.pg_distrib_dir.clone(), neon_distrib_dir: self.neon_distrib_dir.clone(), default_tenant_id: self.default_tenant_id, private_key_path: self.private_key_path.clone(), public_key_path: self.public_key_path.clone(), broker: self.broker.clone(), storage_controller: self.storage_controller.clone(), pageservers: vec![], // it's skip_serializing anyway safekeepers: self.safekeepers.clone(), control_plane_api: Some(self.control_plane_api.clone()), control_plane_hooks_api: self.control_plane_hooks_api.clone(), control_plane_compute_hook_api: None, branch_name_mappings: self.branch_name_mappings.clone(), generate_local_ssl_certs: self.generate_local_ssl_certs, endpoint_storage: self.endpoint_storage.clone(), }, ) } pub fn persist_config_impl(base_path: &Path, config: &OnDiskConfig) -> anyhow::Result<()> { let conf_content = &toml::to_string_pretty(config)?; let target_config_path = base_path.join("config"); fs::write(&target_config_path, conf_content).with_context(|| { format!( "Failed to write config file into path '{}'", target_config_path.display() ) }) } // this function is used only for testing purposes in CLI e g generate tokens during init pub fn generate_auth_token<S: Serialize>(&self, claims: &S) -> anyhow::Result<String> { let key = self.read_private_key()?; encode_from_key_file(claims, &key) } /// Get the path to the private key. pub fn get_private_key_path(&self) -> PathBuf { if self.private_key_path.is_absolute() { self.private_key_path.to_path_buf() } else { self.base_data_dir.join(&self.private_key_path) } } /// Get the path to the public key. pub fn get_public_key_path(&self) -> PathBuf { if self.public_key_path.is_absolute() { self.public_key_path.to_path_buf() } else { self.base_data_dir.join(&self.public_key_path) } } /// Read the contents of the private key file. pub fn read_private_key(&self) -> anyhow::Result<Pem> { let private_key_path = self.get_private_key_path(); let pem = pem::parse(fs::read(private_key_path)?)?; Ok(pem) } /// Read the contents of the public key file. pub fn read_public_key(&self) -> anyhow::Result<Pem> { let public_key_path = self.get_public_key_path(); let pem = pem::parse(fs::read(public_key_path)?)?; Ok(pem) } /// Materialize the [`NeonLocalInitConf`] to disk. Called during [`neon_local init`]. pub fn init(conf: NeonLocalInitConf, force: &InitForceMode) -> anyhow::Result<()> { let base_path = base_path(); assert_ne!(base_path, Path::new("")); let base_path = &base_path; // create base_path dir if base_path.exists() { match force { InitForceMode::MustNotExist => { bail!( "directory '{}' already exists. Perhaps already initialized?", base_path.display() ); } InitForceMode::EmptyDirOk => { if let Some(res) = std::fs::read_dir(base_path)?.next() { res.context("check if directory is empty")?; anyhow::bail!("directory not empty: {base_path:?}"); } } InitForceMode::RemoveAllContents => { println!("removing all contents of '{}'", base_path.display()); // instead of directly calling `remove_dir_all`, we keep the original dir but removing // all contents inside. This helps if the developer symbol links another directory (i.e., // S3 local SSD) to the `.neon` base directory. for entry in std::fs::read_dir(base_path)? { let entry = entry?; let path = entry.path(); if path.is_dir() {
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/background_process.rs
control_plane/src/background_process.rs
//! Spawns and kills background processes that are needed by Neon CLI. //! Applies common set-up such as log and pid files (if needed) to every process. //! //! Neon CLI does not run in background, so it needs to store the information about //! spawned processes, which it does in this module. //! We do that by storing the pid of the process in the "${process_name}.pid" file. //! The pid file can be created by the process itself //! (Neon storage binaries do that and also ensure that a lock is taken onto that file) //! or we create such file after starting the process //! (non-Neon binaries don't necessarily follow our pidfile conventions). //! The pid stored in the file is later used to stop the service. //! //! See the [`lock_file`](utils::lock_file) module for more info. use std::ffi::OsStr; use std::io::Write; use std::os::fd::AsFd; use std::os::unix::process::CommandExt; use std::path::Path; use std::process::Command; use std::time::Duration; use std::{fs, io, thread}; use anyhow::Context; use camino::{Utf8Path, Utf8PathBuf}; use nix::errno::Errno; use nix::fcntl::{FcntlArg, FdFlag}; use nix::sys::signal::{Signal, kill}; use nix::unistd::Pid; use utils::pid_file::{self, PidFileRead}; // These constants control the loop used to poll for process start / stop. // // The loop waits for at most 10 seconds, polling every 100 ms. // Once a second, it prints a dot ("."), to give the user an indication that // it's waiting. If the process hasn't started/stopped after 5 seconds, // it prints a notice that it's taking long, but keeps waiting. // const STOP_RETRY_TIMEOUT: Duration = Duration::from_secs(10); const STOP_RETRIES: u128 = STOP_RETRY_TIMEOUT.as_millis() / RETRY_INTERVAL.as_millis(); const RETRY_INTERVAL: Duration = Duration::from_millis(100); const DOT_EVERY_RETRIES: u128 = 10; const NOTICE_AFTER_RETRIES: u128 = 50; /// Argument to `start_process`, to indicate whether it should create pidfile or if the process creates /// it itself. pub enum InitialPidFile { /// Create a pidfile, to allow future CLI invocations to manipulate the process. Create(Utf8PathBuf), /// The process will create the pidfile itself, need to wait for that event. Expect(Utf8PathBuf), } /// Start a background child process using the parameters given. #[allow(clippy::too_many_arguments)] pub async fn start_process<F, Fut, AI, A, EI>( process_name: &str, datadir: &Path, command: &Path, args: AI, envs: EI, initial_pid_file: InitialPidFile, retry_timeout: &Duration, process_status_check: F, ) -> anyhow::Result<()> where F: Fn() -> Fut, Fut: std::future::Future<Output = anyhow::Result<bool>>, AI: IntoIterator<Item = A>, A: AsRef<OsStr>, // Not generic AsRef<OsStr>, otherwise empty `envs` prevents type inference EI: IntoIterator<Item = (String, String)>, { let retries: u128 = retry_timeout.as_millis() / RETRY_INTERVAL.as_millis(); if !datadir.metadata().context("stat datadir")?.is_dir() { anyhow::bail!("`datadir` must be a directory when calling this function: {datadir:?}"); } let log_path = datadir.join(format!("{process_name}.log")); let process_log_file = fs::OpenOptions::new() .create(true) .append(true) .open(&log_path) .with_context(|| { format!("Could not open {process_name} log file {log_path:?} for writing") })?; let same_file_for_stderr = process_log_file.try_clone().with_context(|| { format!("Could not reuse {process_name} log file {log_path:?} for writing stderr") })?; let mut command = Command::new(command); let background_command = command .stdout(process_log_file) .stderr(same_file_for_stderr) .args(args) // spawn all child processes in their datadir, useful for all kinds of things, // not least cleaning up child processes e.g. after an unclean exit from the test suite: // ``` // lsof -d cwd -a +D Users/cs/src/neon/test_output // ``` .current_dir(datadir); let filled_cmd = fill_env_vars_prefixed_neon(fill_remote_storage_secrets_vars( fill_rust_env_vars(background_command), )); filled_cmd.envs(envs); let pid_file_to_check = match &initial_pid_file { InitialPidFile::Create(path) => { pre_exec_create_pidfile(filled_cmd, path); path } InitialPidFile::Expect(path) => path, }; let spawned_process = filled_cmd.spawn().with_context(|| { format!("Could not spawn {process_name}, see console output and log files for details.") })?; let pid = spawned_process.id(); let pid = Pid::from_raw( i32::try_from(pid) .with_context(|| format!("Subprocess {process_name} has invalid pid {pid}"))?, ); // set up a scopeguard to kill & wait for the child in case we panic or bail below let spawned_process = scopeguard::guard(spawned_process, |mut spawned_process| { println!("SIGKILL & wait the started process"); (|| { // TODO: use another signal that can be caught by the child so it can clean up any children it spawned (e..g, walredo). spawned_process.kill().context("SIGKILL child")?; spawned_process.wait().context("wait() for child process")?; anyhow::Ok(()) })() .with_context(|| format!("scopeguard kill&wait child {process_name:?}")) .unwrap(); }); for retries in 0..retries { match process_started(pid, pid_file_to_check, &process_status_check).await { Ok(true) => { println!("\n{process_name} started and passed status check, pid: {pid}"); // leak the child process, it'll outlive this neon_local invocation drop(scopeguard::ScopeGuard::into_inner(spawned_process)); return Ok(()); } Ok(false) => { if retries == NOTICE_AFTER_RETRIES { // The process is taking a long time to start up. Keep waiting, but // print a message print!("\n{process_name} has not started yet, continuing to wait"); } if retries % DOT_EVERY_RETRIES == 0 { print!("."); io::stdout().flush().unwrap(); } tokio::time::sleep(RETRY_INTERVAL).await; } Err(e) => { println!("error starting process {process_name:?}: {e:#}"); return Err(e); } } } println!(); anyhow::bail!(format!( "{} did not start+pass status checks within {:?} seconds", process_name, retry_timeout )); } /// Stops the process, using the pid file given. Returns Ok also if the process is already not running. pub fn stop_process( immediate: bool, process_name: &str, pid_file: &Utf8Path, ) -> anyhow::Result<()> { let pid = match pid_file::read(pid_file) .with_context(|| format!("read pid_file {pid_file:?}"))? { PidFileRead::NotExist => { println!("{process_name} is already stopped: no pid file present at {pid_file:?}"); return Ok(()); } PidFileRead::NotHeldByAnyProcess(_) => { // Don't try to kill according to file contents beacuse the pid might have been re-used by another process. // Don't delete the file either, it can race with new pid file creation. // Read `pid_file` module comment for details. println!( "No process is holding the pidfile. The process must have already exited. Leave in place to avoid race conditions: {pid_file:?}" ); return Ok(()); } PidFileRead::LockedByOtherProcess(pid) => pid, }; // XXX the pid could become invalid (and recycled) at any time before the kill() below. // send signal let sig = if immediate { print!("Stopping {process_name} with pid {pid} immediately.."); Signal::SIGQUIT } else { print!("Stopping {process_name} with pid {pid} gracefully.."); Signal::SIGTERM }; io::stdout().flush().unwrap(); match kill(pid, sig) { Ok(()) => (), Err(Errno::ESRCH) => { // Again, don't delete the pid file. The unlink can race with a new pid file being created. println!( "{process_name} with pid {pid} does not exist, but a pid file {pid_file:?} was found. Likely the pid got recycled. Lucky we didn't harm anyone." ); return Ok(()); } Err(e) => anyhow::bail!("Failed to send signal to {process_name} with pid {pid}: {e}"), } // Wait until process is gone wait_until_stopped(process_name, pid)?; Ok(()) } pub fn wait_until_stopped(process_name: &str, pid: Pid) -> anyhow::Result<()> { for retries in 0..STOP_RETRIES { match process_has_stopped(pid) { Ok(true) => { println!("\n{process_name} stopped"); return Ok(()); } Ok(false) => { if retries == NOTICE_AFTER_RETRIES { // The process is taking a long time to start up. Keep waiting, but // print a message print!("\n{process_name} has not stopped yet, continuing to wait"); } if retries % DOT_EVERY_RETRIES == 0 { print!("."); io::stdout().flush().unwrap(); } thread::sleep(RETRY_INTERVAL); } Err(e) => { println!("{process_name} with pid {pid} failed to stop: {e:#}"); return Err(e); } } } println!(); anyhow::bail!(format!( "{} with pid {} did not stop in {:?} seconds", process_name, pid, STOP_RETRY_TIMEOUT )); } fn fill_rust_env_vars(cmd: &mut Command) -> &mut Command { // If RUST_BACKTRACE is set, pass it through. But if it's not set, default // to RUST_BACKTRACE=1. let backtrace_setting = std::env::var_os("RUST_BACKTRACE"); let backtrace_setting = backtrace_setting .as_deref() .unwrap_or_else(|| OsStr::new("1")); let mut filled_cmd = cmd.env_clear().env("RUST_BACKTRACE", backtrace_setting); // Pass through these environment variables to the command for var in [ "LLVM_PROFILE_FILE", "FAILPOINTS", "RUST_LOG", "ASAN_OPTIONS", "UBSAN_OPTIONS", ] { if let Some(val) = std::env::var_os(var) { filled_cmd = filled_cmd.env(var, val); } } filled_cmd } fn fill_remote_storage_secrets_vars(mut cmd: &mut Command) -> &mut Command { for env_key in [ "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", // HOME is needed in combination with `AWS_PROFILE` to pick up the SSO sessions. "HOME", "AZURE_STORAGE_ACCOUNT", "AZURE_STORAGE_ACCESS_KEY", ] { if let Ok(value) = std::env::var(env_key) { cmd = cmd.env(env_key, value); } } cmd } fn fill_env_vars_prefixed_neon(mut cmd: &mut Command) -> &mut Command { for (var, val) in std::env::vars() { if var.starts_with("NEON_") { cmd = cmd.env(var, val); } } cmd } /// Add a `pre_exec` to the cmd that, inbetween fork() and exec(), /// 1. Claims a pidfile with a fcntl lock on it and /// 2. Sets up the pidfile's file descriptor so that it (and the lock) /// will remain held until the cmd exits. fn pre_exec_create_pidfile<P>(cmd: &mut Command, path: P) -> &mut Command where P: Into<Utf8PathBuf>, { let path: Utf8PathBuf = path.into(); // SAFETY: // pre_exec is marked unsafe because it runs between fork and exec. // Why is that dangerous in various ways? // Long answer: https://github.com/rust-lang/rust/issues/39575 // Short answer: in a multi-threaded program, other threads may have // been inside of critical sections at the time of fork. In the // original process, that was allright, assuming they protected // the critical sections appropriately, e.g., through locks. // Fork adds another process to the mix that // 1. Has a single thread T // 2. In an exact copy of the address space at the time of fork. // A variety of problems scan occur now: // 1. T tries to grab a lock that was locked at the time of fork. // It will wait forever since in its address space, the lock // is in state 'taken' but the thread that would unlock it is // not there. // 2. A rust object that represented some external resource in the // parent now got implicitly copied by the fork, even though // the object's type is not `Copy`. The parent program may use // non-copyability as way to enforce unique ownership of an // external resource in the typesystem. The fork breaks that // assumption, as now both parent and child process have an // owned instance of the object that represents the same // underlying resource. // While these seem like niche problems, (1) in particular is // highly relevant. For example, `malloc()` may grab a mutex internally, // and so, if we forked while another thread was mallocing' and our // pre_exec closure allocates as well, it will block on the malloc // mutex forever // // The proper solution is to only use C library functions that are marked // "async-signal-safe": https://man7.org/linux/man-pages/man7/signal-safety.7.html // // With this specific pre_exec() closure, the non-error path doesn't allocate. // The error path uses `anyhow`, and hence does allocate. // We take our chances there, hoping that any potential disaster is constrained // to the child process (e.g., malloc has no state ourside of the child process). // Last, `expect` prints to stderr, and stdio is not async-signal-safe. // Again, we take our chances, making the same assumptions as for malloc. unsafe { cmd.pre_exec(move || { let file = pid_file::claim_for_current_process(&path).expect("claim pid file"); // Remove the FD_CLOEXEC flag on the pidfile descriptor so that the pidfile // remains locked after exec. nix::fcntl::fcntl(file.as_fd(), FcntlArg::F_SETFD(FdFlag::empty())) .expect("remove FD_CLOEXEC"); // Don't run drop(file), it would close the file before we actually exec. std::mem::forget(file); Ok(()) }); } cmd } async fn process_started<F, Fut>( pid: Pid, pid_file_to_check: &Utf8Path, status_check: &F, ) -> anyhow::Result<bool> where F: Fn() -> Fut, Fut: std::future::Future<Output = anyhow::Result<bool>>, { match status_check().await { Ok(true) => match pid_file::read(pid_file_to_check)? { PidFileRead::NotExist => Ok(false), PidFileRead::LockedByOtherProcess(pid_in_file) => Ok(pid_in_file == pid), PidFileRead::NotHeldByAnyProcess(_) => Ok(false), }, Ok(false) => Ok(false), Err(e) => anyhow::bail!("process failed to start: {e}"), } } pub(crate) fn process_has_stopped(pid: Pid) -> anyhow::Result<bool> { match kill(pid, None) { // Process exists, keep waiting Ok(_) => Ok(false), // Process not found, we're done Err(Errno::ESRCH) => Ok(true), Err(err) => anyhow::bail!("Failed to send signal to process with pid {pid}: {err}"), } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/storage_controller.rs
control_plane/src/storage_controller.rs
use std::ffi::OsStr; use std::fs; use std::path::PathBuf; use std::process::ExitStatus; use std::str::FromStr; use std::sync::OnceLock; use std::time::{Duration, Instant}; use crate::background_process; use crate::local_env::{LocalEnv, NeonStorageControllerConf}; use camino::{Utf8Path, Utf8PathBuf}; use hyper0::Uri; use nix::unistd::Pid; use pageserver_api::controller_api::{ NodeConfigureRequest, NodeDescribeResponse, NodeRegisterRequest, SafekeeperSchedulingPolicyRequest, SkSchedulingPolicy, TenantCreateRequest, TenantCreateResponse, TenantLocateResponse, }; use pageserver_api::models::{ TenantConfig, TenantConfigRequest, TimelineCreateRequest, TimelineInfo, }; use pageserver_api::shard::TenantShardId; use pageserver_client::mgmt_api::ResponseErrorMessageExt; use pem::Pem; use postgres_backend::AuthType; use reqwest::{Method, Response}; use safekeeper_api::PgMajorVersion; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tokio::process::Command; use tracing::instrument; use url::Url; use utils::auth::{Claims, Scope, encode_from_key_file}; use utils::id::{NodeId, TenantId}; use whoami::username; pub struct StorageController { env: LocalEnv, private_key: Option<Pem>, public_key: Option<Pem>, client: reqwest::Client, config: NeonStorageControllerConf, // The listen port is learned when starting the storage controller, // hence the use of OnceLock to init it at the right time. listen_port: OnceLock<u16>, } const COMMAND: &str = "storage_controller"; const STORAGE_CONTROLLER_POSTGRES_VERSION: PgMajorVersion = PgMajorVersion::PG16; const DB_NAME: &str = "storage_controller"; pub struct NeonStorageControllerStartArgs { pub instance_id: u8, pub base_port: Option<u16>, pub start_timeout: humantime::Duration, pub handle_ps_local_disk_loss: Option<bool>, } impl NeonStorageControllerStartArgs { pub fn with_default_instance_id(start_timeout: humantime::Duration) -> Self { Self { instance_id: 1, base_port: None, start_timeout, handle_ps_local_disk_loss: None, } } } pub struct NeonStorageControllerStopArgs { pub instance_id: u8, pub immediate: bool, } impl NeonStorageControllerStopArgs { pub fn with_default_instance_id(immediate: bool) -> Self { Self { instance_id: 1, immediate, } } } #[derive(Serialize, Deserialize)] pub struct AttachHookRequest { pub tenant_shard_id: TenantShardId, pub node_id: Option<NodeId>, pub generation_override: Option<i32>, // only new tenants pub config: Option<TenantConfig>, // only new tenants } #[derive(Serialize, Deserialize)] pub struct AttachHookResponse { #[serde(rename = "gen")] pub generation: Option<u32>, } #[derive(Serialize, Deserialize)] pub struct InspectRequest { pub tenant_shard_id: TenantShardId, } #[derive(Serialize, Deserialize)] pub struct InspectResponse { pub attachment: Option<(u32, NodeId)>, } impl StorageController { pub fn from_env(env: &LocalEnv) -> Self { // Assume all pageservers have symmetric auth configuration: this service // expects to use one JWT token to talk to all of them. let ps_conf = env .pageservers .first() .expect("Config is validated to contain at least one pageserver"); let (private_key, public_key) = match ps_conf.http_auth_type { AuthType::Trust => (None, None), AuthType::NeonJWT => { let private_key_path = env.get_private_key_path(); let private_key = pem::parse(fs::read(private_key_path).expect("failed to read private key")) .expect("failed to parse PEM file"); // If pageserver auth is enabled, this implicitly enables auth for this service, // using the same credentials. let public_key_path = camino::Utf8PathBuf::try_from(env.base_data_dir.join("auth_public_key.pem")) .unwrap(); // This service takes keys as a string rather than as a path to a file/dir: read the key into memory. let public_key = if std::fs::metadata(&public_key_path) .expect("Can't stat public key") .is_dir() { // Our config may specify a directory: this is for the pageserver's ability to handle multiple // keys. We only use one key at a time, so, arbitrarily load the first one in the directory. let mut dir = std::fs::read_dir(&public_key_path).expect("Can't readdir public key path"); let dent = dir .next() .expect("Empty key dir") .expect("Error reading key dir"); pem::parse(std::fs::read_to_string(dent.path()).expect("Can't read public key")) .expect("Failed to parse PEM file") } else { pem::parse( std::fs::read_to_string(&public_key_path).expect("Can't read public key"), ) .expect("Failed to parse PEM file") }; (Some(private_key), Some(public_key)) } }; Self { env: env.clone(), private_key, public_key, client: env.create_http_client(), config: env.storage_controller.clone(), listen_port: OnceLock::default(), } } fn storage_controller_instance_dir(&self, instance_id: u8) -> PathBuf { self.env .base_data_dir .join(format!("storage_controller_{instance_id}")) } fn pid_file(&self, instance_id: u8) -> Utf8PathBuf { Utf8PathBuf::from_path_buf( self.storage_controller_instance_dir(instance_id) .join("storage_controller.pid"), ) .expect("non-Unicode path") } /// Find the directory containing postgres subdirectories, such `bin` and `lib` /// /// This usually uses STORAGE_CONTROLLER_POSTGRES_VERSION of postgres, but will fall back /// to other versions if that one isn't found. Some automated tests create circumstances /// where only one version is available in pg_distrib_dir, such as `test_remote_extensions`. async fn get_pg_dir(&self, dir_name: &str) -> anyhow::Result<Utf8PathBuf> { const PREFER_VERSIONS: [PgMajorVersion; 5] = [ STORAGE_CONTROLLER_POSTGRES_VERSION, PgMajorVersion::PG16, PgMajorVersion::PG15, PgMajorVersion::PG14, PgMajorVersion::PG17, ]; for v in PREFER_VERSIONS { let path = Utf8PathBuf::from_path_buf(self.env.pg_dir(v, dir_name)?).unwrap(); if tokio::fs::try_exists(&path).await? { return Ok(path); } } // Fall through anyhow::bail!( "Postgres directory '{}' not found in {}", dir_name, self.env.pg_distrib_dir.display(), ); } pub async fn get_pg_bin_dir(&self) -> anyhow::Result<Utf8PathBuf> { self.get_pg_dir("bin").await } pub async fn get_pg_lib_dir(&self) -> anyhow::Result<Utf8PathBuf> { self.get_pg_dir("lib").await } /// Readiness check for our postgres process async fn pg_isready(&self, pg_bin_dir: &Utf8Path, postgres_port: u16) -> anyhow::Result<bool> { let bin_path = pg_bin_dir.join("pg_isready"); let args = [ "-h", "localhost", "-U", &username(), "-d", DB_NAME, "-p", &format!("{postgres_port}"), ]; let pg_lib_dir = self.get_pg_lib_dir().await.unwrap(); let envs = [ ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ]; let exitcode = Command::new(bin_path) .args(args) .envs(envs) .spawn()? .wait() .await?; Ok(exitcode.success()) } /// Create our database if it doesn't exist /// /// This function is equivalent to the `diesel setup` command in the diesel CLI. We implement /// the same steps by hand to avoid imposing a dependency on installing diesel-cli for developers /// who just want to run `cargo neon_local` without knowing about diesel. /// /// Returns the database url pub async fn setup_database(&self, postgres_port: u16) -> anyhow::Result<String> { let database_url = format!( "postgresql://{}@localhost:{}/{DB_NAME}", &username(), postgres_port ); let pg_bin_dir = self.get_pg_bin_dir().await?; let createdb_path = pg_bin_dir.join("createdb"); let pg_lib_dir = self.get_pg_lib_dir().await.unwrap(); let envs = [ ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ]; let output = Command::new(&createdb_path) .args([ "-h", "localhost", "-p", &format!("{postgres_port}"), "-U", &username(), "-O", &username(), DB_NAME, ]) .envs(envs) .output() .await .expect("Failed to spawn createdb"); if !output.status.success() { let stderr = String::from_utf8(output.stderr).expect("Non-UTF8 output from createdb"); if stderr.contains("already exists") { tracing::info!("Database {DB_NAME} already exists"); } else { anyhow::bail!("createdb failed with status {}: {stderr}", output.status); } } Ok(database_url) } pub async fn connect_to_database( &self, postgres_port: u16, ) -> anyhow::Result<( tokio_postgres::Client, tokio_postgres::Connection<tokio_postgres::Socket, tokio_postgres::tls::NoTlsStream>, )> { tokio_postgres::Config::new() .host("localhost") .port(postgres_port) // The user is the ambient operating system user name. // That is an impurity which we want to fix in => TODO https://github.com/neondatabase/neon/issues/8400 // // Until we get there, use the ambient operating system user name. // Recent tokio-postgres versions default to this if the user isn't specified. // But tokio-postgres fork doesn't have this upstream commit: // https://github.com/sfackler/rust-postgres/commit/cb609be758f3fb5af537f04b584a2ee0cebd5e79 // => we should rebase our fork => TODO https://github.com/neondatabase/neon/issues/8399 .user(&username()) .dbname(DB_NAME) .connect(tokio_postgres::NoTls) .await .map_err(anyhow::Error::new) } /// Wrapper for the pg_ctl binary, which we spawn as a short-lived subprocess when starting and stopping postgres async fn pg_ctl<I, S>(&self, args: I) -> ExitStatus where I: IntoIterator<Item = S>, S: AsRef<OsStr>, { let pg_bin_dir = self.get_pg_bin_dir().await.unwrap(); let bin_path = pg_bin_dir.join("pg_ctl"); let pg_lib_dir = self.get_pg_lib_dir().await.unwrap(); let envs = [ ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ]; Command::new(bin_path) .args(args) .envs(envs) .spawn() .expect("Failed to spawn pg_ctl, binary_missing?") .wait() .await .expect("Failed to wait for pg_ctl termination") } pub async fn start(&self, start_args: NeonStorageControllerStartArgs) -> anyhow::Result<()> { let instance_dir = self.storage_controller_instance_dir(start_args.instance_id); if let Err(err) = tokio::fs::create_dir(&instance_dir).await { if err.kind() != std::io::ErrorKind::AlreadyExists { panic!("Failed to create instance dir {instance_dir:?}"); } } if self.env.generate_local_ssl_certs { self.env.generate_ssl_cert( &instance_dir.join("server.crt"), &instance_dir.join("server.key"), )?; } let listen_url = &self.env.control_plane_api; let scheme = listen_url.scheme(); let host = listen_url.host_str().unwrap(); let (listen_port, postgres_port) = if let Some(base_port) = start_args.base_port { ( base_port, self.config .database_url .expect("--base-port requires NeonStorageControllerConf::database_url") .port(), ) } else { let port = listen_url.port().unwrap(); (port, port + 1) }; self.listen_port .set(listen_port) .expect("StorageController::listen_port is only set here"); // Do we remove the pid file on stop? let pg_started = self.is_postgres_running().await?; let pg_lib_dir = self.get_pg_lib_dir().await?; if !pg_started { // Start a vanilla Postgres process used by the storage controller for persistence. let pg_data_path = Utf8PathBuf::from_path_buf(self.env.base_data_dir.clone()) .unwrap() .join("storage_controller_db"); let pg_bin_dir = self.get_pg_bin_dir().await?; let pg_log_path = pg_data_path.join("postgres.log"); if !tokio::fs::try_exists(&pg_data_path).await? { let initdb_args = [ "--pgdata", pg_data_path.as_ref(), "--username", &username(), "--no-sync", "--no-instructions", ]; tracing::info!( "Initializing storage controller database with args: {:?}", initdb_args ); // Initialize empty database let initdb_path = pg_bin_dir.join("initdb"); let mut child = Command::new(&initdb_path) .envs(vec![ ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ]) .args(initdb_args) .spawn() .expect("Failed to spawn initdb"); let status = child.wait().await?; if !status.success() { anyhow::bail!("initdb failed with status {status}"); } }; // Write a minimal config file: // - Specify the port, since this is chosen dynamically // - Switch off fsync, since we're running on lightweight test environments and when e.g. scale testing // the storage controller we don't want a slow local disk to interfere with that. // // NB: it's important that we rewrite this file on each start command so we propagate changes // from `LocalEnv`'s config file (`.neon/config`). tokio::fs::write( &pg_data_path.join("postgresql.conf"), format!("port = {postgres_port}\nfsync=off\n"), ) .await?; println!("Starting storage controller database..."); let db_start_args = [ "-w", "-D", pg_data_path.as_ref(), "-l", pg_log_path.as_ref(), "-U", &username(), "start", ]; tracing::info!( "Starting storage controller database with args: {:?}", db_start_args ); let db_start_status = self.pg_ctl(db_start_args).await; let start_timeout: Duration = start_args.start_timeout.into(); let db_start_deadline = Instant::now() + start_timeout; if !db_start_status.success() { return Err(anyhow::anyhow!( "Failed to start postgres {}", db_start_status.code().unwrap() )); } loop { if Instant::now() > db_start_deadline { return Err(anyhow::anyhow!("Timed out waiting for postgres to start")); } match self.pg_isready(&pg_bin_dir, postgres_port).await { Ok(true) => { tracing::info!("storage controller postgres is now ready"); break; } Ok(false) => { tokio::time::sleep(Duration::from_millis(100)).await; } Err(e) => { tracing::warn!("Failed to check postgres status: {e}") } } } self.setup_database(postgres_port).await?; } let database_url = format!("postgresql://localhost:{postgres_port}/{DB_NAME}"); // We support running a startup SQL script to fiddle with the database before we launch storcon. // This is used by the test suite. let startup_script_path = self .env .base_data_dir .join("storage_controller_db.startup.sql"); let startup_script = match tokio::fs::read_to_string(&startup_script_path).await { Ok(script) => { tokio::fs::remove_file(startup_script_path).await?; script } Err(e) => { if e.kind() == std::io::ErrorKind::NotFound { // always run some startup script so that this code path doesn't bit rot "BEGIN; COMMIT;".to_string() } else { anyhow::bail!("Failed to read startup script: {e}") } } }; let (mut client, conn) = self.connect_to_database(postgres_port).await?; let conn = tokio::spawn(conn); let tx = client.build_transaction(); let tx = tx.start().await?; tx.batch_execute(&startup_script).await?; tx.commit().await?; drop(client); conn.await??; let addr = format!("{host}:{listen_port}"); let address_for_peers = Uri::builder() .scheme(scheme) .authority(addr.clone()) .path_and_query("") .build() .unwrap(); let mut args = vec![ "--dev", "--database-url", &database_url, "--max-offline-interval", &humantime::Duration::from(self.config.max_offline).to_string(), "--max-warming-up-interval", &humantime::Duration::from(self.config.max_warming_up).to_string(), "--heartbeat-interval", &humantime::Duration::from(self.config.heartbeat_interval).to_string(), "--address-for-peers", &address_for_peers.to_string(), ] .into_iter() .map(|s| s.to_string()) .collect::<Vec<_>>(); match scheme { "http" => args.extend(["--listen".to_string(), addr]), "https" => args.extend(["--listen-https".to_string(), addr]), _ => { panic!("Unexpected url scheme in control_plane_api: {scheme}"); } } if self.config.start_as_candidate { args.push("--start-as-candidate".to_string()); } if self.config.use_https_pageserver_api { args.push("--use-https-pageserver-api".to_string()); } if self.config.use_https_safekeeper_api { args.push("--use-https-safekeeper-api".to_string()); } if self.config.use_local_compute_notifications { args.push("--use-local-compute-notifications".to_string()); } if let Some(value) = self.config.kick_secondary_downloads { args.push(format!("--kick-secondary-downloads={value}")); } if let Some(ssl_ca_file) = self.env.ssl_ca_cert_path() { args.push(format!("--ssl-ca-file={}", ssl_ca_file.to_str().unwrap())); } if let Some(private_key) = &self.private_key { let claims = Claims::new(None, Scope::PageServerApi); let jwt_token = encode_from_key_file(&claims, private_key).expect("failed to generate jwt token"); args.push(format!("--jwt-token={jwt_token}")); let peer_claims = Claims::new(None, Scope::Admin); let peer_jwt_token = encode_from_key_file(&peer_claims, private_key) .expect("failed to generate jwt token"); args.push(format!("--peer-jwt-token={peer_jwt_token}")); let claims = Claims::new(None, Scope::SafekeeperData); let jwt_token = encode_from_key_file(&claims, private_key).expect("failed to generate jwt token"); args.push(format!("--safekeeper-jwt-token={jwt_token}")); } if let Some(public_key) = &self.public_key { args.push(format!("--public-key=\"{public_key}\"")); } if let Some(control_plane_hooks_api) = &self.env.control_plane_hooks_api { args.push(format!("--control-plane-url={control_plane_hooks_api}")); } if let Some(split_threshold) = self.config.split_threshold.as_ref() { args.push(format!("--split-threshold={split_threshold}")) } if let Some(max_split_shards) = self.config.max_split_shards.as_ref() { args.push(format!("--max-split-shards={max_split_shards}")) } if let Some(initial_split_threshold) = self.config.initial_split_threshold.as_ref() { args.push(format!( "--initial-split-threshold={initial_split_threshold}" )) } if let Some(initial_split_shards) = self.config.initial_split_shards.as_ref() { args.push(format!("--initial-split-shards={initial_split_shards}")) } if let Some(lag) = self.config.max_secondary_lag_bytes.as_ref() { args.push(format!("--max-secondary-lag-bytes={lag}")) } if let Some(threshold) = self.config.long_reconcile_threshold { args.push(format!( "--long-reconcile-threshold={}", humantime::Duration::from(threshold) )) } args.push(format!( "--neon-local-repo-dir={}", self.env.base_data_dir.display() )); if self.env.safekeepers.iter().any(|sk| sk.auth_enabled) && self.private_key.is_none() { anyhow::bail!("Safekeeper set up for auth but no private key specified"); } if self.config.timelines_onto_safekeepers { args.push("--timelines-onto-safekeepers".to_string()); } // neon_local is used in test environments where we often have less than 3 safekeepers. if self.config.timeline_safekeeper_count.is_some() || self.env.safekeepers.len() < 3 { let sk_cnt = self .config .timeline_safekeeper_count .unwrap_or(self.env.safekeepers.len()); args.push(format!("--timeline-safekeeper-count={sk_cnt}")); } if let Some(duration) = self.config.shard_split_request_timeout { args.push(format!( "--shard-split-request-timeout={}", humantime::Duration::from(duration) )); } let mut envs = vec![ ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()), ]; if let Some(posthog_config) = &self.config.posthog_config { envs.push(( "POSTHOG_CONFIG".to_string(), serde_json::to_string(posthog_config)?, )); } println!("Starting storage controller at {scheme}://{host}:{listen_port}"); if start_args.handle_ps_local_disk_loss.unwrap_or_default() { args.push("--handle-ps-local-disk-loss".to_string()); } background_process::start_process( COMMAND, &instance_dir, &self.env.storage_controller_bin(), args, envs, background_process::InitialPidFile::Create(self.pid_file(start_args.instance_id)), &start_args.start_timeout, || async { match self.ready().await { Ok(_) => Ok(true), Err(_) => Ok(false), } }, ) .await?; if self.config.timelines_onto_safekeepers { self.register_safekeepers().await?; } Ok(()) } pub async fn stop(&self, stop_args: NeonStorageControllerStopArgs) -> anyhow::Result<()> { background_process::stop_process( stop_args.immediate, COMMAND, &self.pid_file(stop_args.instance_id), )?; let storcon_instances = self.env.storage_controller_instances().await?; for (instance_id, instanced_dir_path) in storcon_instances { if instance_id == stop_args.instance_id { continue; } let pid_file = instanced_dir_path.join("storage_controller.pid"); let pid = tokio::fs::read_to_string(&pid_file) .await .map_err(|err| { anyhow::anyhow!("Failed to read storcon pid file at {pid_file:?}: {err}") })? .parse::<i32>() .expect("pid is valid i32"); let other_proc_alive = !background_process::process_has_stopped(Pid::from_raw(pid))?; if other_proc_alive { // There is another storage controller instance running, so we return // and leave the database running. return Ok(()); } } let pg_data_path = self.env.base_data_dir.join("storage_controller_db"); println!("Stopping storage controller database..."); let pg_stop_args = ["-D", &pg_data_path.to_string_lossy(), "stop"]; let stop_status = self.pg_ctl(pg_stop_args).await; if !stop_status.success() { match self.is_postgres_running().await { Ok(false) => { println!("Storage controller database is already stopped"); return Ok(()); } Ok(true) => { anyhow::bail!("Failed to stop storage controller database"); } Err(err) => { anyhow::bail!("Failed to stop storage controller database: {err}"); } } } Ok(()) } async fn is_postgres_running(&self) -> anyhow::Result<bool> { let pg_data_path = self.env.base_data_dir.join("storage_controller_db"); let pg_status_args = ["-D", &pg_data_path.to_string_lossy(), "status"]; let status_exitcode = self.pg_ctl(pg_status_args).await; // pg_ctl status returns this exit code if postgres is not running: in this case it is // fine that stop failed. Otherwise it is an error that stop failed. const PG_STATUS_NOT_RUNNING: i32 = 3; const PG_NO_DATA_DIR: i32 = 4; const PG_STATUS_RUNNING: i32 = 0; match status_exitcode.code() { Some(PG_STATUS_NOT_RUNNING) => Ok(false), Some(PG_NO_DATA_DIR) => Ok(false), Some(PG_STATUS_RUNNING) => Ok(true), Some(code) => Err(anyhow::anyhow!( "pg_ctl status returned unexpected status code: {:?}", code )), None => Err(anyhow::anyhow!("pg_ctl status returned no status code")), } } fn get_claims_for_path(path: &str) -> anyhow::Result<Option<Claims>> { let category = match path.find('/') { Some(idx) => &path[..idx], None => path, }; match category { "status" | "ready" => Ok(None), "control" | "debug" => Ok(Some(Claims::new(None, Scope::Admin))), "v1" => Ok(Some(Claims::new(None, Scope::PageServerApi))), _ => Err(anyhow::anyhow!("Failed to determine claims for {}", path)), } } /// Simple HTTP request wrapper for calling into storage controller async fn dispatch<RQ, RS>( &self, method: reqwest::Method, path: String, body: Option<RQ>, ) -> anyhow::Result<RS> where RQ: Serialize + Sized, RS: DeserializeOwned + Sized, { let response = self.dispatch_inner(method, path, body).await?; Ok(response .json() .await .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)?) } /// Simple HTTP request wrapper for calling into storage controller async fn dispatch_inner<RQ>( &self, method: reqwest::Method, path: String, body: Option<RQ>, ) -> anyhow::Result<Response> where RQ: Serialize + Sized, { // In the special case of the `storage_controller start` subcommand, we wish // to use the API endpoint of the newly started storage controller in order // to pass the readiness check. In this scenario [`Self::listen_port`] will // be set (see [`Self::start`]). // // Otherwise, we infer the storage controller api endpoint from the configured // control plane API. let port = if let Some(port) = self.listen_port.get() { *port } else { self.env.control_plane_api.port().unwrap() }; // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out // for general purpose API access. let url = Url::from_str(&format!( "{}://{}:{port}/{path}", self.env.control_plane_api.scheme(), self.env.control_plane_api.host_str().unwrap(), )) .unwrap(); let mut builder = self.client.request(method, url); if let Some(body) = body { builder = builder.json(&body) } if let Some(private_key) = &self.private_key { println!("Getting claims for path {path}"); if let Some(required_claims) = Self::get_claims_for_path(&path)? { println!("Got claims {required_claims:?} for path {path}"); let jwt_token = encode_from_key_file(&required_claims, private_key)?; builder = builder.header( reqwest::header::AUTHORIZATION, format!("Bearer {jwt_token}"), ); } } let response = builder.send().await?; let response = response.error_from_body().await?; Ok(response) } /// Register the safekeepers in the storage controller #[instrument(skip(self))] async fn register_safekeepers(&self) -> anyhow::Result<()> { for sk in self.env.safekeepers.iter() { let sk_id = sk.id; let body = serde_json::json!({ "id": sk_id, "created_at": "2023-10-25T09:11:25Z", "updated_at": "2024-08-28T11:32:43Z", "region_id": "aws-us-east-2", "host": "127.0.0.1", "port": sk.pg_port, "http_port": sk.http_port, "https_port": sk.https_port, "version": 5957, "availability_zone_id": format!("us-east-2b-{sk_id}"), }); self.upsert_safekeeper(sk_id, body).await?; self.safekeeper_scheduling_policy(sk_id, SkSchedulingPolicy::Active)
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/broker.rs
control_plane/src/broker.rs
//! Code to manage the storage broker //! //! In the local test environment, the storage broker stores its data directly in //! //! ```text //! .neon/storage_broker //! ``` use std::time::Duration; use anyhow::Context; use camino::Utf8PathBuf; use crate::{background_process, local_env::LocalEnv}; pub struct StorageBroker { env: LocalEnv, } impl StorageBroker { /// Create a new `StorageBroker` instance from the environment. pub fn from_env(env: &LocalEnv) -> Self { Self { env: env.clone() } } pub fn initialize(&self) -> anyhow::Result<()> { if self.env.generate_local_ssl_certs { self.env.generate_ssl_cert( &self.env.storage_broker_data_dir().join("server.crt"), &self.env.storage_broker_data_dir().join("server.key"), )?; } Ok(()) } /// Start the storage broker process. pub async fn start(&self, retry_timeout: &Duration) -> anyhow::Result<()> { let broker = &self.env.broker; println!("Starting neon broker at {}", broker.client_url()); let mut args = Vec::new(); if let Some(addr) = &broker.listen_addr { args.push(format!("--listen-addr={addr}")); } if let Some(addr) = &broker.listen_https_addr { args.push(format!("--listen-https-addr={addr}")); } let client = self.env.create_http_client(); background_process::start_process( "storage_broker", &self.env.storage_broker_data_dir(), &self.env.storage_broker_bin(), args, [], background_process::InitialPidFile::Create(self.pid_file_path()), retry_timeout, || async { let url = broker.client_url(); let status_url = url.join("status").with_context(|| { format!("Failed to append /status path to broker endpoint {url}") })?; let request = client.get(status_url).build().with_context(|| { format!("Failed to construct request to broker endpoint {url}") })?; match client.execute(request).await { Ok(resp) => Ok(resp.status().is_success()), Err(_) => Ok(false), } }, ) .await .context("Failed to spawn storage_broker subprocess")?; Ok(()) } /// Stop the storage broker process. pub fn stop(&self) -> anyhow::Result<()> { background_process::stop_process(true, "storage_broker", &self.pid_file_path()) } /// Get the path to the PID file for the storage broker. fn pid_file_path(&self) -> Utf8PathBuf { Utf8PathBuf::from_path_buf(self.env.base_data_dir.join("storage_broker.pid")) .expect("non-Unicode path") } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/endpoint.rs
control_plane/src/endpoint.rs
//! Code to manage compute endpoints //! //! In the local test environment, the data for each endpoint is stored in //! //! ```text //! .neon/endpoints/<endpoint id> //! ``` //! //! Some basic information about the endpoint, like the tenant and timeline IDs, //! are stored in the `endpoint.json` file. The `endpoint.json` file is created //! when the endpoint is created, and doesn't change afterwards. //! //! The endpoint is managed by the `compute_ctl` binary. When an endpoint is //! started, we launch `compute_ctl` It synchronizes the safekeepers, downloads //! the basebackup from the pageserver to initialize the data directory, and //! finally launches the PostgreSQL process. It watches the PostgreSQL process //! until it exits. //! //! When an endpoint is created, a `postgresql.conf` file is also created in //! the endpoint's directory. The file can be modified before starting PostgreSQL. //! However, the `postgresql.conf` file in the endpoint directory is not used directly //! by PostgreSQL. It is passed to `compute_ctl`, and `compute_ctl` writes another //! copy of it in the data directory. //! //! Directory contents: //! //! ```text //! .neon/endpoints/main/ //! compute.log - log output of `compute_ctl` and `postgres` //! endpoint.json - serialized `EndpointConf` struct //! postgresql.conf - postgresql settings //! config.json - passed to `compute_ctl` //! pgdata/ //! postgresql.conf - copy of postgresql.conf created by `compute_ctl` //! neon.signal //! zenith.signal - copy of neon.signal, for backward compatibility //! <other PostgreSQL files> //! ``` //! use std::collections::{BTreeMap, HashMap}; use std::fmt::Display; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream}; use std::path::PathBuf; use std::process::Command; use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, Instant}; use anyhow::{Context, Result, anyhow, bail}; use base64::Engine; use base64::prelude::BASE64_URL_SAFE_NO_PAD; use compute_api::requests::{ COMPUTE_AUDIENCE, ComputeClaims, ComputeClaimsScope, ConfigurationRequest, }; use compute_api::responses::{ ComputeConfig, ComputeCtlConfig, ComputeStatus, ComputeStatusResponse, TerminateResponse, TlsConfig, }; use compute_api::spec::{ Cluster, ComputeAudit, ComputeFeature, ComputeMode, ComputeSpec, Database, PageserverProtocol, PageserverShardInfo, PgIdent, RemoteExtSpec, Role, }; // re-export these, because they're used in the reconfigure() function pub use compute_api::spec::{PageserverConnectionInfo, PageserverShardConnectionInfo}; use jsonwebtoken::jwk::{ AlgorithmParameters, CommonParameters, EllipticCurve, Jwk, JwkSet, KeyAlgorithm, KeyOperations, OctetKeyPairParameters, OctetKeyPairType, PublicKeyUse, }; use nix::sys::signal::{Signal, kill}; use pem::Pem; use reqwest::header::CONTENT_TYPE; use safekeeper_api::PgMajorVersion; use safekeeper_api::membership::SafekeeperGeneration; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use spki::der::Decode; use spki::{SubjectPublicKeyInfo, SubjectPublicKeyInfoRef}; use tracing::debug; use utils::id::{NodeId, TenantId, TimelineId}; use utils::shard::{ShardCount, ShardIndex, ShardNumber}; use pageserver_api::config::DEFAULT_GRPC_LISTEN_PORT as DEFAULT_PAGESERVER_GRPC_PORT; use postgres_connection::parse_host_port; use crate::local_env::LocalEnv; use crate::postgresql_conf::PostgresConf; // contents of a endpoint.json file #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)] pub struct EndpointConf { endpoint_id: String, tenant_id: TenantId, timeline_id: TimelineId, mode: ComputeMode, pg_port: u16, external_http_port: u16, internal_http_port: u16, pg_version: PgMajorVersion, grpc: bool, skip_pg_catalog_updates: bool, reconfigure_concurrency: usize, drop_subscriptions_before_start: bool, features: Vec<ComputeFeature>, cluster: Option<Cluster>, compute_ctl_config: ComputeCtlConfig, privileged_role_name: Option<String>, } // // ComputeControlPlane // pub struct ComputeControlPlane { base_port: u16, // endpoint ID is the key pub endpoints: BTreeMap<String, Arc<Endpoint>>, env: LocalEnv, } impl ComputeControlPlane { // Load current endpoints from the endpoints/ subdirectories pub fn load(env: LocalEnv) -> Result<ComputeControlPlane> { let mut endpoints = BTreeMap::default(); for endpoint_dir in std::fs::read_dir(env.endpoints_path()) .with_context(|| format!("failed to list {}", env.endpoints_path().display()))? { let ep_res = Endpoint::from_dir_entry(endpoint_dir?, &env); let ep = match ep_res { Ok(ep) => ep, Err(e) => match e.downcast::<std::io::Error>() { Ok(e) => { // A parallel task could delete an endpoint while we have just scanned the directory if e.kind() == std::io::ErrorKind::NotFound { continue; } else { Err(e)? } } Err(e) => Err(e)?, }, }; endpoints.insert(ep.endpoint_id.clone(), Arc::new(ep)); } Ok(ComputeControlPlane { base_port: 55431, endpoints, env, }) } fn get_port(&mut self) -> u16 { 1 + self .endpoints .values() .map(|ep| std::cmp::max(ep.pg_address.port(), ep.external_http_address.port())) .max() .unwrap_or(self.base_port) } /// Create a JSON Web Key Set. This ideally matches the way we create a JWKS /// from the production control plane. fn create_jwks_from_pem(pem: &Pem) -> Result<JwkSet> { let spki: SubjectPublicKeyInfoRef = SubjectPublicKeyInfo::from_der(pem.contents())?; let public_key = spki.subject_public_key.raw_bytes(); let mut hasher = Sha256::new(); hasher.update(public_key); let key_hash = hasher.finalize(); Ok(JwkSet { keys: vec![Jwk { common: CommonParameters { public_key_use: Some(PublicKeyUse::Signature), key_operations: Some(vec![KeyOperations::Verify]), key_algorithm: Some(KeyAlgorithm::EdDSA), key_id: Some(BASE64_URL_SAFE_NO_PAD.encode(key_hash)), x509_url: None::<String>, x509_chain: None::<Vec<String>>, x509_sha1_fingerprint: None::<String>, x509_sha256_fingerprint: None::<String>, }, algorithm: AlgorithmParameters::OctetKeyPair(OctetKeyPairParameters { key_type: OctetKeyPairType::OctetKeyPair, curve: EllipticCurve::Ed25519, x: BASE64_URL_SAFE_NO_PAD.encode(public_key), }), }], }) } #[allow(clippy::too_many_arguments)] pub fn new_endpoint( &mut self, endpoint_id: &str, tenant_id: TenantId, timeline_id: TimelineId, pg_port: Option<u16>, external_http_port: Option<u16>, internal_http_port: Option<u16>, pg_version: PgMajorVersion, mode: ComputeMode, grpc: bool, skip_pg_catalog_updates: bool, drop_subscriptions_before_start: bool, privileged_role_name: Option<String>, ) -> Result<Arc<Endpoint>> { let pg_port = pg_port.unwrap_or_else(|| self.get_port()); let external_http_port = external_http_port.unwrap_or_else(|| self.get_port() + 1); let internal_http_port = internal_http_port.unwrap_or_else(|| external_http_port + 1); let compute_ctl_config = ComputeCtlConfig { jwks: Self::create_jwks_from_pem(&self.env.read_public_key()?)?, tls: None::<TlsConfig>, }; let ep = Arc::new(Endpoint { endpoint_id: endpoint_id.to_owned(), pg_address: SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), pg_port), external_http_address: SocketAddr::new( IpAddr::from(Ipv4Addr::UNSPECIFIED), external_http_port, ), internal_http_address: SocketAddr::new( IpAddr::from(Ipv4Addr::LOCALHOST), internal_http_port, ), env: self.env.clone(), timeline_id, mode, tenant_id, pg_version, // We don't setup roles and databases in the spec locally, so we don't need to // do catalog updates. Catalog updates also include check availability // data creation. Yet, we have tests that check that size and db dump // before and after start are the same. So, skip catalog updates, // with this we basically test a case of waking up an idle compute, where // we also skip catalog updates in the cloud. skip_pg_catalog_updates, drop_subscriptions_before_start, grpc, reconfigure_concurrency: 1, features: vec![], cluster: None, compute_ctl_config: compute_ctl_config.clone(), privileged_role_name: privileged_role_name.clone(), }); ep.create_endpoint_dir()?; std::fs::write( ep.endpoint_path().join("endpoint.json"), serde_json::to_string_pretty(&EndpointConf { endpoint_id: endpoint_id.to_string(), tenant_id, timeline_id, mode, external_http_port, internal_http_port, pg_port, pg_version, grpc, skip_pg_catalog_updates, drop_subscriptions_before_start, reconfigure_concurrency: 1, features: vec![], cluster: None, compute_ctl_config, privileged_role_name, })?, )?; std::fs::write( ep.endpoint_path().join("postgresql.conf"), ep.setup_pg_conf()?.to_string(), )?; self.endpoints .insert(ep.endpoint_id.clone(), Arc::clone(&ep)); Ok(ep) } pub fn check_conflicting_endpoints( &self, mode: ComputeMode, tenant_id: TenantId, timeline_id: TimelineId, ) -> Result<()> { if matches!(mode, ComputeMode::Primary) { // this check is not complete, as you could have a concurrent attempt at // creating another primary, both reading the state before checking it here, // but it's better than nothing. let mut duplicates = self.endpoints.iter().filter(|(_k, v)| { v.tenant_id == tenant_id && v.timeline_id == timeline_id && v.mode == mode && v.status() != EndpointStatus::Stopped }); if let Some((key, _)) = duplicates.next() { bail!( "attempting to create a duplicate primary endpoint on tenant {tenant_id}, timeline {timeline_id}: endpoint {key:?} exists already. please don't do this, it is not supported." ); } } Ok(()) } } /////////////////////////////////////////////////////////////////////////////// pub struct Endpoint { /// used as the directory name endpoint_id: String, pub tenant_id: TenantId, pub timeline_id: TimelineId, pub mode: ComputeMode, /// If true, the endpoint should use gRPC to communicate with Pageservers. pub grpc: bool, // port and address of the Postgres server and `compute_ctl`'s HTTP APIs pub pg_address: SocketAddr, pub external_http_address: SocketAddr, pub internal_http_address: SocketAddr, // postgres major version in the format: 14, 15, etc. pg_version: PgMajorVersion, // These are not part of the endpoint as such, but the environment // the endpoint runs in. pub env: LocalEnv, // Optimizations skip_pg_catalog_updates: bool, drop_subscriptions_before_start: bool, reconfigure_concurrency: usize, // Feature flags features: Vec<ComputeFeature>, // Cluster settings cluster: Option<Cluster>, /// The compute_ctl config for the endpoint's compute. compute_ctl_config: ComputeCtlConfig, /// The name of the privileged role for the endpoint. privileged_role_name: Option<String>, } #[derive(PartialEq, Eq)] pub enum EndpointStatus { Running, Stopped, Crashed, RunningNoPidfile, } impl Display for EndpointStatus { fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result { writer.write_str(match self { Self::Running => "running", Self::Stopped => "stopped", Self::Crashed => "crashed", Self::RunningNoPidfile => "running, no pidfile", }) } } #[derive(Default, Clone, Copy, clap::ValueEnum)] pub enum EndpointTerminateMode { #[default] /// Use pg_ctl stop -m fast Fast, /// Use pg_ctl stop -m immediate Immediate, /// Use /terminate?mode=immediate ImmediateTerminate, } impl std::fmt::Display for EndpointTerminateMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match &self { EndpointTerminateMode::Fast => "fast", EndpointTerminateMode::Immediate => "immediate", EndpointTerminateMode::ImmediateTerminate => "immediate-terminate", }) } } pub struct EndpointStartArgs { pub auth_token: Option<String>, pub endpoint_storage_token: String, pub endpoint_storage_addr: String, pub safekeepers_generation: Option<SafekeeperGeneration>, pub safekeepers: Vec<NodeId>, pub pageserver_conninfo: PageserverConnectionInfo, pub remote_ext_base_url: Option<String>, pub create_test_user: bool, pub start_timeout: Duration, pub autoprewarm: bool, pub offload_lfc_interval_seconds: Option<std::num::NonZeroU64>, pub dev: bool, } impl Endpoint { fn from_dir_entry(entry: std::fs::DirEntry, env: &LocalEnv) -> Result<Endpoint> { if !entry.file_type()?.is_dir() { anyhow::bail!( "Endpoint::from_dir_entry failed: '{}' is not a directory", entry.path().display() ); } // parse data directory name let fname = entry.file_name(); let endpoint_id = fname.to_str().unwrap().to_string(); // Read the endpoint.json file let conf: EndpointConf = serde_json::from_slice(&std::fs::read(entry.path().join("endpoint.json"))?)?; debug!("serialized endpoint conf: {:?}", conf); Ok(Endpoint { pg_address: SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), conf.pg_port), external_http_address: SocketAddr::new( IpAddr::from(Ipv4Addr::UNSPECIFIED), conf.external_http_port, ), internal_http_address: SocketAddr::new( IpAddr::from(Ipv4Addr::LOCALHOST), conf.internal_http_port, ), endpoint_id, env: env.clone(), timeline_id: conf.timeline_id, mode: conf.mode, tenant_id: conf.tenant_id, pg_version: conf.pg_version, grpc: conf.grpc, skip_pg_catalog_updates: conf.skip_pg_catalog_updates, reconfigure_concurrency: conf.reconfigure_concurrency, drop_subscriptions_before_start: conf.drop_subscriptions_before_start, features: conf.features, cluster: conf.cluster, compute_ctl_config: conf.compute_ctl_config, privileged_role_name: conf.privileged_role_name, }) } fn create_endpoint_dir(&self) -> Result<()> { std::fs::create_dir_all(self.endpoint_path()).with_context(|| { format!( "could not create endpoint directory {}", self.endpoint_path().display() ) }) } // Generate postgresql.conf with default configuration fn setup_pg_conf(&self) -> Result<PostgresConf> { let mut conf = PostgresConf::new(); conf.append("max_wal_senders", "10"); conf.append("wal_log_hints", "off"); conf.append("max_replication_slots", "10"); conf.append("hot_standby", "on"); // Set to 1MB to both exercise getPage requests/LFC, and still have enough room for // Postgres to operate. Everything smaller might be not enough for Postgres under load, // and can cause errors like 'no unpinned buffers available', see // <https://github.com/neondatabase/neon/issues/9956> conf.append("shared_buffers", "1MB"); // Postgres defaults to effective_io_concurrency=1, which does not exercise the pageserver's // batching logic. Set this to 2 so that we exercise the code a bit without letting // individual tests do a lot of concurrent work on underpowered test machines conf.append("effective_io_concurrency", "2"); conf.append("fsync", "off"); conf.append("max_connections", "100"); conf.append("wal_level", "logical"); // wal_sender_timeout is the maximum time to wait for WAL replication. // It also defines how often the walreceiver will send a feedback message to the wal sender. conf.append("wal_sender_timeout", "5s"); conf.append("listen_addresses", &self.pg_address.ip().to_string()); conf.append("port", &self.pg_address.port().to_string()); conf.append("wal_keep_size", "0"); // walproposer panics when basebackup is invalid, it is pointless to restart in this case. conf.append("restart_after_crash", "off"); // Load the 'neon' extension conf.append("shared_preload_libraries", "neon"); conf.append_line(""); // Replication-related configurations, such as WAL sending match &self.mode { ComputeMode::Primary => { // Configure backpressure // - Replication write lag depends on how fast the walreceiver can process incoming WAL. // This lag determines latency of get_page_at_lsn. Speed of applying WAL is about 10MB/sec, // so to avoid expiration of 1 minute timeout, this lag should not be larger than 600MB. // Actually latency should be much smaller (better if < 1sec). But we assume that recently // updates pages are not requested from pageserver. // - Replication flush lag depends on speed of persisting data by checkpointer (creation of // delta/image layers) and advancing disk_consistent_lsn. Safekeepers are able to // remove/archive WAL only beyond disk_consistent_lsn. Too large a lag can cause long // recovery time (in case of pageserver crash) and disk space overflow at safekeepers. // - Replication apply lag depends on speed of uploading changes to S3 by uploader thread. // To be able to restore database in case of pageserver node crash, safekeeper should not // remove WAL beyond this point. Too large lag can cause space exhaustion in safekeepers // (if they are not able to upload WAL to S3). conf.append("max_replication_write_lag", "15MB"); conf.append("max_replication_flush_lag", "10GB"); if !self.env.safekeepers.is_empty() { // Configure Postgres to connect to the safekeepers conf.append("synchronous_standby_names", "walproposer"); let safekeepers = self .env .safekeepers .iter() .map(|sk| format!("localhost:{}", sk.get_compute_port())) .collect::<Vec<String>>() .join(","); conf.append("neon.safekeepers", &safekeepers); } else { // We only use setup without safekeepers for tests, // and don't care about data durability on pageserver, // so set more relaxed synchronous_commit. conf.append("synchronous_commit", "remote_write"); // Configure the node to stream WAL directly to the pageserver // This isn't really a supported configuration, but can be useful for // testing. conf.append("synchronous_standby_names", "pageserver"); } } ComputeMode::Static(lsn) => { conf.append("recovery_target_lsn", &lsn.to_string()); } ComputeMode::Replica => { assert!(!self.env.safekeepers.is_empty()); // TODO: use future host field from safekeeper spec // Pass the list of safekeepers to the replica so that it can connect to any of them, // whichever is available. let sk_ports = self .env .safekeepers .iter() .map(|x| x.get_compute_port().to_string()) .collect::<Vec<_>>() .join(","); let sk_hosts = vec!["localhost"; self.env.safekeepers.len()].join(","); let connstr = format!( "host={} port={} options='-c timeline_id={} tenant_id={}' application_name=replica replication=true", sk_hosts, sk_ports, &self.timeline_id.to_string(), &self.tenant_id.to_string(), ); let slot_name = format!("repl_{}_", self.timeline_id); conf.append("primary_conninfo", connstr.as_str()); conf.append("primary_slot_name", slot_name.as_str()); conf.append("hot_standby", "on"); // prefetching of blocks referenced in WAL doesn't make sense for us // Neon hot standby ignores pages that are not in the shared_buffers if self.pg_version >= PgMajorVersion::PG15 { conf.append("recovery_prefetch", "off"); } } } Ok(conf) } pub fn endpoint_path(&self) -> PathBuf { self.env.endpoints_path().join(&self.endpoint_id) } pub fn pgdata(&self) -> PathBuf { self.endpoint_path().join("pgdata") } pub fn status(&self) -> EndpointStatus { let timeout = Duration::from_millis(300); let has_pidfile = self.pgdata().join("postmaster.pid").exists(); let can_connect = TcpStream::connect_timeout(&self.pg_address, timeout).is_ok(); match (has_pidfile, can_connect) { (true, true) => EndpointStatus::Running, (false, false) => EndpointStatus::Stopped, (true, false) => EndpointStatus::Crashed, (false, true) => EndpointStatus::RunningNoPidfile, } } fn pg_ctl(&self, args: &[&str], auth_token: &Option<String>) -> Result<()> { let pg_ctl_path = self.env.pg_bin_dir(self.pg_version)?.join("pg_ctl"); let mut cmd = Command::new(&pg_ctl_path); cmd.args( [ &[ "-D", self.pgdata().to_str().unwrap(), "-w", //wait till pg_ctl actually does what was asked ], args, ] .concat(), ) .env_clear() .env( "LD_LIBRARY_PATH", self.env.pg_lib_dir(self.pg_version)?.to_str().unwrap(), ) .env( "DYLD_LIBRARY_PATH", self.env.pg_lib_dir(self.pg_version)?.to_str().unwrap(), ); // Pass authentication token used for the connections to pageserver and safekeepers if let Some(token) = auth_token { cmd.env("NEON_AUTH_TOKEN", token); } let pg_ctl = cmd .output() .context(format!("{} failed", pg_ctl_path.display()))?; if !pg_ctl.status.success() { anyhow::bail!( "pg_ctl failed, exit code: {}, stdout: {}, stderr: {}", pg_ctl.status, String::from_utf8_lossy(&pg_ctl.stdout), String::from_utf8_lossy(&pg_ctl.stderr), ); } Ok(()) } fn wait_for_compute_ctl_to_exit(&self, send_sigterm: bool) -> Result<()> { // TODO use background_process::stop_process instead: https://github.com/neondatabase/neon/pull/6482 let pidfile_path = self.endpoint_path().join("compute_ctl.pid"); let pid: u32 = std::fs::read_to_string(pidfile_path)?.parse()?; let pid = nix::unistd::Pid::from_raw(pid as i32); if send_sigterm { kill(pid, Signal::SIGTERM).ok(); } crate::background_process::wait_until_stopped("compute_ctl", pid)?; Ok(()) } fn read_postgresql_conf(&self) -> Result<String> { // Slurp the endpoints/<endpoint id>/postgresql.conf file into // memory. We will include it in the spec file that we pass to // `compute_ctl`, and `compute_ctl` will write it to the postgresql.conf // in the data directory. let postgresql_conf_path = self.endpoint_path().join("postgresql.conf"); match std::fs::read(&postgresql_conf_path) { Ok(content) => Ok(String::from_utf8(content)?), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok("".to_string()), Err(e) => Err(anyhow::Error::new(e).context(format!( "failed to read config file in {}", postgresql_conf_path.to_str().unwrap() ))), } } /// Map safekeepers ids to the actual connection strings. fn build_safekeepers_connstrs(&self, sk_ids: Vec<NodeId>) -> Result<Vec<String>> { let mut safekeeper_connstrings = Vec::new(); if self.mode == ComputeMode::Primary { for sk_id in sk_ids { let sk = self .env .safekeepers .iter() .find(|node| node.id == sk_id) .ok_or_else(|| anyhow!("safekeeper {sk_id} does not exist"))?; safekeeper_connstrings.push(format!("127.0.0.1:{}", sk.get_compute_port())); } } Ok(safekeeper_connstrings) } /// Generate a JWT with the correct claims. pub fn generate_jwt(&self, scope: Option<ComputeClaimsScope>) -> Result<String> { self.env.generate_auth_token(&ComputeClaims { audience: match scope { Some(ComputeClaimsScope::Admin) => Some(vec![COMPUTE_AUDIENCE.to_owned()]), _ => None, }, compute_id: match scope { Some(ComputeClaimsScope::Admin) => None, _ => Some(self.endpoint_id.clone()), }, scope, }) } pub async fn start(&self, args: EndpointStartArgs) -> Result<()> { if self.status() == EndpointStatus::Running { anyhow::bail!("The endpoint is already running"); } let postgresql_conf = self.read_postgresql_conf()?; // We always start the compute node from scratch, so if the Postgres // data dir exists from a previous launch, remove it first. if self.pgdata().exists() { std::fs::remove_dir_all(self.pgdata())?; } let safekeeper_connstrings = self.build_safekeepers_connstrs(args.safekeepers)?; // check for file remote_extensions_spec.json // if it is present, read it and pass to compute_ctl let remote_extensions_spec_path = self.endpoint_path().join("remote_extensions_spec.json"); let remote_extensions_spec = std::fs::File::open(remote_extensions_spec_path); let remote_extensions: Option<RemoteExtSpec>; if let Ok(spec_file) = remote_extensions_spec { remote_extensions = serde_json::from_reader(spec_file).ok(); } else { remote_extensions = None; }; // For the sake of backwards-compatibility, also fill in 'pageserver_connstring' // // XXX: I believe this is not really needed, except to make // test_forward_compatibility happy. // // Use a closure so that we can conviniently return None in the middle of the // loop. let pageserver_connstring: Option<String> = (|| { let num_shards = args.pageserver_conninfo.shard_count.count(); let mut connstrings = Vec::new(); for shard_no in 0..num_shards { let shard_index = ShardIndex { shard_count: args.pageserver_conninfo.shard_count, shard_number: ShardNumber(shard_no), }; let shard = args .pageserver_conninfo .shards .get(&shard_index) .ok_or_else(|| { anyhow!( "shard {} not found in pageserver_connection_info", shard_index ) })?; let pageserver = shard .pageservers .first() .ok_or(anyhow!("must have at least one pageserver"))?; if let Some(libpq_url) = &pageserver.libpq_url { connstrings.push(libpq_url.clone()); } else { return Ok::<_, anyhow::Error>(None); } } Ok(Some(connstrings.join(","))) })()?; // Create config file let config = { let mut spec = ComputeSpec { skip_pg_catalog_updates: self.skip_pg_catalog_updates, format_version: 1.0, operation_uuid: None, features: self.features.clone(), swap_size_bytes: None, disk_quota_bytes: None, disable_lfc_resizing: None, cluster: Cluster { cluster_id: None, // project ID: not used name: None, // project name: not used state: None, roles: if args.create_test_user { vec![Role { name: PgIdent::from_str("test").unwrap(), encrypted_password: None, options: None, }] } else { Vec::new() }, databases: if args.create_test_user { vec![Database { name: PgIdent::from_str("neondb").unwrap(), owner: PgIdent::from_str("test").unwrap(), options: None, restrict_conn: false, invalid: false, }] } else { Vec::new() }, settings: None, postgresql_conf: Some(postgresql_conf.clone()), }, delta_operations: None, tenant_id: Some(self.tenant_id), timeline_id: Some(self.timeline_id), project_id: None, branch_id: None, endpoint_id: Some(self.endpoint_id.clone()), mode: self.mode, pageserver_connection_info: Some(args.pageserver_conninfo.clone()), pageserver_connstring, safekeepers_generation: args.safekeepers_generation.map(|g| g.into_inner()), safekeeper_connstrings, storage_auth_token: args.auth_token.clone(), remote_extensions, pgbouncer_settings: None,
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/src/bin/neon_local.rs
control_plane/src/bin/neon_local.rs
//! //! `neon_local` is an executable that can be used to create a local //! Neon environment, for testing purposes. The local environment is //! quite different from the cloud environment with Kubernetes, but it //! easier to work with locally. The python tests in `test_runner` //! rely on `neon_local` to set up the environment for each test. //! use std::borrow::Cow; use std::collections::{BTreeSet, HashMap}; use std::fs::File; use std::path::PathBuf; use std::process::exit; use std::str::FromStr; use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; use clap::Parser; use compute_api::requests::ComputeClaimsScope; use compute_api::spec::{ComputeMode, PageserverProtocol}; use control_plane::broker::StorageBroker; use control_plane::endpoint::{ComputeControlPlane, EndpointTerminateMode}; use control_plane::endpoint::{ local_pageserver_conf_to_conn_info, tenant_locate_response_to_conn_info, }; use control_plane::endpoint_storage::{ENDPOINT_STORAGE_DEFAULT_ADDR, EndpointStorage}; use control_plane::local_env; use control_plane::local_env::{ EndpointStorageConf, InitForceMode, LocalEnv, NeonBroker, NeonLocalInitConf, NeonLocalInitPageserverConf, SafekeeperConf, }; use control_plane::pageserver::PageServerNode; use control_plane::safekeeper::SafekeeperNode; use control_plane::storage_controller::{ NeonStorageControllerStartArgs, NeonStorageControllerStopArgs, StorageController, }; use nix::fcntl::{Flock, FlockArg}; use pageserver_api::config::{ DEFAULT_GRPC_LISTEN_PORT as DEFAULT_PAGESERVER_GRPC_PORT, DEFAULT_HTTP_LISTEN_PORT as DEFAULT_PAGESERVER_HTTP_PORT, DEFAULT_PG_LISTEN_PORT as DEFAULT_PAGESERVER_PG_PORT, }; use pageserver_api::controller_api::{ NodeAvailabilityWrapper, PlacementPolicy, TenantCreateRequest, }; use pageserver_api::models::{ ShardParameters, TenantConfigRequest, TimelineCreateRequest, TimelineInfo, }; use pageserver_api::shard::{DEFAULT_STRIPE_SIZE, ShardCount, ShardStripeSize, TenantShardId}; use postgres_backend::AuthType; use safekeeper_api::membership::{SafekeeperGeneration, SafekeeperId}; use safekeeper_api::{ DEFAULT_HTTP_LISTEN_PORT as DEFAULT_SAFEKEEPER_HTTP_PORT, DEFAULT_PG_LISTEN_PORT as DEFAULT_SAFEKEEPER_PG_PORT, PgMajorVersion, PgVersionId, }; use storage_broker::DEFAULT_LISTEN_ADDR as DEFAULT_BROKER_ADDR; use tokio::task::JoinSet; use utils::auth::{Claims, Scope}; use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId}; use utils::lsn::Lsn; use utils::project_git_version; // Default id of a safekeeper node, if not specified on the command line. const DEFAULT_SAFEKEEPER_ID: NodeId = NodeId(1); const DEFAULT_PAGESERVER_ID: NodeId = NodeId(1); const DEFAULT_BRANCH_NAME: &str = "main"; project_git_version!(GIT_VERSION); #[allow(dead_code)] const DEFAULT_PG_VERSION: PgMajorVersion = PgMajorVersion::PG17; const DEFAULT_PG_VERSION_NUM: &str = "17"; const DEFAULT_PAGESERVER_CONTROL_PLANE_API: &str = "http://127.0.0.1:1234/upcall/v1/"; /// Neon CLI. #[derive(clap::Parser)] #[command(version = GIT_VERSION, name = "Neon CLI")] struct Cli { #[command(subcommand)] command: NeonLocalCmd, } #[derive(clap::Subcommand)] enum NeonLocalCmd { Init(InitCmdArgs), #[command(subcommand)] Tenant(TenantCmd), #[command(subcommand)] Timeline(TimelineCmd), #[command(subcommand)] Pageserver(PageserverCmd), #[command(subcommand)] #[clap(alias = "storage_controller")] StorageController(StorageControllerCmd), #[command(subcommand)] #[clap(alias = "storage_broker")] StorageBroker(StorageBrokerCmd), #[command(subcommand)] Safekeeper(SafekeeperCmd), #[command(subcommand)] EndpointStorage(EndpointStorageCmd), #[command(subcommand)] Endpoint(EndpointCmd), #[command(subcommand)] Mappings(MappingsCmd), Start(StartCmdArgs), Stop(StopCmdArgs), } /// Initialize a new Neon repository, preparing configs for services to start with. #[derive(clap::Args)] struct InitCmdArgs { /// How many pageservers to create (default 1). #[clap(long)] num_pageservers: Option<u16>, #[clap(long)] config: Option<PathBuf>, /// Force initialization even if the repository is not empty. #[clap(long, default_value = "must-not-exist")] #[arg(value_parser)] force: InitForceMode, } /// Start pageserver and safekeepers. #[derive(clap::Args)] struct StartCmdArgs { #[clap(long = "start-timeout", default_value = "10s")] timeout: humantime::Duration, } /// Stop pageserver and safekeepers. #[derive(clap::Args)] struct StopCmdArgs { #[arg(value_enum)] #[clap(long, default_value_t = StopMode::Fast)] mode: StopMode, } #[derive(Clone, Copy, clap::ValueEnum)] enum StopMode { Fast, Immediate, } /// Manage tenants. #[derive(clap::Subcommand)] enum TenantCmd { List, Create(TenantCreateCmdArgs), SetDefault(TenantSetDefaultCmdArgs), Config(TenantConfigCmdArgs), Import(TenantImportCmdArgs), } #[derive(clap::Args)] struct TenantCreateCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, /// Use a specific timeline id when creating a tenant and its initial timeline. #[clap(long)] timeline_id: Option<TimelineId>, #[clap(short = 'c')] config: Vec<String>, /// Postgres version to use for the initial timeline. #[arg(default_value = DEFAULT_PG_VERSION_NUM)] #[clap(long)] pg_version: PgMajorVersion, /// Use this tenant in future CLI commands where tenant_id is needed, but not specified. #[clap(long)] set_default: bool, /// Number of shards in the new tenant. #[clap(long)] #[arg(default_value_t = 0)] shard_count: u8, /// Sharding stripe size in pages. #[clap(long)] shard_stripe_size: Option<u32>, /// Placement policy shards in this tenant. #[clap(long)] #[arg(value_parser = parse_placement_policy)] placement_policy: Option<PlacementPolicy>, } fn parse_placement_policy(s: &str) -> anyhow::Result<PlacementPolicy> { Ok(serde_json::from_str::<PlacementPolicy>(s)?) } /// Set a particular tenant as default in future CLI commands where tenant_id is needed, but not /// specified. #[derive(clap::Args)] struct TenantSetDefaultCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: TenantId, } #[derive(clap::Args)] struct TenantConfigCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, #[clap(short = 'c')] config: Vec<String>, } /// Import a tenant that is present in remote storage, and create branches for its timelines. #[derive(clap::Args)] struct TenantImportCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: TenantId, } /// Manage timelines. #[derive(clap::Subcommand)] enum TimelineCmd { List(TimelineListCmdArgs), Branch(TimelineBranchCmdArgs), Create(TimelineCreateCmdArgs), Import(TimelineImportCmdArgs), } /// List all timelines available to this pageserver. #[derive(clap::Args)] struct TimelineListCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_shard_id: Option<TenantShardId>, } /// Create a new timeline, branching off from another timeline. #[derive(clap::Args)] struct TimelineBranchCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, /// New timeline's ID, as a 32-byte hexadecimal string. #[clap(long)] timeline_id: Option<TimelineId>, /// Human-readable alias for the new timeline. #[clap(long)] branch_name: String, /// Use last Lsn of another timeline (and its data) as base when creating the new timeline. The /// timeline gets resolved by its branch name. #[clap(long)] ancestor_branch_name: Option<String>, /// When using another timeline as base, use a specific Lsn in it instead of the latest one. #[clap(long)] ancestor_start_lsn: Option<Lsn>, } /// Create a new blank timeline. #[derive(clap::Args)] struct TimelineCreateCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, /// New timeline's ID, as a 32-byte hexadecimal string. #[clap(long)] timeline_id: Option<TimelineId>, /// Human-readable alias for the new timeline. #[clap(long)] branch_name: String, /// Postgres version. #[arg(default_value = DEFAULT_PG_VERSION_NUM)] #[clap(long)] pg_version: PgMajorVersion, } /// Import a timeline from a basebackup directory. #[derive(clap::Args)] struct TimelineImportCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, /// New timeline's ID, as a 32-byte hexadecimal string. #[clap(long)] timeline_id: TimelineId, /// Human-readable alias for the new timeline. #[clap(long)] branch_name: String, /// Basebackup tarfile to import. #[clap(long)] base_tarfile: PathBuf, /// LSN the basebackup starts at. #[clap(long)] base_lsn: Lsn, /// WAL to add after base. #[clap(long)] wal_tarfile: Option<PathBuf>, /// LSN the basebackup ends at. #[clap(long)] end_lsn: Option<Lsn>, /// Postgres version of the basebackup being imported. #[arg(default_value = DEFAULT_PG_VERSION_NUM)] #[clap(long)] pg_version: PgMajorVersion, } /// Manage pageservers. #[derive(clap::Subcommand)] enum PageserverCmd { Status(PageserverStatusCmdArgs), Start(PageserverStartCmdArgs), Stop(PageserverStopCmdArgs), Restart(PageserverRestartCmdArgs), } /// Show status of a local pageserver. #[derive(clap::Args)] struct PageserverStatusCmdArgs { /// Pageserver ID. #[clap(long = "id")] pageserver_id: Option<NodeId>, } /// Start local pageserver. #[derive(clap::Args)] struct PageserverStartCmdArgs { /// Pageserver ID. #[clap(long = "id")] pageserver_id: Option<NodeId>, /// Timeout until we fail the command. #[clap(short = 't', long)] #[arg(default_value = "10s")] start_timeout: humantime::Duration, } /// Stop local pageserver. #[derive(clap::Args)] struct PageserverStopCmdArgs { /// Pageserver ID. #[clap(long = "id")] pageserver_id: Option<NodeId>, /// If 'immediate', don't flush repository data at shutdown #[clap(short = 'm')] #[arg(value_enum, default_value = "fast")] stop_mode: StopMode, } /// Restart local pageserver. #[derive(clap::Args)] struct PageserverRestartCmdArgs { /// Pageserver ID. #[clap(long = "id")] pageserver_id: Option<NodeId>, /// Timeout until we fail the command. #[clap(short = 't', long)] #[arg(default_value = "10s")] start_timeout: humantime::Duration, } /// Manage storage controller. #[derive(clap::Subcommand)] enum StorageControllerCmd { Start(StorageControllerStartCmdArgs), Stop(StorageControllerStopCmdArgs), } /// Start storage controller. #[derive(clap::Args)] struct StorageControllerStartCmdArgs { /// Timeout until we fail the command. #[clap(short = 't', long)] #[arg(default_value = "10s")] start_timeout: humantime::Duration, /// Identifier used to distinguish storage controller instances. #[clap(long)] #[arg(default_value_t = 1)] instance_id: u8, /// Base port for the storage controller instance identified by instance-id (defaults to /// pageserver cplane api). #[clap(long)] base_port: Option<u16>, /// Whether the storage controller should handle pageserver-reported local disk loss events. #[clap(long)] handle_ps_local_disk_loss: Option<bool>, } /// Stop storage controller. #[derive(clap::Args)] struct StorageControllerStopCmdArgs { /// If 'immediate', don't flush repository data at shutdown #[clap(short = 'm')] #[arg(value_enum, default_value = "fast")] stop_mode: StopMode, /// Identifier used to distinguish storage controller instances. #[clap(long)] #[arg(default_value_t = 1)] instance_id: u8, } /// Manage storage broker. #[derive(clap::Subcommand)] enum StorageBrokerCmd { Start(StorageBrokerStartCmdArgs), Stop(StorageBrokerStopCmdArgs), } /// Start broker. #[derive(clap::Args)] struct StorageBrokerStartCmdArgs { /// Timeout until we fail the command. #[clap(short = 't', long, default_value = "10s")] start_timeout: humantime::Duration, } /// Stop broker. #[derive(clap::Args)] struct StorageBrokerStopCmdArgs { /// If 'immediate', don't flush repository data on shutdown. #[clap(short = 'm')] #[arg(value_enum, default_value = "fast")] stop_mode: StopMode, } /// Manage safekeepers. #[derive(clap::Subcommand)] enum SafekeeperCmd { Start(SafekeeperStartCmdArgs), Stop(SafekeeperStopCmdArgs), Restart(SafekeeperRestartCmdArgs), } /// Manage object storage. #[derive(clap::Subcommand)] enum EndpointStorageCmd { Start(EndpointStorageStartCmd), Stop(EndpointStorageStopCmd), } /// Start object storage. #[derive(clap::Args)] struct EndpointStorageStartCmd { /// Timeout until we fail the command. #[clap(short = 't', long)] #[arg(default_value = "10s")] start_timeout: humantime::Duration, } /// Stop object storage. #[derive(clap::Args)] struct EndpointStorageStopCmd { /// If 'immediate', don't flush repository data on shutdown. #[clap(short = 'm')] #[arg(value_enum, default_value = "fast")] stop_mode: StopMode, } /// Start local safekeeper. #[derive(clap::Args)] struct SafekeeperStartCmdArgs { /// Safekeeper ID. #[arg(default_value_t = NodeId(1))] id: NodeId, /// Additional safekeeper invocation options, e.g. -e=--http-auth-public-key-path=foo. #[clap(short = 'e', long = "safekeeper-extra-opt")] extra_opt: Vec<String>, /// Timeout until we fail the command. #[clap(short = 't', long)] #[arg(default_value = "10s")] start_timeout: humantime::Duration, } /// Stop local safekeeper. #[derive(clap::Args)] struct SafekeeperStopCmdArgs { /// Safekeeper ID. #[arg(default_value_t = NodeId(1))] id: NodeId, /// If 'immediate', don't flush repository data on shutdown. #[arg(value_enum, default_value = "fast")] #[clap(short = 'm')] stop_mode: StopMode, } /// Restart local safekeeper. #[derive(clap::Args)] struct SafekeeperRestartCmdArgs { /// Safekeeper ID. #[arg(default_value_t = NodeId(1))] id: NodeId, /// If 'immediate', don't flush repository data on shutdown. #[arg(value_enum, default_value = "fast")] #[clap(short = 'm')] stop_mode: StopMode, /// Additional safekeeper invocation options, e.g. -e=--http-auth-public-key-path=foo. #[clap(short = 'e', long = "safekeeper-extra-opt")] extra_opt: Vec<String>, /// Timeout until we fail the command. #[clap(short = 't', long)] #[arg(default_value = "10s")] start_timeout: humantime::Duration, } /// Manage Postgres instances. #[derive(clap::Subcommand)] enum EndpointCmd { List(EndpointListCmdArgs), Create(EndpointCreateCmdArgs), Start(EndpointStartCmdArgs), Reconfigure(EndpointReconfigureCmdArgs), RefreshConfiguration(EndpointRefreshConfigurationArgs), Stop(EndpointStopCmdArgs), UpdatePageservers(EndpointUpdatePageserversCmdArgs), GenerateJwt(EndpointGenerateJwtCmdArgs), } /// List endpoints. #[derive(clap::Args)] struct EndpointListCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_shard_id: Option<TenantShardId>, } /// Create a compute endpoint. #[derive(clap::Args)] struct EndpointCreateCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, /// Postgres endpoint ID. endpoint_id: Option<String>, /// Name of the branch the endpoint will run on. #[clap(long)] branch_name: Option<String>, /// Specify LSN on the timeline to start from. By default, end of the timeline would be used. #[clap(long)] lsn: Option<Lsn>, #[clap(long)] pg_port: Option<u16>, #[clap(long, alias = "http-port")] external_http_port: Option<u16>, #[clap(long)] internal_http_port: Option<u16>, #[clap(long = "pageserver-id")] endpoint_pageserver_id: Option<NodeId>, /// Don't do basebackup, create endpoint directory with only config files. #[clap(long, action = clap::ArgAction::Set, default_value_t = false)] config_only: bool, /// Postgres version. #[arg(default_value = DEFAULT_PG_VERSION_NUM)] #[clap(long)] pg_version: PgMajorVersion, /// Use gRPC to communicate with Pageservers, by generating grpc:// connstrings. /// /// Specified on creation such that it's retained across reconfiguration and restarts. /// /// NB: not yet supported by computes. #[clap(long)] grpc: bool, /// If set, the node will be a hot replica on the specified timeline. #[clap(long, action = clap::ArgAction::Set, default_value_t = false)] hot_standby: bool, /// If set, will set up the catalog for neon_superuser. #[clap(long)] update_catalog: bool, /// Allow multiple primary endpoints running on the same branch. Shouldn't be used normally, but /// useful for tests. #[clap(long)] allow_multiple: bool, /// Name of the privileged role for the endpoint. // Only allow changing it on creation. #[clap(long)] privileged_role_name: Option<String>, } /// Start Postgres. If the endpoint doesn't exist yet, it is created. #[derive(clap::Args)] struct EndpointStartCmdArgs { /// Postgres endpoint ID. endpoint_id: String, /// Pageserver ID. #[clap(long = "pageserver-id")] endpoint_pageserver_id: Option<NodeId>, /// Safekeepers membership generation to prefix neon.safekeepers with. #[clap(long)] safekeepers_generation: Option<u32>, /// List of safekeepers endpoint will talk to. #[clap(long)] safekeepers: Option<String>, /// Configure the remote extensions storage proxy gateway URL to request for extensions. #[clap(long, alias = "remote-ext-config")] remote_ext_base_url: Option<String>, /// If set, will create test user `user` and `neondb` database. Requires `update-catalog = true` #[clap(long)] create_test_user: bool, /// Allow multiple primary endpoints running on the same branch. Shouldn't be used normally, but /// useful for tests. #[clap(long)] allow_multiple: bool, /// Timeout until we fail the command. #[clap(short = 't', long, value_parser= humantime::parse_duration)] #[arg(default_value = "90s")] start_timeout: Duration, /// Download LFC cache from endpoint storage on endpoint startup #[clap(long, default_value = "false")] autoprewarm: bool, /// Upload LFC cache to endpoint storage periodically #[clap(long)] offload_lfc_interval_seconds: Option<std::num::NonZeroU64>, /// Run in development mode, skipping VM-specific operations like process termination #[clap(long, action = clap::ArgAction::SetTrue)] dev: bool, } /// Reconfigure an endpoint. #[derive(clap::Args)] struct EndpointReconfigureCmdArgs { /// Tenant id. Represented as a hexadecimal string 32 symbols length #[clap(long = "tenant-id")] tenant_id: Option<TenantId>, /// Postgres endpoint ID. endpoint_id: String, /// Pageserver ID. #[clap(long = "pageserver-id")] endpoint_pageserver_id: Option<NodeId>, #[clap(long)] safekeepers: Option<String>, } /// Refresh the endpoint's configuration by forcing it reload it's spec #[derive(clap::Args)] struct EndpointRefreshConfigurationArgs { /// Postgres endpoint id endpoint_id: String, } /// Stop an endpoint. #[derive(clap::Args)] struct EndpointStopCmdArgs { /// Postgres endpoint ID. endpoint_id: String, /// Also delete data directory (now optional, should be default in future). #[clap(long)] destroy: bool, /// Postgres shutdown mode, passed to `pg_ctl -m <mode>`. #[clap(long)] #[clap(default_value = "fast")] mode: EndpointTerminateMode, } /// Update the pageservers in the spec file of the compute endpoint #[derive(clap::Args)] struct EndpointUpdatePageserversCmdArgs { /// Postgres endpoint id endpoint_id: String, /// Specified pageserver id #[clap(short = 'p', long)] pageserver_id: Option<NodeId>, } /// Generate a JWT for an endpoint. #[derive(clap::Args)] struct EndpointGenerateJwtCmdArgs { /// Postgres endpoint ID. endpoint_id: String, /// Scope to generate the JWT with. #[clap(short = 's', long, value_parser = ComputeClaimsScope::from_str)] scope: Option<ComputeClaimsScope>, } /// Manage neon_local branch name mappings. #[derive(clap::Subcommand)] enum MappingsCmd { Map(MappingsMapCmdArgs), } /// Create new mapping which cannot exist already. #[derive(clap::Args)] struct MappingsMapCmdArgs { /// Tenant ID, as a 32-byte hexadecimal string. #[clap(long)] tenant_id: TenantId, /// Timeline ID, as a 32-byte hexadecimal string. #[clap(long)] timeline_id: TimelineId, /// Branch name to give to the timeline. #[clap(long)] branch_name: String, } /// /// Timelines tree element used as a value in the HashMap. /// struct TimelineTreeEl { /// `TimelineInfo` received from the `pageserver` via the `timeline_list` http API call. pub info: TimelineInfo, /// Name, recovered from neon config mappings pub name: Option<String>, /// Holds all direct children of this timeline referenced using `timeline_id`. pub children: BTreeSet<TimelineId>, } /// A flock-based guard over the neon_local repository directory struct RepoLock { _file: Flock<File>, } impl RepoLock { fn new() -> Result<Self> { let repo_dir = File::open(local_env::base_path())?; match Flock::lock(repo_dir, FlockArg::LockExclusive) { Ok(f) => Ok(Self { _file: f }), Err((_, e)) => Err(e).context("flock error"), } } } // Main entry point for the 'neon_local' CLI utility // // This utility helps to manage neon installation. That includes following: // * Management of local postgres installations running on top of the // pageserver. // * Providing CLI api to the pageserver // * TODO: export/import to/from usual postgres fn main() -> Result<()> { let cli = Cli::parse(); // Check for 'neon init' command first. let (subcommand_result, _lock) = if let NeonLocalCmd::Init(args) = cli.command { (handle_init(&args).map(|env| Some(Cow::Owned(env))), None) } else { // This tool uses a collection of simple files to store its state, and consequently // it is not generally safe to run multiple commands concurrently. Rather than expect // all callers to know this, use a lock file to protect against concurrent execution. let _repo_lock = RepoLock::new().unwrap(); // all other commands need an existing config let env = LocalEnv::load_config(&local_env::base_path()).context("Error loading config")?; let original_env = env.clone(); let env = Box::leak(Box::new(env)); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); let subcommand_result = match cli.command { NeonLocalCmd::Init(_) => unreachable!("init was handled earlier already"), NeonLocalCmd::Start(args) => rt.block_on(handle_start_all(&args, env)), NeonLocalCmd::Stop(args) => rt.block_on(handle_stop_all(&args, env)), NeonLocalCmd::Tenant(subcmd) => rt.block_on(handle_tenant(&subcmd, env)), NeonLocalCmd::Timeline(subcmd) => rt.block_on(handle_timeline(&subcmd, env)), NeonLocalCmd::Pageserver(subcmd) => rt.block_on(handle_pageserver(&subcmd, env)), NeonLocalCmd::StorageController(subcmd) => { rt.block_on(handle_storage_controller(&subcmd, env)) } NeonLocalCmd::StorageBroker(subcmd) => rt.block_on(handle_storage_broker(&subcmd, env)), NeonLocalCmd::Safekeeper(subcmd) => rt.block_on(handle_safekeeper(&subcmd, env)), NeonLocalCmd::EndpointStorage(subcmd) => { rt.block_on(handle_endpoint_storage(&subcmd, env)) } NeonLocalCmd::Endpoint(subcmd) => rt.block_on(handle_endpoint(&subcmd, env)), NeonLocalCmd::Mappings(subcmd) => handle_mappings(&subcmd, env), }; let subcommand_result = if &original_env != env { subcommand_result.map(|()| Some(Cow::Borrowed(env))) } else { subcommand_result.map(|()| None) }; (subcommand_result, Some(_repo_lock)) }; match subcommand_result { Ok(Some(updated_env)) => updated_env.persist_config()?, Ok(None) => (), Err(e) => { eprintln!("command failed: {e:?}"); exit(1); } } Ok(()) } /// /// Prints timelines list as a tree-like structure. /// fn print_timelines_tree( timelines: Vec<TimelineInfo>, mut timeline_name_mappings: HashMap<TenantTimelineId, String>, ) -> Result<()> { let mut timelines_hash = timelines .iter() .map(|t| { ( t.timeline_id, TimelineTreeEl { info: t.clone(), children: BTreeSet::new(), name: timeline_name_mappings .remove(&TenantTimelineId::new(t.tenant_id.tenant_id, t.timeline_id)), }, ) }) .collect::<HashMap<_, _>>(); // Memorize all direct children of each timeline. for timeline in timelines.iter() { if let Some(ancestor_timeline_id) = timeline.ancestor_timeline_id { timelines_hash .get_mut(&ancestor_timeline_id) .context("missing timeline info in the HashMap")? .children .insert(timeline.timeline_id); } } for timeline in timelines_hash.values() { // Start with root local timelines (no ancestors) first. if timeline.info.ancestor_timeline_id.is_none() { print_timeline(0, &Vec::from([true]), timeline, &timelines_hash)?; } } Ok(()) } /// /// Recursively prints timeline info with all its children. /// fn print_timeline( nesting_level: usize, is_last: &[bool], timeline: &TimelineTreeEl, timelines: &HashMap<TimelineId, TimelineTreeEl>, ) -> Result<()> { if nesting_level > 0 { let ancestor_lsn = match timeline.info.ancestor_lsn { Some(lsn) => lsn.to_string(), None => "Unknown Lsn".to_string(), }; let mut br_sym = "┣━"; // Draw each nesting padding with proper style // depending on whether its timeline ended or not. if nesting_level > 1 { for l in &is_last[1..is_last.len() - 1] { if *l { print!(" "); } else { print!("┃ "); } } } // We are the last in this sub-timeline if *is_last.last().unwrap() { br_sym = "┗━"; } print!("{br_sym} @{ancestor_lsn}: "); } // Finally print a timeline id and name with new line println!( "{} [{}]", timeline.name.as_deref().unwrap_or("_no_name_"), timeline.info.timeline_id ); let len = timeline.children.len(); let mut i: usize = 0; let mut is_last_new = Vec::from(is_last); is_last_new.push(false); for child in &timeline.children { i += 1; // Mark that the last padding is the end of the timeline if i == len { if let Some(last) = is_last_new.last_mut() { *last = true; } } print_timeline( nesting_level + 1, &is_last_new, timelines .get(child) .context("missing timeline info in the HashMap")?, timelines, )?; } Ok(()) } /// Helper function to get tenant id from an optional --tenant_id option or from the config file fn get_tenant_id( tenant_id_arg: Option<TenantId>, env: &local_env::LocalEnv, ) -> anyhow::Result<TenantId> { if let Some(tenant_id_from_arguments) = tenant_id_arg { Ok(tenant_id_from_arguments) } else if let Some(default_id) = env.default_tenant_id { Ok(default_id) } else { anyhow::bail!("No tenant id. Use --tenant-id, or set a default tenant"); } } /// Helper function to get tenant-shard ID from an optional --tenant_id option or from the config file, /// for commands that accept a shard suffix fn get_tenant_shard_id( tenant_shard_id_arg: Option<TenantShardId>, env: &local_env::LocalEnv, ) -> anyhow::Result<TenantShardId> { if let Some(tenant_id_from_arguments) = tenant_shard_id_arg { Ok(tenant_id_from_arguments) } else if let Some(default_id) = env.default_tenant_id { Ok(TenantShardId::unsharded(default_id)) } else { anyhow::bail!("No tenant shard id. Use --tenant-id, or set a default tenant"); } } fn handle_init(args: &InitCmdArgs) -> anyhow::Result<LocalEnv> { // Create the in-memory `LocalEnv` that we'd normally load from disk in `load_config`. let init_conf: NeonLocalInitConf = if let Some(config_path) = &args.config { // User (likely the Python test suite) provided a description of the environment. if args.num_pageservers.is_some() { bail!( "Cannot specify both --num-pageservers and --config, use key `pageservers` in the --config file instead" ); } // load and parse the file let contents = std::fs::read_to_string(config_path).with_context(|| { format!( "Could not read configuration file '{}'", config_path.display() ) })?; toml_edit::de::from_str(&contents)? } else { // User (likely interactive) did not provide a description of the environment, give them the default NeonLocalInitConf { control_plane_api: Some(DEFAULT_PAGESERVER_CONTROL_PLANE_API.parse().unwrap()), broker: NeonBroker { listen_addr: Some(DEFAULT_BROKER_ADDR.parse().unwrap()), listen_https_addr: None, }, safekeepers: vec![SafekeeperConf { id: DEFAULT_SAFEKEEPER_ID, pg_port: DEFAULT_SAFEKEEPER_PG_PORT, http_port: DEFAULT_SAFEKEEPER_HTTP_PORT, ..Default::default() }], pageservers: (0..args.num_pageservers.unwrap_or(1)) .map(|i| { let pageserver_id = NodeId(DEFAULT_PAGESERVER_ID.0 + i as u64); let pg_port = DEFAULT_PAGESERVER_PG_PORT + i; let http_port = DEFAULT_PAGESERVER_HTTP_PORT + i; let grpc_port = DEFAULT_PAGESERVER_GRPC_PORT + i; NeonLocalInitPageserverConf { id: pageserver_id, listen_pg_addr: format!("127.0.0.1:{pg_port}"), listen_http_addr: format!("127.0.0.1:{http_port}"), listen_https_addr: None, listen_grpc_addr: Some(format!("127.0.0.1:{grpc_port}")), pg_auth_type: AuthType::Trust, http_auth_type: AuthType::Trust, grpc_auth_type: AuthType::Trust, other: Default::default(), // Typical developer machines use disks with slow fsync, and we don't care // about data integrity: disable disk syncs. no_sync: true, } }) .collect(), endpoint_storage: EndpointStorageConf { listen_addr: ENDPOINT_STORAGE_DEFAULT_ADDR, }, pg_distrib_dir: None, neon_distrib_dir: None, default_tenant_id: TenantId::from_array(std::array::from_fn(|_| 0)), storage_controller: None, control_plane_hooks_api: None, generate_local_ssl_certs: false, } };
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/control_plane/storcon_cli/src/main.rs
control_plane/storcon_cli/src/main.rs
use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; use clap::{Parser, Subcommand}; use futures::StreamExt; use pageserver_api::controller_api::{ AvailabilityZone, MigrationConfig, NodeAvailabilityWrapper, NodeConfigureRequest, NodeDescribeResponse, NodeRegisterRequest, NodeSchedulingPolicy, NodeShardResponse, PlacementPolicy, SafekeeperDescribeResponse, SafekeeperSchedulingPolicyRequest, ShardSchedulingPolicy, ShardsPreferredAzsRequest, ShardsPreferredAzsResponse, SkSchedulingPolicy, TenantCreateRequest, TenantDescribeResponse, TenantPolicyRequest, TenantShardMigrateRequest, TenantShardMigrateResponse, TimelineSafekeeperMigrateRequest, }; use pageserver_api::models::{ EvictionPolicy, EvictionPolicyLayerAccessThreshold, ShardParameters, TenantConfig, TenantConfigPatchRequest, TenantConfigRequest, TenantShardSplitRequest, TenantShardSplitResponse, }; use pageserver_api::shard::{ShardStripeSize, TenantShardId}; use pageserver_client::mgmt_api::{self}; use reqwest::{Certificate, Method, StatusCode, Url}; use safekeeper_api::models::TimelineLocateResponse; use storage_controller_client::control_api::Client; use utils::id::{NodeId, TenantId, TimelineId}; #[derive(Subcommand, Debug)] enum Command { /// Register a pageserver with the storage controller. This shouldn't usually be necessary, /// since pageservers auto-register when they start up NodeRegister { #[arg(long)] node_id: NodeId, #[arg(long)] listen_pg_addr: String, #[arg(long)] listen_pg_port: u16, #[arg(long)] listen_grpc_addr: Option<String>, #[arg(long)] listen_grpc_port: Option<u16>, #[arg(long)] listen_http_addr: String, #[arg(long)] listen_http_port: u16, #[arg(long)] listen_https_port: Option<u16>, #[arg(long)] availability_zone_id: String, }, /// Modify a node's configuration in the storage controller NodeConfigure { #[arg(long)] node_id: NodeId, /// Availability is usually auto-detected based on heartbeats. Set 'offline' here to /// manually mark a node offline #[arg(long)] availability: Option<NodeAvailabilityArg>, /// Scheduling policy controls whether tenant shards may be scheduled onto this node. #[arg(long)] scheduling: Option<NodeSchedulingPolicy>, }, /// Exists for backup usage and will be removed in future. /// Use [`Command::NodeStartDelete`] instead, if possible. NodeDelete { #[arg(long)] node_id: NodeId, }, /// Start deletion of the specified pageserver. NodeStartDelete { #[arg(long)] node_id: NodeId, /// When `force` is true, skip waiting for shards to prewarm during migration. /// This can significantly speed up node deletion since prewarming all shards /// can take considerable time, but may result in slower initial access to /// migrated shards until they warm up naturally. #[arg(long)] force: bool, }, /// Cancel deletion of the specified pageserver and wait for `timeout` /// for the operation to be canceled. May be retried. NodeCancelDelete { #[arg(long)] node_id: NodeId, #[arg(long)] timeout: humantime::Duration, }, /// Delete a tombstone of node from the storage controller. /// This is used when we want to allow the node to be re-registered. NodeDeleteTombstone { #[arg(long)] node_id: NodeId, }, /// Modify a tenant's policies in the storage controller TenantPolicy { #[arg(long)] tenant_id: TenantId, /// Placement policy controls whether a tenant is `detached`, has only a secondary location (`secondary`), /// or is in the normal attached state with N secondary locations (`attached:N`) #[arg(long)] placement: Option<PlacementPolicyArg>, /// Scheduling policy enables pausing the controller's scheduling activity involving this tenant. `active` is normal, /// `essential` disables optimization scheduling changes, `pause` disables all scheduling changes, and `stop` prevents /// all reconciliation activity including for scheduling changes already made. `pause` and `stop` can make a tenant /// unavailable, and are only for use in emergencies. #[arg(long)] scheduling: Option<ShardSchedulingPolicyArg>, }, /// List nodes known to the storage controller Nodes {}, /// List soft deleted nodes known to the storage controller NodeTombstones {}, /// List tenants known to the storage controller Tenants { /// If this field is set, it will list the tenants on a specific node node_id: Option<NodeId>, }, /// Create a new tenant in the storage controller, and by extension on pageservers. TenantCreate { #[arg(long)] tenant_id: TenantId, }, /// Delete a tenant in the storage controller, and by extension on pageservers. TenantDelete { #[arg(long)] tenant_id: TenantId, }, /// Split an existing tenant into a higher number of shards than its current shard count. TenantShardSplit { #[arg(long)] tenant_id: TenantId, #[arg(long)] shard_count: u8, /// Optional, in 8kiB pages. e.g. set 2048 for 16MB stripes. #[arg(long)] stripe_size: Option<u32>, }, /// Migrate the attached location for a tenant shard to a specific pageserver. TenantShardMigrate { #[arg(long)] tenant_shard_id: TenantShardId, #[arg(long)] node: NodeId, #[arg(long, default_value_t = true, action = clap::ArgAction::Set)] prewarm: bool, #[arg(long, default_value_t = false, action = clap::ArgAction::Set)] override_scheduler: bool, }, /// Watch the location of a tenant shard evolve, e.g. while expecting it to migrate TenantShardWatch { #[arg(long)] tenant_shard_id: TenantShardId, }, /// Migrate the secondary location for a tenant shard to a specific pageserver. TenantShardMigrateSecondary { #[arg(long)] tenant_shard_id: TenantShardId, #[arg(long)] node: NodeId, }, /// Cancel any ongoing reconciliation for this shard TenantShardCancelReconcile { #[arg(long)] tenant_shard_id: TenantShardId, }, /// Set the pageserver tenant configuration of a tenant: this is the configuration structure /// that is passed through to pageservers, and does not affect storage controller behavior. /// Any previous tenant configs are overwritten. SetTenantConfig { #[arg(long)] tenant_id: TenantId, #[arg(long)] config: String, }, /// Patch the pageserver tenant configuration of a tenant. Any fields with null values in the /// provided JSON are unset from the tenant config and all fields with non-null values are set. /// Unspecified fields are not changed. PatchTenantConfig { #[arg(long)] tenant_id: TenantId, #[arg(long)] config: String, }, /// Print details about a particular tenant, including all its shards' states. TenantDescribe { #[arg(long)] tenant_id: TenantId, }, TenantSetPreferredAz { #[arg(long)] tenant_id: TenantId, #[arg(long)] preferred_az: Option<String>, }, /// Uncleanly drop a tenant from the storage controller: this doesn't delete anything from pageservers. Appropriate /// if you e.g. used `tenant-warmup` by mistake on a tenant ID that doesn't really exist, or is in some other region. TenantDrop { #[arg(long)] tenant_id: TenantId, #[arg(long)] unclean: bool, }, NodeDrop { #[arg(long)] node_id: NodeId, #[arg(long)] unclean: bool, }, TenantSetTimeBasedEviction { #[arg(long)] tenant_id: TenantId, #[arg(long)] period: humantime::Duration, #[arg(long)] threshold: humantime::Duration, }, // Migrate away from a set of specified pageservers by moving the primary attachments to pageservers // outside of the specified set. BulkMigrate { // Set of pageserver node ids to drain. #[arg(long)] nodes: Vec<NodeId>, // Optional: migration concurrency (default is 8) #[arg(long)] concurrency: Option<usize>, // Optional: maximum number of shards to migrate #[arg(long)] max_shards: Option<usize>, // Optional: when set to true, nothing is migrated, but the plan is printed to stdout #[arg(long)] dry_run: Option<bool>, }, /// Start draining the specified pageserver. /// The drain is complete when the schedulling policy returns to active. StartDrain { #[arg(long)] node_id: NodeId, }, /// Cancel draining the specified pageserver and wait for `timeout` /// for the operation to be canceled. May be retried. CancelDrain { #[arg(long)] node_id: NodeId, #[arg(long)] timeout: humantime::Duration, }, /// Start filling the specified pageserver. /// The drain is complete when the schedulling policy returns to active. StartFill { #[arg(long)] node_id: NodeId, }, /// Cancel filling the specified pageserver and wait for `timeout` /// for the operation to be canceled. May be retried. CancelFill { #[arg(long)] node_id: NodeId, #[arg(long)] timeout: humantime::Duration, }, /// List safekeepers known to the storage controller Safekeepers {}, /// Set the scheduling policy of the specified safekeeper SafekeeperScheduling { #[arg(long)] node_id: NodeId, #[arg(long)] scheduling_policy: SkSchedulingPolicyArg, }, /// Downloads any missing heatmap layers for all shard for a given timeline DownloadHeatmapLayers { /// Tenant ID or tenant shard ID. When an unsharded tenant ID is specified, /// the operation is performed on all shards. When a sharded tenant ID is /// specified, the operation is only performed on the specified shard. #[arg(long)] tenant_shard_id: TenantShardId, #[arg(long)] timeline_id: TimelineId, /// Optional: Maximum download concurrency (default is 16) #[arg(long)] concurrency: Option<usize>, }, /// Locate safekeepers for a timeline from the storcon DB. TimelineLocate { #[arg(long)] tenant_id: TenantId, #[arg(long)] timeline_id: TimelineId, }, /// Migrate a timeline to a new set of safekeepers TimelineSafekeeperMigrate { #[arg(long)] tenant_id: TenantId, #[arg(long)] timeline_id: TimelineId, /// Example: --new-sk-set 1,2,3 #[arg(long, required = true, value_delimiter = ',')] new_sk_set: Vec<NodeId>, }, /// Abort ongoing safekeeper migration. TimelineSafekeeperMigrateAbort { #[arg(long)] tenant_id: TenantId, #[arg(long)] timeline_id: TimelineId, }, } #[derive(Parser)] #[command( author, version, about, long_about = "CLI for Storage Controller Support/Debug" )] #[command(arg_required_else_help(true))] struct Cli { #[arg(long)] /// URL to storage controller. e.g. http://127.0.0.1:1234 when using `neon_local` api: Url, #[arg(long)] /// JWT token for authenticating with storage controller. Depending on the API used, this /// should have either `pageserverapi` or `admin` scopes: for convenience, you should mint /// a token with both scopes to use with this tool. jwt: Option<String>, #[arg(long)] /// Trusted root CA certificates to use in https APIs. ssl_ca_file: Option<PathBuf>, #[command(subcommand)] command: Command, } #[derive(Debug, Clone)] struct PlacementPolicyArg(PlacementPolicy); impl FromStr for PlacementPolicyArg { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "detached" => Ok(Self(PlacementPolicy::Detached)), "secondary" => Ok(Self(PlacementPolicy::Secondary)), _ if s.starts_with("attached:") => { let mut splitter = s.split(':'); let _prefix = splitter.next().unwrap(); match splitter.next().and_then(|s| s.parse::<usize>().ok()) { Some(n) => Ok(Self(PlacementPolicy::Attached(n))), None => Err(anyhow::anyhow!( "Invalid format '{s}', a valid example is 'attached:1'" )), } } _ => Err(anyhow::anyhow!( "Unknown placement policy '{s}', try detached,secondary,attached:<n>" )), } } } #[derive(Debug, Clone)] struct SkSchedulingPolicyArg(SkSchedulingPolicy); impl FromStr for SkSchedulingPolicyArg { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { SkSchedulingPolicy::from_str(s).map(Self) } } #[derive(Debug, Clone)] struct ShardSchedulingPolicyArg(ShardSchedulingPolicy); impl FromStr for ShardSchedulingPolicyArg { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "active" => Ok(Self(ShardSchedulingPolicy::Active)), "essential" => Ok(Self(ShardSchedulingPolicy::Essential)), "pause" => Ok(Self(ShardSchedulingPolicy::Pause)), "stop" => Ok(Self(ShardSchedulingPolicy::Stop)), _ => Err(anyhow::anyhow!( "Unknown scheduling policy '{s}', try active,essential,pause,stop" )), } } } #[derive(Debug, Clone)] struct NodeAvailabilityArg(NodeAvailabilityWrapper); impl FromStr for NodeAvailabilityArg { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "active" => Ok(Self(NodeAvailabilityWrapper::Active)), "offline" => Ok(Self(NodeAvailabilityWrapper::Offline)), _ => Err(anyhow::anyhow!("Unknown availability state '{s}'")), } } } async fn wait_for_scheduling_policy<F>( client: Client, node_id: NodeId, timeout: Duration, f: F, ) -> anyhow::Result<NodeSchedulingPolicy> where F: Fn(NodeSchedulingPolicy) -> bool, { let waiter = tokio::time::timeout(timeout, async move { loop { let node = client .dispatch::<(), NodeDescribeResponse>( Method::GET, format!("control/v1/node/{node_id}"), None, ) .await?; if f(node.scheduling) { return Ok::<NodeSchedulingPolicy, mgmt_api::Error>(node.scheduling); } } }); Ok(waiter.await??) } #[tokio::main] async fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let ssl_ca_certs = match &cli.ssl_ca_file { Some(ssl_ca_file) => { let buf = tokio::fs::read(ssl_ca_file).await?; Certificate::from_pem_bundle(&buf)? } None => Vec::new(), }; let mut http_client = reqwest::Client::builder(); for ssl_ca_cert in ssl_ca_certs { http_client = http_client.add_root_certificate(ssl_ca_cert); } let http_client = http_client.build()?; let storcon_client = Client::new(http_client.clone(), cli.api.clone(), cli.jwt.clone()); let mut trimmed = cli.api.to_string(); trimmed.pop(); let vps_client = mgmt_api::Client::new(http_client.clone(), trimmed, cli.jwt.as_deref()); match cli.command { Command::NodeRegister { node_id, listen_pg_addr, listen_pg_port, listen_grpc_addr, listen_grpc_port, listen_http_addr, listen_http_port, listen_https_port, availability_zone_id, } => { storcon_client .dispatch::<_, ()>( Method::POST, "control/v1/node".to_string(), Some(NodeRegisterRequest { node_id, listen_pg_addr, listen_pg_port, listen_grpc_addr, listen_grpc_port, listen_http_addr, listen_http_port, listen_https_port, availability_zone_id: AvailabilityZone(availability_zone_id), node_ip_addr: None, }), ) .await?; } Command::TenantCreate { tenant_id } => { storcon_client .dispatch::<_, ()>( Method::POST, "v1/tenant".to_string(), Some(TenantCreateRequest { new_tenant_id: TenantShardId::unsharded(tenant_id), generation: None, shard_parameters: ShardParameters::default(), placement_policy: Some(PlacementPolicy::Attached(1)), config: TenantConfig::default(), }), ) .await?; } Command::TenantDelete { tenant_id } => { let status = vps_client .tenant_delete(TenantShardId::unsharded(tenant_id)) .await?; tracing::info!("Delete status: {}", status); } Command::Nodes {} => { let mut resp = storcon_client .dispatch::<(), Vec<NodeDescribeResponse>>( Method::GET, "control/v1/node".to_string(), None, ) .await?; resp.sort_by(|a, b| a.listen_http_addr.cmp(&b.listen_http_addr)); let mut table = comfy_table::Table::new(); table.set_header(["Id", "Hostname", "AZ", "Scheduling", "Availability"]); for node in resp { table.add_row([ format!("{}", node.id), node.listen_http_addr, node.availability_zone_id, format!("{:?}", node.scheduling), format!("{:?}", node.availability), ]); } println!("{table}"); } Command::NodeConfigure { node_id, availability, scheduling, } => { let req = NodeConfigureRequest { node_id, availability: availability.map(|a| a.0), scheduling, }; storcon_client .dispatch::<_, ()>( Method::PUT, format!("control/v1/node/{node_id}/config"), Some(req), ) .await?; } Command::Tenants { node_id: Some(node_id), } => { let describe_response = storcon_client .dispatch::<(), NodeShardResponse>( Method::GET, format!("control/v1/node/{node_id}/shards"), None, ) .await?; let shards = describe_response.shards; let mut table = comfy_table::Table::new(); table.set_header([ "Shard", "Intended Primary/Secondary", "Observed Primary/Secondary", ]); for shard in shards { table.add_row([ format!("{}", shard.tenant_shard_id), match shard.is_intended_secondary { None => "".to_string(), Some(true) => "Secondary".to_string(), Some(false) => "Primary".to_string(), }, match shard.is_observed_secondary { None => "".to_string(), Some(true) => "Secondary".to_string(), Some(false) => "Primary".to_string(), }, ]); } println!("{table}"); } Command::Tenants { node_id: None } => { // Set up output formatting let mut table = comfy_table::Table::new(); table.set_header([ "TenantId", "Preferred AZ", "ShardCount", "StripeSize", "Placement", "Scheduling", ]); // Pagination loop over listing API let mut start_after = None; const LIMIT: usize = 1000; loop { let path = match start_after { None => format!("control/v1/tenant?limit={LIMIT}"), Some(start_after) => { format!("control/v1/tenant?limit={LIMIT}&start_after={start_after}") } }; let resp = storcon_client .dispatch::<(), Vec<TenantDescribeResponse>>(Method::GET, path, None) .await?; if resp.is_empty() { // End of data reached break; } // Give some visual feedback while we're building up the table (comfy_table doesn't have // streaming output) if resp.len() >= LIMIT { eprint!("."); } start_after = Some(resp.last().unwrap().tenant_id); for tenant in resp { let shard_zero = tenant.shards.into_iter().next().unwrap(); table.add_row([ format!("{}", tenant.tenant_id), shard_zero .preferred_az_id .as_ref() .cloned() .unwrap_or("".to_string()), format!("{}", shard_zero.tenant_shard_id.shard_count.literal()), format!("{:?}", tenant.stripe_size), format!("{:?}", tenant.policy), format!("{:?}", shard_zero.scheduling_policy), ]); } } // Terminate progress dots if table.row_count() > LIMIT { eprint!(""); } println!("{table}"); } Command::TenantPolicy { tenant_id, placement, scheduling, } => { let req = TenantPolicyRequest { scheduling: scheduling.map(|s| s.0), placement: placement.map(|p| p.0), }; storcon_client .dispatch::<_, ()>( Method::PUT, format!("control/v1/tenant/{tenant_id}/policy"), Some(req), ) .await?; } Command::TenantShardSplit { tenant_id, shard_count, stripe_size, } => { let req = TenantShardSplitRequest { new_shard_count: shard_count, new_stripe_size: stripe_size.map(ShardStripeSize), }; let response = storcon_client .dispatch::<TenantShardSplitRequest, TenantShardSplitResponse>( Method::PUT, format!("control/v1/tenant/{tenant_id}/shard_split"), Some(req), ) .await?; println!( "Split tenant {} into {} shards: {}", tenant_id, shard_count, response .new_shards .iter() .map(|s| format!("{s:?}")) .collect::<Vec<_>>() .join(",") ); } Command::TenantShardMigrate { tenant_shard_id, node, prewarm, override_scheduler, } => { let migration_config = MigrationConfig { prewarm, override_scheduler, ..Default::default() }; let req = TenantShardMigrateRequest { node_id: node, origin_node_id: None, migration_config, }; match storcon_client .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>( Method::PUT, format!("control/v1/tenant/{tenant_shard_id}/migrate"), Some(req), ) .await { Err(mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg)) => { anyhow::bail!( "Migration to {node} rejected, may require `--force` ({}) ", msg ); } Err(e) => return Err(e.into()), Ok(_) => {} } watch_tenant_shard(storcon_client, tenant_shard_id, Some(node)).await?; } Command::TenantShardWatch { tenant_shard_id } => { watch_tenant_shard(storcon_client, tenant_shard_id, None).await?; } Command::TenantShardMigrateSecondary { tenant_shard_id, node, } => { let req = TenantShardMigrateRequest { node_id: node, origin_node_id: None, migration_config: MigrationConfig::default(), }; storcon_client .dispatch::<TenantShardMigrateRequest, TenantShardMigrateResponse>( Method::PUT, format!("control/v1/tenant/{tenant_shard_id}/migrate_secondary"), Some(req), ) .await?; } Command::TenantShardCancelReconcile { tenant_shard_id } => { storcon_client .dispatch::<(), ()>( Method::PUT, format!("control/v1/tenant/{tenant_shard_id}/cancel_reconcile"), None, ) .await?; } Command::SetTenantConfig { tenant_id, config } => { let tenant_conf = serde_json::from_str(&config)?; vps_client .set_tenant_config(&TenantConfigRequest { tenant_id, config: tenant_conf, }) .await?; } Command::PatchTenantConfig { tenant_id, config } => { let tenant_conf = serde_json::from_str(&config)?; vps_client .patch_tenant_config(&TenantConfigPatchRequest { tenant_id, config: tenant_conf, }) .await?; } Command::TenantDescribe { tenant_id } => { let TenantDescribeResponse { tenant_id, shards, stripe_size, policy, config, } = storcon_client .dispatch::<(), TenantDescribeResponse>( Method::GET, format!("control/v1/tenant/{tenant_id}"), None, ) .await?; let nodes = storcon_client .dispatch::<(), Vec<NodeDescribeResponse>>( Method::GET, "control/v1/node".to_string(), None, ) .await?; let nodes = nodes .into_iter() .map(|n| (n.id, n)) .collect::<HashMap<_, _>>(); println!("Tenant {tenant_id}"); let mut table = comfy_table::Table::new(); table.add_row(["Policy", &format!("{policy:?}")]); table.add_row(["Stripe size", &format!("{stripe_size:?}")]); table.add_row(["Config", &serde_json::to_string_pretty(&config).unwrap()]); println!("{table}"); println!("Shards:"); let mut table = comfy_table::Table::new(); table.set_header([ "Shard", "Attached", "Attached AZ", "Secondary", "Last error", "status", ]); for shard in shards { let secondary = shard .node_secondary .iter() .map(|n| format!("{n}")) .collect::<Vec<_>>() .join(","); let mut status_parts = Vec::new(); if shard.is_reconciling { status_parts.push("reconciling"); } if shard.is_pending_compute_notification { status_parts.push("pending_compute"); } if shard.is_splitting { status_parts.push("splitting"); } let status = status_parts.join(","); let attached_node = shard .node_attached .as_ref() .map(|id| nodes.get(id).expect("Shard references nonexistent node")); table.add_row([ format!("{}", shard.tenant_shard_id), attached_node .map(|n| format!("{} ({})", n.listen_http_addr, n.id)) .unwrap_or(String::new()), attached_node .map(|n| n.availability_zone_id.clone()) .unwrap_or(String::new()), secondary, shard.last_error, status, ]); } println!("{table}"); } Command::TenantSetPreferredAz { tenant_id, preferred_az, } => { // First learn about the tenant's shards let describe_response = storcon_client .dispatch::<(), TenantDescribeResponse>( Method::GET, format!("control/v1/tenant/{tenant_id}"), None, ) .await?; // Learn about nodes to validate the AZ ID let nodes = storcon_client .dispatch::<(), Vec<NodeDescribeResponse>>( Method::GET, "control/v1/node".to_string(), None, ) .await?; if let Some(preferred_az) = &preferred_az { let azs = nodes .into_iter() .map(|n| (n.availability_zone_id)) .collect::<HashSet<_>>(); if !azs.contains(preferred_az) { anyhow::bail!( "AZ {} not found on any node: known AZs are: {:?}", preferred_az, azs ); } } else { // Make it obvious to the user that since they've omitted an AZ, we're clearing it eprintln!("Clearing preferred AZ for tenant {tenant_id}"); } // Construct a request that modifies all the tenant's shards let req = ShardsPreferredAzsRequest { preferred_az_ids: describe_response .shards .into_iter() .map(|s| { ( s.tenant_shard_id, preferred_az.clone().map(AvailabilityZone), ) }) .collect(), }; storcon_client .dispatch::<ShardsPreferredAzsRequest, ShardsPreferredAzsResponse>( Method::PUT,
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/endpoint_storage/src/app.rs
endpoint_storage/src/app.rs
use anyhow::anyhow; use axum::body::{Body, Bytes}; use axum::response::{IntoResponse, Response}; use axum::{Router, http::StatusCode}; use endpoint_storage::{PrefixS3Path, S3Path, Storage, bad_request, internal_error, not_found, ok}; use remote_storage::TimeoutOrCancel; use remote_storage::{DownloadError, DownloadOpts, GenericRemoteStorage, RemotePath}; use std::{sync::Arc, time::SystemTime, time::UNIX_EPOCH}; use tokio_util::sync::CancellationToken; use tracing::{error, info}; use utils::backoff::retry; pub fn app(state: Arc<Storage>) -> Router<()> { use axum::routing::{delete as _delete, get as _get}; let delete_prefix = _delete(delete_prefix); // NB: On any changes do not forget to update the OpenAPI spec // in /endpoint_storage/src/openapi_spec.yml. Router::new() .route( "/{tenant_id}/{timeline_id}/{endpoint_id}/{*path}", _get(get).put(set).delete(delete), ) .route( "/{tenant_id}/{timeline_id}/{endpoint_id}", delete_prefix.clone(), ) .route("/{tenant_id}/{timeline_id}", delete_prefix.clone()) .route("/{tenant_id}", delete_prefix) .route("/metrics", _get(metrics)) .route("/status", _get(async || StatusCode::OK.into_response())) .with_state(state) } type Result = anyhow::Result<Response, Response>; type State = axum::extract::State<Arc<Storage>>; const CONTENT_TYPE: &str = "content-type"; const APPLICATION_OCTET_STREAM: &str = "application/octet-stream"; const WARN_THRESHOLD: u32 = 3; const MAX_RETRIES: u32 = 10; async fn metrics() -> Result { prometheus::TextEncoder::new() .encode_to_string(&prometheus::gather()) .map(|s| s.into_response()) .map_err(|e| internal_error(e, "/metrics", "collecting metrics")) } async fn get(S3Path { path }: S3Path, state: State) -> Result { info!(%path, "downloading"); let download_err = |err| { if let DownloadError::NotFound = err { info!(%path, %err, "downloading"); // 404 is not an issue of _this_ service return not_found(&path); } internal_error(err, &path, "downloading") }; let cancel = state.cancel.clone(); let opts = &DownloadOpts::default(); let stream = retry( async || state.storage.download(&path, opts, &cancel).await, DownloadError::is_permanent, WARN_THRESHOLD, MAX_RETRIES, "downloading", &cancel, ) .await .unwrap_or(Err(DownloadError::Cancelled)) .map_err(download_err)? .download_stream; Response::builder() .status(StatusCode::OK) .header(CONTENT_TYPE, APPLICATION_OCTET_STREAM) .body(Body::from_stream(stream)) .map_err(|e| internal_error(e, path, "reading response")) } // Best solution for files is multipart upload, but remote_storage doesn't support it, // so we can either read Bytes in memory and push at once or forward BodyDataStream to // remote_storage. The latter may seem more peformant, but BodyDataStream doesn't have a // guaranteed size() which may produce issues while uploading to s3. // So, currently we're going with an in-memory copy plus a boundary to prevent uploading // very large files. async fn set(S3Path { path }: S3Path, state: State, bytes: Bytes) -> Result { info!(%path, "uploading"); let request_len = bytes.len(); let max_len = state.max_upload_file_limit; if request_len > max_len { return Err(bad_request( anyhow!("File size {request_len} exceeds max {max_len}"), "uploading", )); } let cancel = state.cancel.clone(); let fun = async || { let stream = bytes_to_stream(bytes.clone()); state .storage .upload(stream, request_len, &path, None, &cancel) .await }; retry( fun, TimeoutOrCancel::caused_by_cancel, WARN_THRESHOLD, MAX_RETRIES, "uploading", &cancel, ) .await .unwrap_or(Err(anyhow!("uploading cancelled"))) .map_err(|e| internal_error(e, path, "reading response"))?; Ok(ok()) } async fn delete(S3Path { path }: S3Path, state: State) -> Result { info!(%path, "deleting"); let cancel = state.cancel.clone(); retry( async || state.storage.delete(&path, &cancel).await, TimeoutOrCancel::caused_by_cancel, WARN_THRESHOLD, MAX_RETRIES, "deleting", &cancel, ) .await .unwrap_or(Err(anyhow!("deleting cancelled"))) .map_err(|e| internal_error(e, path, "deleting"))?; Ok(ok()) } async fn delete_prefix(PrefixS3Path { path }: PrefixS3Path, state: State) -> Result { info!(%path, "deleting prefix"); let cancel = state.cancel.clone(); retry( async || state.storage.delete_prefix(&path, &cancel).await, TimeoutOrCancel::caused_by_cancel, WARN_THRESHOLD, MAX_RETRIES, "deleting prefix", &cancel, ) .await .unwrap_or(Err(anyhow!("deleting prefix cancelled"))) .map_err(|e| internal_error(e, path, "deleting prefix"))?; Ok(ok()) } pub async fn check_storage_permissions( client: &GenericRemoteStorage, cancel: CancellationToken, ) -> anyhow::Result<()> { info!("storage permissions check"); // as_nanos() as multiple instances proxying same bucket may be started at once let now = SystemTime::now() .duration_since(UNIX_EPOCH)? .as_nanos() .to_string(); let path = RemotePath::from_string(&format!("write_access_{now}"))?; info!(%path, "uploading"); let body = now.to_string(); let stream = bytes_to_stream(Bytes::from(body.clone())); client .upload(stream, body.len(), &path, None, &cancel) .await?; use tokio::io::AsyncReadExt; info!(%path, "downloading"); let download_opts = DownloadOpts { kind: remote_storage::DownloadKind::Small, ..Default::default() }; let mut body_read_buf = Vec::new(); let stream = client .download(&path, &download_opts, &cancel) .await? .download_stream; tokio_util::io::StreamReader::new(stream) .read_to_end(&mut body_read_buf) .await?; let body_read = String::from_utf8(body_read_buf)?; if body != body_read { error!(%body, %body_read, "File contents do not match"); anyhow::bail!("Read back file doesn't match original") } info!(%path, "removing"); client.delete(&path, &cancel).await } fn bytes_to_stream(bytes: Bytes) -> impl futures::Stream<Item = std::io::Result<Bytes>> { futures::stream::once(futures::future::ready(Ok(bytes))) } #[cfg(test)] mod tests { use super::*; use axum::{body::Body, extract::Request, response::Response}; use http_body_util::BodyExt; use itertools::iproduct; use std::env::var; use std::sync::Arc; use std::time::Duration; use test_log::test as testlog; use tower::{Service, util::ServiceExt}; use utils::id::{TenantId, TimelineId}; // see libs/remote_storage/tests/test_real_s3.rs const REAL_S3_ENV: &str = "ENABLE_REAL_S3_REMOTE_STORAGE"; const REAL_S3_BUCKET: &str = "REMOTE_STORAGE_S3_BUCKET"; const REAL_S3_REGION: &str = "REMOTE_STORAGE_S3_REGION"; async fn proxy() -> (Storage, Option<camino_tempfile::Utf8TempDir>) { let cancel = CancellationToken::new(); let (dir, storage) = if var(REAL_S3_ENV).is_err() { // tests execute in parallel and we need a new directory for each of them let dir = camino_tempfile::tempdir().unwrap(); let fs = remote_storage::LocalFs::new(dir.path().into(), Duration::from_secs(5)).unwrap(); (Some(dir), GenericRemoteStorage::LocalFs(fs)) } else { // test_real_s3::create_s3_client is hard to reference, reimplementing here let millis = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_millis(); use rand::Rng; let random = rand::rng().random::<u32>(); let s3_config = remote_storage::S3Config { bucket_name: var(REAL_S3_BUCKET).unwrap(), bucket_region: var(REAL_S3_REGION).unwrap(), prefix_in_bucket: Some(format!("test_{millis}_{random:08x}/")), endpoint: None, concurrency_limit: std::num::NonZeroUsize::new(100).unwrap(), max_keys_per_list_response: None, upload_storage_class: None, }; let bucket = remote_storage::S3Bucket::new(&s3_config, Duration::from_secs(1)) .await .unwrap(); (None, GenericRemoteStorage::AwsS3(Arc::new(bucket))) }; let proxy = Storage { auth: endpoint_storage::JwtAuth::new(TEST_PUB_KEY_ED25519).unwrap(), storage, cancel: cancel.clone(), max_upload_file_limit: usize::MAX, }; check_storage_permissions(&proxy.storage, cancel) .await .unwrap(); (proxy, dir) } // see libs/utils/src/auth.rs const TEST_PUB_KEY_ED25519: &[u8] = b" -----BEGIN PUBLIC KEY----- MCowBQYDK2VwAyEARYwaNBayR+eGI0iXB4s3QxE3Nl2g1iWbr6KtLWeVD/w= -----END PUBLIC KEY----- "; const TEST_PRIV_KEY_ED25519: &[u8] = br#" -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEID/Drmc1AA6U/znNRWpF3zEGegOATQxfkdWxitcOMsIH -----END PRIVATE KEY----- "#; async fn request(req: Request<Body>) -> Response<Body> { let (proxy, _) = proxy().await; app(Arc::new(proxy)) .into_service() .oneshot(req) .await .unwrap() } #[testlog(tokio::test)] async fn status() { let res = Request::builder() .uri("/status") .body(Body::empty()) .map(request) .unwrap() .await; assert_eq!(res.status(), StatusCode::OK); } fn routes() -> impl Iterator<Item = (&'static str, &'static str)> { iproduct!( vec!["/1", "/1/2", "/1/2/3", "/1/2/3/4"], vec!["GET", "PUT", "DELETE"] ) } #[testlog(tokio::test)] async fn no_token() { for (uri, method) in routes() { info!(%uri, %method); let res = Request::builder() .uri(uri) .method(method) .body(Body::empty()) .map(request) .unwrap() .await; assert!(matches!( res.status(), StatusCode::METHOD_NOT_ALLOWED | StatusCode::BAD_REQUEST )); } } #[testlog(tokio::test)] async fn invalid_token() { for (uri, method) in routes() { info!(%uri, %method); let status = Request::builder() .uri(uri) .header("Authorization", "Bearer 123") .method(method) .body(Body::empty()) .map(request) .unwrap() .await; assert!(matches!( status.status(), StatusCode::METHOD_NOT_ALLOWED | StatusCode::BAD_REQUEST )); } } const TENANT_ID: TenantId = TenantId::from_array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6]); const TIMELINE_ID: TimelineId = TimelineId::from_array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 7]); const ENDPOINT_ID: &str = "ep-winter-frost-a662z3vg"; fn token() -> String { let claims = endpoint_storage::claims::EndpointStorageClaims { tenant_id: TENANT_ID, timeline_id: TIMELINE_ID, endpoint_id: ENDPOINT_ID.into(), exp: u64::MAX, }; let key = jsonwebtoken::EncodingKey::from_ed_pem(TEST_PRIV_KEY_ED25519).unwrap(); let header = jsonwebtoken::Header::new(endpoint_storage::VALIDATION_ALGO); jsonwebtoken::encode(&header, &claims, &key).unwrap() } #[testlog(tokio::test)] async fn unauthorized() { let (proxy, _) = proxy().await; let mut app = app(Arc::new(proxy)).into_service(); let token = token(); let args = itertools::iproduct!( vec![TENANT_ID.to_string(), TenantId::generate().to_string()], vec![TIMELINE_ID.to_string(), TimelineId::generate().to_string()], vec![ENDPOINT_ID, "ep-ololo"] ) // first one is fully valid path, second path is valid for GET as // read paths may have different endpoint if tenant and timeline matches // (needed for prewarming RO->RW replica) .skip(2); for ((uri, method), (tenant, timeline, endpoint)) in iproduct!(routes(), args) { info!(%uri, %method, %tenant, %timeline, %endpoint); let request = Request::builder() .uri(format!("/{tenant}/{timeline}/{endpoint}/sub/path/key")) .method(method) .header("Authorization", format!("Bearer {token}")) .body(Body::empty()) .unwrap(); let status = ServiceExt::ready(&mut app) .await .unwrap() .call(request) .await .unwrap() .status(); assert_eq!(status, StatusCode::UNAUTHORIZED); } } #[testlog(tokio::test)] async fn method_not_allowed() { let token = token(); let iter = iproduct!(vec!["", "/.."], vec!["GET", "PUT"]); for (key, method) in iter { let status = Request::builder() .uri(format!("/{TENANT_ID}/{TIMELINE_ID}/{ENDPOINT_ID}{key}")) .method(method) .header("Authorization", format!("Bearer {token}")) .body(Body::empty()) .map(request) .unwrap() .await .status(); assert!(matches!( status, StatusCode::BAD_REQUEST | StatusCode::METHOD_NOT_ALLOWED )); } } async fn requests_chain( chain: impl Iterator<Item = (String, &str, &'static str, StatusCode, bool)>, token: impl Fn(&str) -> String, ) { let (proxy, _) = proxy().await; let mut app = app(Arc::new(proxy)).into_service(); for (uri, method, body, expected_status, compare_body) in chain { info!(%uri, %method, %body, %expected_status); let bearer = format!("Bearer {}", token(&uri)); let request = Request::builder() .uri(uri) .method(method) .header("Authorization", &bearer) .body(Body::from(body)) .unwrap(); let response = ServiceExt::ready(&mut app) .await .unwrap() .call(request) .await .unwrap(); assert_eq!(response.status(), expected_status); if !compare_body { continue; } let read_body = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(body, read_body); } } #[testlog(tokio::test)] async fn metrics() { let uri = format!("/{TENANT_ID}/{TIMELINE_ID}/{ENDPOINT_ID}/key"); let req = vec![ (uri.clone(), "PUT", "body", StatusCode::OK, false), (uri.clone(), "DELETE", "", StatusCode::OK, false), ]; requests_chain(req.into_iter(), |_| token()).await; let res = Request::builder() .uri("/metrics") .body(Body::empty()) .map(request) .unwrap() .await; assert_eq!(res.status(), StatusCode::OK); let body = res.into_body().collect().await.unwrap().to_bytes(); let body = String::from_utf8_lossy(&body); tracing::debug!(%body); // Storage metrics are not gathered for LocalFs if var(REAL_S3_ENV).is_ok() { assert!(body.contains("remote_storage_s3_deleted_objects_total")); } #[cfg(target_os = "linux")] assert!(body.contains("process_threads")); } #[testlog(tokio::test)] async fn insert_retrieve_remove() { let uri = format!("/{TENANT_ID}/{TIMELINE_ID}/{ENDPOINT_ID}/key"); let chain = vec![ (uri.clone(), "GET", "", StatusCode::NOT_FOUND, false), (uri.clone(), "PUT", "пыщьпыщь", StatusCode::OK, false), (uri.clone(), "GET", "пыщьпыщь", StatusCode::OK, true), (uri.clone(), "DELETE", "", StatusCode::OK, false), (uri, "GET", "", StatusCode::NOT_FOUND, false), ]; requests_chain(chain.into_iter(), |_| token()).await; } #[testlog(tokio::test)] async fn read_other_endpoint_data() { let uri = format!("/{TENANT_ID}/{TIMELINE_ID}/other_endpoint/key"); let chain = vec![ (uri.clone(), "GET", "", StatusCode::NOT_FOUND, false), (uri.clone(), "PUT", "", StatusCode::UNAUTHORIZED, false), ]; requests_chain(chain.into_iter(), |_| token()).await; } fn delete_prefix_token(uri: &str) -> String { let parts = uri.split("/").collect::<Vec<&str>>(); let claims = endpoint_storage::claims::DeletePrefixClaims { tenant_id: parts.get(1).map(|c| c.parse().unwrap()).unwrap(), timeline_id: parts.get(2).map(|c| c.parse().unwrap()), endpoint_id: parts.get(3).map(ToString::to_string), exp: u64::MAX, }; let key = jsonwebtoken::EncodingKey::from_ed_pem(TEST_PRIV_KEY_ED25519).unwrap(); let header = jsonwebtoken::Header::new(endpoint_storage::VALIDATION_ALGO); jsonwebtoken::encode(&header, &claims, &key).unwrap() } // Can't use single digit numbers as they won't be validated as TimelineId and EndpointId #[testlog(tokio::test)] async fn delete_prefix() { let tenant_id = TenantId::from_array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).to_string(); let t2 = TimelineId::from_array([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let t3 = TimelineId::from_array([3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let t4 = TimelineId::from_array([4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); let f = |timeline, path| format!("/{tenant_id}/{timeline}{path}"); // Why extra slash in string literals? Axum is weird with URIs: // /1/2 and 1/2/ match different routes, thus first yields OK and second NOT_FOUND // as it matches /tenant/timeline/endpoint, see https://stackoverflow.com/a/75355932 // The cost of removing trailing slash is suprisingly hard: // * Add tower dependency with NormalizePath layer // * wrap Router<()> in this layer https://github.com/tokio-rs/axum/discussions/2377 // * Rewrite make_service() -> into_make_service() // * Rewrite oneshot() (not available for NormalizePath) // I didn't manage to get it working correctly let chain = vec![ // create 1/2/3/4, 1/2/3/5, delete prefix 1/2/3 -> empty (f(t2, "/3/4"), "PUT", "", StatusCode::OK, false), (f(t2, "/3/4"), "PUT", "", StatusCode::OK, false), // we can override file contents (f(t2, "/3/5"), "PUT", "", StatusCode::OK, false), (f(t2, "/3"), "DELETE", "", StatusCode::OK, false), (f(t2, "/3/4"), "GET", "", StatusCode::NOT_FOUND, false), (f(t2, "/3/5"), "GET", "", StatusCode::NOT_FOUND, false), // create 1/2/3/4, 1/2/5/6, delete prefix 1/2/3 -> 1/2/5/6 (f(t2, "/3/4"), "PUT", "", StatusCode::OK, false), (f(t2, "/5/6"), "PUT", "", StatusCode::OK, false), (f(t2, "/3"), "DELETE", "", StatusCode::OK, false), (f(t2, "/3/4"), "GET", "", StatusCode::NOT_FOUND, false), (f(t2, "/5/6"), "GET", "", StatusCode::OK, false), // create 1/2/3/4, 1/2/7/8, delete prefix 1/2 -> empty (f(t2, "/3/4"), "PUT", "", StatusCode::OK, false), (f(t2, "/7/8"), "PUT", "", StatusCode::OK, false), (f(t2, ""), "DELETE", "", StatusCode::OK, false), (f(t2, "/3/4"), "GET", "", StatusCode::NOT_FOUND, false), (f(t2, "/7/8"), "GET", "", StatusCode::NOT_FOUND, false), // create 1/2/3/4, 1/2/5/6, 1/3/8/9, delete prefix 1/2/3 -> 1/2/5/6, 1/3/8/9 (f(t2, "/3/4"), "PUT", "", StatusCode::OK, false), (f(t2, "/5/6"), "PUT", "", StatusCode::OK, false), (f(t3, "/8/9"), "PUT", "", StatusCode::OK, false), (f(t2, "/3"), "DELETE", "", StatusCode::OK, false), (f(t2, "/3/4"), "GET", "", StatusCode::NOT_FOUND, false), (f(t2, "/5/6"), "GET", "", StatusCode::OK, false), (f(t3, "/8/9"), "GET", "", StatusCode::OK, false), // create 1/4/5/6, delete prefix 1/2 -> 1/3/8/9, 1/4/5/6 (f(t4, "/5/6"), "PUT", "", StatusCode::OK, false), (f(t2, ""), "DELETE", "", StatusCode::OK, false), (f(t2, "/3/4"), "GET", "", StatusCode::NOT_FOUND, false), (f(t2, "/5/6"), "GET", "", StatusCode::NOT_FOUND, false), (f(t3, "/8/9"), "GET", "", StatusCode::OK, false), (f(t4, "/5/6"), "GET", "", StatusCode::OK, false), // delete prefix 1 -> empty (format!("/{tenant_id}"), "DELETE", "", StatusCode::OK, false), (f(t2, "/3/4"), "GET", "", StatusCode::NOT_FOUND, false), (f(t2, "/5/6"), "GET", "", StatusCode::NOT_FOUND, false), (f(t3, "/8/9"), "GET", "", StatusCode::NOT_FOUND, false), (f(t4, "/5/6"), "GET", "", StatusCode::NOT_FOUND, false), ]; requests_chain(chain.into_iter(), delete_prefix_token).await; } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/endpoint_storage/src/lib.rs
endpoint_storage/src/lib.rs
pub mod claims; use crate::claims::{DeletePrefixClaims, EndpointStorageClaims}; use anyhow::Result; use axum::extract::{FromRequestParts, Path}; use axum::response::{IntoResponse, Response}; use axum::{RequestPartsExt, http::StatusCode, http::request::Parts}; use axum_extra::TypedHeader; use axum_extra::headers::{Authorization, authorization::Bearer}; use camino::Utf8PathBuf; use jsonwebtoken::{DecodingKey, Validation}; use remote_storage::{GenericRemoteStorage, RemotePath}; use serde::{Deserialize, Serialize}; use std::fmt::Display; use std::result::Result as StdResult; use std::sync::Arc; use tokio_util::sync::CancellationToken; use tracing::{debug, error}; use utils::id::{EndpointId, TenantId, TimelineId}; // simplified version of utils::auth::JwtAuth pub struct JwtAuth { decoding_key: DecodingKey, validation: Validation, } pub const VALIDATION_ALGO: jsonwebtoken::Algorithm = jsonwebtoken::Algorithm::EdDSA; impl JwtAuth { pub fn new(key: &[u8]) -> Result<Self> { Ok(Self { decoding_key: DecodingKey::from_ed_pem(key)?, validation: Validation::new(VALIDATION_ALGO), }) } pub fn decode<T: serde::de::DeserializeOwned>(&self, token: &str) -> Result<T> { Ok(jsonwebtoken::decode(token, &self.decoding_key, &self.validation).map(|t| t.claims)?) } } fn normalize_key(key: &str) -> StdResult<Utf8PathBuf, String> { let key = clean_utf8(&Utf8PathBuf::from(key)); if key.starts_with("..") || key == "." || key == "/" { return Err(format!("invalid key {key}")); } match key.strip_prefix("/").map(Utf8PathBuf::from) { Ok(p) => Ok(p), _ => Ok(key), } } // Copied from path_clean crate with PathBuf->Utf8PathBuf fn clean_utf8(path: &camino::Utf8Path) -> Utf8PathBuf { use camino::Utf8Component as Comp; let mut out = Vec::new(); for comp in path.components() { match comp { Comp::CurDir => (), Comp::ParentDir => match out.last() { Some(Comp::RootDir) => (), Some(Comp::Normal(_)) => { out.pop(); } None | Some(Comp::CurDir) | Some(Comp::ParentDir) | Some(Comp::Prefix(_)) => { out.push(comp) } }, comp => out.push(comp), } } if !out.is_empty() { out.iter().collect() } else { Utf8PathBuf::from(".") } } pub struct Storage { pub auth: JwtAuth, pub storage: GenericRemoteStorage, pub cancel: CancellationToken, pub max_upload_file_limit: usize, } #[derive(Deserialize, Serialize)] struct KeyRequest { tenant_id: TenantId, timeline_id: TimelineId, endpoint_id: EndpointId, path: String, } #[derive(Deserialize, Serialize, PartialEq)] struct PrefixKeyRequest { tenant_id: TenantId, timeline_id: Option<TimelineId>, endpoint_id: Option<EndpointId>, } #[derive(Debug, PartialEq)] pub struct S3Path { pub path: RemotePath, } impl TryFrom<&KeyRequest> for S3Path { type Error = String; fn try_from(req: &KeyRequest) -> StdResult<Self, Self::Error> { let KeyRequest { tenant_id, timeline_id, endpoint_id, path, } = &req; let prefix = format!("{tenant_id}/{timeline_id}/{endpoint_id}",); let path = Utf8PathBuf::from(prefix).join(normalize_key(path)?); let path = RemotePath::new(&path).unwrap(); // unwrap() because the path is already relative Ok(S3Path { path }) } } fn unauthorized(route: impl Display, claims: impl Display) -> Response { debug!(%route, %claims, "route doesn't match claims"); StatusCode::UNAUTHORIZED.into_response() } pub fn bad_request(err: impl Display, desc: &'static str) -> Response { debug!(%err, desc); (StatusCode::BAD_REQUEST, err.to_string()).into_response() } pub fn ok() -> Response { StatusCode::OK.into_response() } pub fn internal_error(err: impl Display, path: impl Display, desc: &'static str) -> Response { error!(%err, %path, desc); StatusCode::INTERNAL_SERVER_ERROR.into_response() } pub fn not_found(key: impl ToString) -> Response { (StatusCode::NOT_FOUND, key.to_string()).into_response() } impl FromRequestParts<Arc<Storage>> for S3Path { type Rejection = Response; async fn from_request_parts( parts: &mut Parts, state: &Arc<Storage>, ) -> Result<Self, Self::Rejection> { let Path(path): Path<KeyRequest> = parts .extract() .await .map_err(|e| bad_request(e, "invalid route"))?; let TypedHeader(Authorization(bearer)) = parts .extract::<TypedHeader<Authorization<Bearer>>>() .await .map_err(|e| bad_request(e, "invalid token"))?; let claims: EndpointStorageClaims = state .auth .decode(bearer.token()) .map_err(|e| bad_request(e, "decoding token"))?; // Read paths may have different endpoint ids. For readonly -> readwrite replica // prewarming, endpoint must read other endpoint's data. let endpoint_id = if parts.method == axum::http::Method::GET { claims.endpoint_id.clone() } else { path.endpoint_id.clone() }; let route = EndpointStorageClaims { tenant_id: path.tenant_id, timeline_id: path.timeline_id, endpoint_id, exp: claims.exp, }; if route != claims { return Err(unauthorized(route, claims)); } (&path) .try_into() .map_err(|e| bad_request(e, "invalid route")) } } #[derive(Debug, PartialEq)] pub struct PrefixS3Path { pub path: RemotePath, } impl From<&DeletePrefixClaims> for PrefixS3Path { fn from(path: &DeletePrefixClaims) -> Self { let timeline_id = path .timeline_id .as_ref() .map(ToString::to_string) .unwrap_or("".to_string()); let endpoint_id = path .endpoint_id .as_ref() .map(ToString::to_string) .unwrap_or("".to_string()); let path = Utf8PathBuf::from(path.tenant_id.to_string()) .join(timeline_id) .join(endpoint_id); let path = RemotePath::new(&path).unwrap(); // unwrap() because the path is already relative PrefixS3Path { path } } } impl FromRequestParts<Arc<Storage>> for PrefixS3Path { type Rejection = Response; async fn from_request_parts( parts: &mut Parts, state: &Arc<Storage>, ) -> Result<Self, Self::Rejection> { let Path(path) = parts .extract::<Path<PrefixKeyRequest>>() .await .map_err(|e| bad_request(e, "invalid route"))?; let TypedHeader(Authorization(bearer)) = parts .extract::<TypedHeader<Authorization<Bearer>>>() .await .map_err(|e| bad_request(e, "invalid token"))?; let claims: DeletePrefixClaims = state .auth .decode(bearer.token()) .map_err(|e| bad_request(e, "invalid token"))?; let route = DeletePrefixClaims { tenant_id: path.tenant_id, timeline_id: path.timeline_id, endpoint_id: path.endpoint_id, exp: claims.exp, }; if route != claims { return Err(unauthorized(route, claims)); } Ok((&route).into()) } } #[cfg(test)] mod tests { use super::*; #[test] fn normalize_key() { let f = super::normalize_key; assert_eq!(f("hello/world/..").unwrap(), Utf8PathBuf::from("hello")); assert_eq!( f("ololo/1/../../not_ololo").unwrap(), Utf8PathBuf::from("not_ololo") ); assert!(f("ololo/1/../../../").is_err()); assert!(f(".").is_err()); assert!(f("../").is_err()); assert!(f("").is_err()); assert_eq!(f("/1/2/3").unwrap(), Utf8PathBuf::from("1/2/3")); assert!(f("/1/2/3/../../../").is_err()); assert!(f("/1/2/3/../../../../").is_err()); } const TENANT_ID: TenantId = TenantId::from_array([1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6]); const TIMELINE_ID: TimelineId = TimelineId::from_array([1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 7]); const ENDPOINT_ID: &str = "ep-winter-frost-a662z3vg"; #[test] fn s3_path() { let auth = EndpointStorageClaims { tenant_id: TENANT_ID, timeline_id: TIMELINE_ID, endpoint_id: ENDPOINT_ID.into(), exp: u64::MAX, }; let s3_path = |key| { let path = &format!("{TENANT_ID}/{TIMELINE_ID}/{ENDPOINT_ID}/{key}"); let path = RemotePath::from_string(path).unwrap(); S3Path { path } }; let path = "cache_key".to_string(); let mut key_path = KeyRequest { path, tenant_id: auth.tenant_id, timeline_id: auth.timeline_id, endpoint_id: auth.endpoint_id, }; assert_eq!(S3Path::try_from(&key_path).unwrap(), s3_path(key_path.path)); key_path.path = "we/can/have/nested/paths".to_string(); assert_eq!(S3Path::try_from(&key_path).unwrap(), s3_path(key_path.path)); key_path.path = "../error/hello/../".to_string(); assert!(S3Path::try_from(&key_path).is_err()); } #[test] fn prefix_s3_path() { let mut path = DeletePrefixClaims { tenant_id: TENANT_ID, timeline_id: None, endpoint_id: None, exp: 0, }; let prefix_path = |s: String| RemotePath::from_string(&s).unwrap(); assert_eq!( PrefixS3Path::from(&path).path, prefix_path(format!("{TENANT_ID}")) ); path.timeline_id = Some(TIMELINE_ID); assert_eq!( PrefixS3Path::from(&path).path, prefix_path(format!("{TENANT_ID}/{TIMELINE_ID}")) ); path.endpoint_id = Some(ENDPOINT_ID.into()); assert_eq!( PrefixS3Path::from(&path).path, prefix_path(format!("{TENANT_ID}/{TIMELINE_ID}/{ENDPOINT_ID}")) ); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/endpoint_storage/src/claims.rs
endpoint_storage/src/claims.rs
use serde::{Deserialize, Serialize}; use std::fmt::Display; use utils::id::{EndpointId, TenantId, TimelineId}; /// Claims to add, remove, or retrieve endpoint data. Used by compute_ctl #[derive(Deserialize, Serialize, PartialEq)] pub struct EndpointStorageClaims { pub tenant_id: TenantId, pub timeline_id: TimelineId, pub endpoint_id: EndpointId, pub exp: u64, } /// Claims to remove tenant, timeline, or endpoint data. Used by control plane #[derive(Deserialize, Serialize, PartialEq)] pub struct DeletePrefixClaims { pub tenant_id: TenantId, /// None when tenant is deleted (endpoint_id is also None in this case) pub timeline_id: Option<TimelineId>, /// None when timeline is deleted pub endpoint_id: Option<EndpointId>, pub exp: u64, } impl Display for EndpointStorageClaims { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "EndpointClaims(tenant_id={} timeline_id={} endpoint_id={} exp={})", self.tenant_id, self.timeline_id, self.endpoint_id, self.exp ) } } impl Display for DeletePrefixClaims { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "DeletePrefixClaims(tenant_id={} timeline_id={} endpoint_id={}, exp={})", self.tenant_id, self.timeline_id .as_ref() .map(ToString::to_string) .unwrap_or("".to_string()), self.endpoint_id .as_ref() .map(ToString::to_string) .unwrap_or("".to_string()), self.exp ) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/endpoint_storage/src/main.rs
endpoint_storage/src/main.rs
//! `endpoint_storage` is a service which provides API for uploading and downloading //! files. It is used by compute and control plane for accessing LFC prewarm data. //! This service is deployed either as a separate component or as part of compute image //! for large computes. mod app; use anyhow::Context; use clap::Parser; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use tracing::info; use utils::logging; //see set() const fn max_upload_file_limit() -> usize { 100 * 1024 * 1024 } const fn listen() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 51243) } #[derive(Parser)] struct Args { #[arg(exclusive = true)] config_file: Option<String>, #[arg(long, default_value = "false", requires = "config")] /// to allow testing k8s helm chart where we don't have s3 credentials no_s3_check_on_startup: bool, #[arg(long, value_name = "FILE")] /// inline config mode for k8s helm chart config: Option<String>, } #[derive(serde::Deserialize)] struct Config { #[serde(default = "listen")] listen: std::net::SocketAddr, pemfile: camino::Utf8PathBuf, #[serde(flatten)] storage_kind: remote_storage::TypedRemoteStorageKind, #[serde(default = "max_upload_file_limit")] max_upload_file_limit: usize, } #[tokio::main] async fn main() -> anyhow::Result<()> { logging::init( logging::LogFormat::Plain, logging::TracingErrorLayerEnablement::EnableWithRustLogFilter, logging::Output::Stdout, )?; let args = Args::parse(); let config: Config = if let Some(config_path) = args.config_file { info!("Reading config from {config_path}"); let config = std::fs::read_to_string(config_path)?; serde_json::from_str(&config).context("parsing config")? } else if let Some(config) = args.config { info!("Reading inline config"); serde_json::from_str(&config).context("parsing config")? } else { anyhow::bail!("Supply either config file path or --config=inline-config"); }; info!("Reading pemfile from {}", config.pemfile.clone()); let pemfile = std::fs::read(config.pemfile.clone())?; info!("Loading public key from {}", config.pemfile.clone()); let auth = endpoint_storage::JwtAuth::new(&pemfile)?; let listener = tokio::net::TcpListener::bind(config.listen).await.unwrap(); info!("listening on {}", listener.local_addr().unwrap()); let storage = remote_storage::GenericRemoteStorage::from_storage_kind(config.storage_kind).await?; let cancel = tokio_util::sync::CancellationToken::new(); if !args.no_s3_check_on_startup { app::check_storage_permissions(&storage, cancel.clone()).await?; } let proxy = std::sync::Arc::new(endpoint_storage::Storage { auth, storage, cancel: cancel.clone(), max_upload_file_limit: config.max_upload_file_limit, }); tokio::spawn(utils::signals::signal_handler(cancel.clone())); axum::serve(listener, app::app(proxy)) .with_graceful_shutdown(async move { cancel.cancelled().await }) .await?; Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/pageserver_physical_gc.rs
storage_scrubber/src/pageserver_physical_gc.rs
use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use std::time::Duration; use async_stream::try_stream; use futures::future::Either; use futures_util::{StreamExt, TryStreamExt}; use pageserver::tenant::IndexPart; use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata; use pageserver::tenant::remote_timeline_client::manifest::OffloadedTimelineManifest; use pageserver::tenant::remote_timeline_client::{ parse_remote_index_path, parse_remote_tenant_manifest_path, remote_layer_path, }; use pageserver::tenant::storage_layer::LayerName; use pageserver_api::controller_api::TenantDescribeResponse; use pageserver_api::shard::{ShardIndex, TenantShardId}; use remote_storage::{GenericRemoteStorage, ListingObject, RemotePath}; use reqwest::Method; use serde::Serialize; use storage_controller_client::control_api; use tokio_util::sync::CancellationToken; use tracing::{Instrument, info_span}; use utils::backoff; use utils::generation::Generation; use utils::id::{TenantId, TenantTimelineId}; use crate::checks::{ BlobDataParseResult, ListTenantManifestResult, RemoteTenantManifestInfo, list_tenant_manifests, list_timeline_blobs, }; use crate::metadata_stream::{stream_tenant_timelines, stream_tenants}; use crate::{BucketConfig, MAX_RETRIES, NodeKind, RootTarget, TenantShardTimelineId, init_remote}; #[derive(Serialize, Default)] pub struct GcSummary { indices_deleted: usize, tenant_manifests_deleted: usize, remote_storage_errors: usize, controller_api_errors: usize, ancestor_layers_deleted: usize, } impl GcSummary { fn merge(&mut self, other: Self) { let Self { indices_deleted, tenant_manifests_deleted, remote_storage_errors, ancestor_layers_deleted, controller_api_errors, } = other; self.indices_deleted += indices_deleted; self.tenant_manifests_deleted += tenant_manifests_deleted; self.remote_storage_errors += remote_storage_errors; self.ancestor_layers_deleted += ancestor_layers_deleted; self.controller_api_errors += controller_api_errors; } } #[derive(clap::ValueEnum, Debug, Clone, Copy)] pub enum GcMode { // Delete nothing DryRun, // Enable only removing old-generation indices IndicesOnly, // Enable all forms of GC Full, } impl std::fmt::Display for GcMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { GcMode::DryRun => write!(f, "dry-run"), GcMode::IndicesOnly => write!(f, "indices-only"), GcMode::Full => write!(f, "full"), } } } mod refs { use super::*; // Map of cross-shard layer references, giving a refcount for each layer in each shard that is referenced by some other // shard in the same tenant. This is sparse! The vast majority of timelines will have no cross-shard refs, and those that // do have cross shard refs should eventually drop most of them via compaction. // // In our inner map type, the TTID in the key is shard-agnostic, and the ShardIndex in the value refers to the _ancestor // which is is referenced_. #[derive(Default)] pub(super) struct AncestorRefs( BTreeMap<TenantTimelineId, HashMap<(ShardIndex, LayerName), usize>>, ); impl AncestorRefs { /// Insert references for layers discovered in a particular shard-timeline that refer to an ancestral shard-timeline. pub(super) fn update( &mut self, ttid: TenantShardTimelineId, layers: Vec<(LayerName, LayerFileMetadata)>, ) { let ttid_refs = self.0.entry(ttid.as_tenant_timeline_id()).or_default(); for (layer_name, layer_metadata) in layers { // Increment refcount of this layer in the ancestor shard *(ttid_refs .entry((layer_metadata.shard, layer_name)) .or_default()) += 1; } } /// For a particular TTID, return the map of all ancestor layers referenced by a descendent to their refcount /// /// The `ShardIndex` in the result's key is the index of the _ancestor_, not the descendent. pub(super) fn get_ttid_refcounts( &self, ttid: &TenantTimelineId, ) -> Option<&HashMap<(ShardIndex, LayerName), usize>> { self.0.get(ttid) } } } use refs::AncestorRefs; // As we see shards for a tenant, acccumulate knowledge needed for cross-shard GC: // - Are there any ancestor shards? // - Are there any refs to ancestor shards' layers? #[derive(Default)] struct TenantRefAccumulator { shards_seen: HashMap<TenantId, BTreeSet<ShardIndex>>, // For each shard that has refs to an ancestor's layers, the set of ancestor layers referred to ancestor_ref_shards: AncestorRefs, } impl TenantRefAccumulator { fn update(&mut self, ttid: TenantShardTimelineId, index_part: &IndexPart) { let this_shard_idx = ttid.tenant_shard_id.to_index(); self.shards_seen .entry(ttid.tenant_shard_id.tenant_id) .or_default() .insert(this_shard_idx); let mut ancestor_refs = Vec::new(); for (layer_name, layer_metadata) in &index_part.layer_metadata { if layer_metadata.shard != this_shard_idx { // This is a reference from this shard to a layer in an ancestor shard: we must track this // as a marker to not GC this layer from the parent. ancestor_refs.push((layer_name.clone(), layer_metadata.clone())); } } tracing::info!(%ttid, "Found {} ancestor refs", ancestor_refs.len()); self.ancestor_ref_shards.update(ttid, ancestor_refs); } /// Consume Self and return a vector of ancestor tenant shards that should be GC'd, and map of referenced ancestor layers to preserve async fn into_gc_ancestors( self, controller_client: &control_api::Client, summary: &mut GcSummary, ) -> (Vec<TenantShardId>, AncestorRefs) { let mut ancestors_to_gc = Vec::new(); for (tenant_id, shard_indices) in self.shards_seen { // Find the highest shard count let latest_count = shard_indices .iter() .map(|i| i.shard_count) .max() .expect("Always at least one shard"); let mut shard_indices = shard_indices.iter().collect::<Vec<_>>(); let (mut latest_shards, ancestor_shards) = { let at = itertools::partition(&mut shard_indices, |i| i.shard_count == latest_count); (shard_indices[0..at].to_owned(), &shard_indices[at..]) }; // Sort shards, as we will later compare them with a sorted list from the controller latest_shards.sort(); // Check that we have a complete view of the latest shard count: this should always be the case unless we happened // to scan the S3 bucket halfway through a shard split. if latest_shards.len() != latest_count.count() as usize { // This should be extremely rare, so we warn on it. tracing::warn!(%tenant_id, "Missed some shards at count {:?}: {latest_shards:?}", latest_count); continue; } // Check if we have any non-latest-count shards if ancestor_shards.is_empty() { tracing::debug!(%tenant_id, "No ancestor shards to clean up"); continue; } // Based on S3 view, this tenant looks like it might have some ancestor shard work to do. We // must only do this work if the tenant is not currently being split: otherwise, it is not safe // to GC ancestors, because if the split fails then the controller will try to attach ancestor // shards again. match controller_client .dispatch::<(), TenantDescribeResponse>( Method::GET, format!("control/v1/tenant/{tenant_id}"), None, ) .await { Err(e) => { // We were not able to learn the latest shard split state from the controller, so we will not // do ancestor GC on this tenant. tracing::warn!(%tenant_id, "Failed to query storage controller, will not do ancestor GC: {e}"); summary.controller_api_errors += 1; continue; } Ok(desc) => { // We expect to see that the latest shard count matches the one we saw in S3, and that none // of the shards indicate splitting in progress. let controller_indices: Vec<ShardIndex> = desc .shards .iter() .map(|s| s.tenant_shard_id.to_index()) .collect(); if !controller_indices.iter().eq(latest_shards.iter().copied()) { tracing::info!(%tenant_id, "Latest shards seen in S3 ({latest_shards:?}) don't match controller state ({controller_indices:?})"); continue; } if desc.shards.iter().any(|s| s.is_splitting) { tracing::info!(%tenant_id, "One or more shards is currently splitting"); continue; } // This shouldn't be too noisy, because we only log this for tenants that have some ancestral refs. tracing::info!(%tenant_id, "Validated state with controller: {desc:?}"); } } // GC ancestor shards for ancestor_shard in ancestor_shards.iter().map(|idx| TenantShardId { tenant_id, shard_count: idx.shard_count, shard_number: idx.shard_number, }) { ancestors_to_gc.push(ancestor_shard); } } (ancestors_to_gc, self.ancestor_ref_shards) } } fn is_old_enough(min_age: &Duration, key: &ListingObject, summary: &mut GcSummary) -> bool { // Validation: we will only GC indices & layers after a time threshold (e.g. one week) so that during an incident // it is easier to read old data for analysis, and easier to roll back shard splits without having to un-delete any objects. let age = match key.last_modified.elapsed() { Ok(e) => e, Err(_) => { tracing::warn!("Bad last_modified time: {:?}", key.last_modified); summary.remote_storage_errors += 1; return false; } }; let old_enough = &age > min_age; if !old_enough { tracing::info!( "Skipping young object {} < {}", humantime::format_duration(age), humantime::format_duration(*min_age) ); } old_enough } /// Same as [`is_old_enough`], but doesn't require a [`ListingObject`] passed to it. async fn check_is_old_enough( remote_client: &GenericRemoteStorage, key: &RemotePath, min_age: &Duration, summary: &mut GcSummary, ) -> Option<bool> { let listing_object = remote_client .head_object(key, &CancellationToken::new()) .await .ok()?; Some(is_old_enough(min_age, &listing_object, summary)) } async fn maybe_delete_index( remote_client: &GenericRemoteStorage, min_age: &Duration, latest_gen: Generation, obj: &ListingObject, mode: GcMode, summary: &mut GcSummary, ) { // Validation: we will only delete things that parse cleanly let basename = obj.key.get_path().file_name().unwrap(); let candidate_generation = match parse_remote_index_path(RemotePath::from_string(basename).unwrap()) { Some(g) => g, None => { if basename == IndexPart::FILE_NAME { // A legacy pre-generation index Generation::none() } else { // A strange key: we will not delete this because we don't understand it. tracing::warn!("Bad index key"); return; } } }; // Validation: we will only delete indices more than one generation old, to avoid interfering // in typical migrations, even if they are very long running. if candidate_generation >= latest_gen { // This shouldn't happen: when we loaded metadata, it should have selected the latest // generation already, and only populated [`S3TimelineBlobData::unused_index_keys`] // with older generations. tracing::warn!("Deletion candidate is >= latest generation, this is a bug!"); return; } else if candidate_generation.next() == latest_gen { // Skip deleting the latest-1th generation's index. return; } if !is_old_enough(min_age, obj, summary) { return; } if matches!(mode, GcMode::DryRun) { tracing::info!("Dry run: would delete this key"); return; } // All validations passed: erase the object let cancel = CancellationToken::new(); match backoff::retry( || remote_client.delete(&obj.key, &cancel), |_| false, 3, MAX_RETRIES as u32, "maybe_delete_index", &cancel, ) .await { None => { unreachable!("Using a dummy cancellation token"); } Some(Ok(_)) => { tracing::info!("Successfully deleted index"); summary.indices_deleted += 1; } Some(Err(e)) => { tracing::warn!("Failed to delete index: {e}"); summary.remote_storage_errors += 1; } } } async fn maybe_delete_tenant_manifest( remote_client: &GenericRemoteStorage, min_age: &Duration, latest_gen: Generation, obj: &ListingObject, mode: GcMode, summary: &mut GcSummary, ) { // Validation: we will only delete things that parse cleanly let basename = obj.key.get_path().file_name().unwrap(); let Some(candidate_generation) = parse_remote_tenant_manifest_path(RemotePath::from_string(basename).unwrap()) else { // A strange key: we will not delete this because we don't understand it. tracing::warn!("Bad index key"); return; }; // Validation: we will only delete manifests more than one generation old, and in fact we // should never be called with such recent generations. if candidate_generation >= latest_gen { tracing::warn!("Deletion candidate is >= latest generation, this is a bug!"); return; } else if candidate_generation.next() == latest_gen { tracing::warn!("Deletion candidate is >= latest generation - 1, this is a bug!"); return; } if !is_old_enough(min_age, obj, summary) { return; } if matches!(mode, GcMode::DryRun) { tracing::info!("Dry run: would delete this key"); return; } // All validations passed: erase the object let cancel = CancellationToken::new(); match backoff::retry( || remote_client.delete(&obj.key, &cancel), |_| false, 3, MAX_RETRIES as u32, "maybe_delete_tenant_manifest", &cancel, ) .await { None => { unreachable!("Using a dummy cancellation token"); } Some(Ok(_)) => { tracing::info!("Successfully deleted tenant manifest"); summary.tenant_manifests_deleted += 1; } Some(Err(e)) => { tracing::warn!("Failed to delete tenant manifest: {e}"); summary.remote_storage_errors += 1; } } } #[allow(clippy::too_many_arguments)] async fn gc_ancestor( remote_client: &GenericRemoteStorage, root_target: &RootTarget, min_age: &Duration, ancestor: TenantShardId, refs: &AncestorRefs, mode: GcMode, summary: &mut GcSummary, ) -> anyhow::Result<()> { // Scan timelines in the ancestor let timelines = stream_tenant_timelines(remote_client, root_target, ancestor).await?; let mut timelines = std::pin::pin!(timelines); // Build a list of keys to retain while let Some(ttid) = timelines.next().await { let ttid = ttid?; let data = list_timeline_blobs(remote_client, ttid, root_target).await?; let s3_layers = match data.blob_data { BlobDataParseResult::Parsed { index_part: _, index_part_generation: _, s3_layers, index_part_last_modified_time: _, index_part_snapshot_time: _, } => s3_layers, BlobDataParseResult::Relic => { // Post-deletion tenant location: don't try and GC it. continue; } BlobDataParseResult::Incorrect { errors, s3_layers: _, // TODO(yuchen): could still check references to these s3 layers? } => { // Our primary purpose isn't to report on bad data, but log this rather than skipping silently tracing::warn!( "Skipping ancestor GC for timeline {ttid}, bad metadata: {errors:?}" ); continue; } }; let ttid_refs = refs.get_ttid_refcounts(&ttid.as_tenant_timeline_id()); let ancestor_shard_index = ttid.tenant_shard_id.to_index(); for (layer_name, layer_gen) in s3_layers { let ref_count = ttid_refs .and_then(|m| m.get(&(ancestor_shard_index, layer_name.clone()))) .copied() .unwrap_or(0); if ref_count > 0 { tracing::debug!(%ttid, "Ancestor layer {layer_name} has {ref_count} refs"); continue; } tracing::info!(%ttid, "Ancestor layer {layer_name} is not referenced"); // Build the key for the layer we are considering deleting let key = root_target.absolute_key(&remote_layer_path( &ttid.tenant_shard_id.tenant_id, &ttid.timeline_id, ancestor_shard_index, &layer_name, layer_gen, )); // We apply a time threshold to GCing objects that are un-referenced: this preserves our ability // to roll back a shard split if we have to, by avoiding deleting ancestor layers right away let path = RemotePath::from_string(key.strip_prefix("/").unwrap_or(&key)).unwrap(); if check_is_old_enough(remote_client, &path, min_age, summary).await != Some(true) { continue; } if !matches!(mode, GcMode::Full) { tracing::info!("Dry run: would delete key {key}"); continue; } // All validations passed: erase the object match remote_client.delete(&path, &CancellationToken::new()).await { Ok(_) => { tracing::info!("Successfully deleted unreferenced ancestor layer {key}"); summary.ancestor_layers_deleted += 1; } Err(e) => { tracing::warn!("Failed to delete layer {key}: {e}"); summary.remote_storage_errors += 1; } } } // TODO: if all the layers are gone, clean up the whole timeline dir (remove index) } Ok(()) } async fn gc_tenant_manifests( remote_client: &GenericRemoteStorage, min_age: Duration, target: &RootTarget, mode: GcMode, tenant_shard_id: TenantShardId, ) -> anyhow::Result<(GcSummary, Option<RemoteTenantManifestInfo>)> { let mut gc_summary = GcSummary::default(); match list_tenant_manifests(remote_client, tenant_shard_id, target).await? { ListTenantManifestResult::WithErrors { errors, unknown_keys: _, } => { for (_key, error) in errors { tracing::warn!(%tenant_shard_id, "list_tenant_manifests: {error}"); } Ok((gc_summary, None)) } ListTenantManifestResult::NoErrors { latest_generation, mut manifests, } => { let Some(latest_generation) = latest_generation else { return Ok((gc_summary, None)); }; manifests.sort_by_key(|(generation, _obj)| *generation); // skip the two latest generations (they don't neccessarily have to be 1 apart from each other) let candidates = manifests.iter().rev().skip(2); for (_generation, key) in candidates { maybe_delete_tenant_manifest( remote_client, &min_age, latest_generation.generation, key, mode, &mut gc_summary, ) .instrument( info_span!("maybe_delete_tenant_manifest", %tenant_shard_id, ?latest_generation.generation, %key.key), ) .await; } Ok((gc_summary, Some(latest_generation))) } } } async fn gc_timeline( remote_client: &GenericRemoteStorage, min_age: &Duration, target: &RootTarget, mode: GcMode, ttid: TenantShardTimelineId, accumulator: &std::sync::Mutex<TenantRefAccumulator>, tenant_manifest_info: Arc<Option<RemoteTenantManifestInfo>>, ) -> anyhow::Result<GcSummary> { let mut summary = GcSummary::default(); let data = list_timeline_blobs(remote_client, ttid, target).await?; let (index_part, latest_gen, candidates) = match &data.blob_data { BlobDataParseResult::Parsed { index_part, index_part_generation, s3_layers: _, index_part_last_modified_time: _, index_part_snapshot_time: _, } => (index_part, *index_part_generation, data.unused_index_keys), BlobDataParseResult::Relic => { tracing::info!("Skipping timeline {ttid}, it is a relic"); // Post-deletion tenant location: don't try and GC it. return Ok(summary); } BlobDataParseResult::Incorrect { errors, s3_layers: _, } => { // Our primary purpose isn't to report on bad data, but log this rather than skipping silently tracing::warn!("Skipping timeline {ttid}, bad metadata: {errors:?}"); return Ok(summary); } }; if let Some(tenant_manifest_info) = &*tenant_manifest_info { // TODO: this is O(n^2) in the number of offloaded timelines. Do a hashmap lookup instead. let maybe_offloaded = tenant_manifest_info .manifest .offloaded_timelines .iter() .find(|offloaded_timeline| offloaded_timeline.timeline_id == ttid.timeline_id); if let Some(offloaded) = maybe_offloaded { let warnings = validate_index_part_with_offloaded(index_part, offloaded); let warn = if warnings.is_empty() { false } else { // Verify that the manifest hasn't changed. If it has, a potential racing change could have been cause for our troubles. match list_tenant_manifests(remote_client, ttid.tenant_shard_id, target).await? { ListTenantManifestResult::WithErrors { errors, unknown_keys: _, } => { for (_key, error) in errors { tracing::warn!(%ttid, "list_tenant_manifests in gc_timeline: {error}"); } true } ListTenantManifestResult::NoErrors { latest_generation, manifests: _, } => { if let Some(new_latest_gen) = latest_generation { let manifest_changed = ( new_latest_gen.generation, new_latest_gen.listing_object.last_modified, ) == ( tenant_manifest_info.generation, tenant_manifest_info.listing_object.last_modified, ); if manifest_changed { tracing::debug!(%ttid, "tenant manifest changed since it was loaded, suppressing {} warnings", warnings.len()); } manifest_changed } else { // The latest generation is gone. This timeline is in the progress of being deleted? false } } } }; if warn { for warning in warnings { tracing::warn!(%ttid, "{}", warning); } } } } accumulator.lock().unwrap().update(ttid, index_part); for key in candidates { maybe_delete_index(remote_client, min_age, latest_gen, &key, mode, &mut summary) .instrument(info_span!("maybe_delete_index", %ttid, ?latest_gen, %key.key)) .await; } Ok(summary) } fn validate_index_part_with_offloaded( index_part: &IndexPart, offloaded: &OffloadedTimelineManifest, ) -> Vec<String> { let mut warnings = Vec::new(); if let Some(archived_at_index_part) = index_part.archived_at { if archived_at_index_part .signed_duration_since(offloaded.archived_at) .num_seconds() != 0 { warnings.push(format!( "index-part archived_at={} differs from manifest archived_at={}", archived_at_index_part, offloaded.archived_at )); } } else { warnings.push("Timeline offloaded in manifest but not archived in index-part".to_string()); } if index_part.metadata.ancestor_timeline() != offloaded.ancestor_timeline_id { warnings.push(format!( "index-part anestor={:?} differs from manifest ancestor={:?}", index_part.metadata.ancestor_timeline(), offloaded.ancestor_timeline_id )); } warnings } /// Physical garbage collection: removing unused S3 objects. /// /// This is distinct from the garbage collection done inside the pageserver, which operates at a higher level /// (keys, layers). This type of garbage collection is about removing: /// - Objects that were uploaded but never referenced in the remote index (e.g. because of a shutdown between /// uploading a layer and uploading an index) /// - Index objects and tenant manifests from historic generations /// /// This type of GC is not necessary for correctness: rather it serves to reduce wasted storage capacity, and /// make sure that object listings don't get slowed down by large numbers of garbage objects. pub async fn pageserver_physical_gc( bucket_config: &BucketConfig, controller_client: Option<&control_api::Client>, tenant_shard_ids: Vec<TenantShardId>, min_age: Duration, mode: GcMode, ) -> anyhow::Result<GcSummary> { let (remote_client, target) = init_remote(bucket_config.clone(), NodeKind::Pageserver).await?; let remote_client = Arc::new(remote_client); let tenants = if tenant_shard_ids.is_empty() { Either::Left(stream_tenants(&remote_client, &target)) } else { Either::Right(futures::stream::iter(tenant_shard_ids.into_iter().map(Ok))) }; // How many tenants to process in parallel. We need to be mindful of pageservers // accessing the same per tenant prefixes, so use a lower setting than pageservers. const CONCURRENCY: usize = 32; // Accumulate information about each tenant for cross-shard GC step we'll do at the end let accumulator = std::sync::Mutex::new(TenantRefAccumulator::default()); // Accumulate information about how many manifests we have GCd let manifest_gc_summary = std::sync::Mutex::new(GcSummary::default()); // Generate a stream of TenantTimelineId let timelines = tenants.map_ok(|tenant_shard_id| { let target_ref = &target; let remote_client_ref = &remote_client; let manifest_gc_summary_ref = &manifest_gc_summary; async move { let gc_manifest_result = gc_tenant_manifests( remote_client_ref, min_age, target_ref, mode, tenant_shard_id, ) .await; let (summary_from_manifest, tenant_manifest_opt) = match gc_manifest_result { Ok((gc_summary, tenant_manifest)) => (gc_summary, tenant_manifest), Err(e) => { tracing::warn!(%tenant_shard_id, "Error in gc_tenant_manifests: {e}"); (GcSummary::default(), None) } }; manifest_gc_summary_ref .lock() .unwrap() .merge(summary_from_manifest); let tenant_manifest_arc = Arc::new(tenant_manifest_opt); let mut timelines = Box::pin( stream_tenant_timelines(remote_client_ref, target_ref, tenant_shard_id).await?, ); Ok(try_stream! { let mut cnt = 0; while let Some(ttid_res) = timelines.next().await { let ttid = ttid_res?; cnt += 1; yield (ttid, tenant_manifest_arc.clone()); } tracing::info!(%tenant_shard_id, "Found {} timelines", cnt); }) } }); let mut summary = GcSummary::default(); { let timelines = timelines.try_buffered(CONCURRENCY); let timelines = timelines.try_flatten(); let timelines = timelines.map_ok(|(ttid, tenant_manifest_arc)| { gc_timeline( &remote_client, &min_age, &target, mode, ttid, &accumulator, tenant_manifest_arc, ) .instrument(info_span!("gc_timeline", %ttid)) }); let timelines = timelines.try_buffered(CONCURRENCY); let mut timelines = std::pin::pin!(timelines); // Drain futures for per-shard GC, populating accumulator as a side effect while let Some(i) = timelines.next().await { summary.merge(i?); } } // Streams are lazily evaluated, so only now do we have access to the inner object summary.merge(manifest_gc_summary.into_inner().unwrap()); // Execute cross-shard GC, using the accumulator's full view of all the shards built in the per-shard GC let Some(client) = controller_client else { tracing::info!("Skipping ancestor layer GC, because no `--controller-api` was specified"); return Ok(summary); }; let (ancestor_shards, ancestor_refs) = accumulator .into_inner() .unwrap() .into_gc_ancestors(client, &mut summary) .await; for ancestor_shard in ancestor_shards { gc_ancestor( &remote_client, &target, &min_age, ancestor_shard, &ancestor_refs, mode, &mut summary, ) .instrument(info_span!("gc_ancestor", %ancestor_shard)) .await?; } Ok(summary) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/lib.rs
storage_scrubber/src/lib.rs
#![deny(unsafe_code)] #![deny(clippy::undocumented_unsafe_blocks)] pub mod checks; pub mod cloud_admin_api; pub mod find_large_objects; pub mod garbage; pub mod metadata_stream; pub mod pageserver_physical_gc; pub mod scan_pageserver_metadata; pub mod scan_safekeeper_metadata; pub mod tenant_snapshot; use std::env; use std::fmt::Display; use std::time::{Duration, SystemTime}; use anyhow::Context; use camino::{Utf8Path, Utf8PathBuf}; use clap::ValueEnum; use futures::{Stream, StreamExt}; use pageserver::tenant::TENANTS_SEGMENT_NAME; use pageserver::tenant::remote_timeline_client::{remote_tenant_path, remote_timeline_path}; use pageserver_api::shard::TenantShardId; use remote_storage::{ DownloadOpts, GenericRemoteStorage, Listing, ListingMode, RemotePath, RemoteStorageConfig, RemoteStorageKind, VersionId, }; use reqwest::Url; use serde::{Deserialize, Serialize}; use storage_controller_client::control_api; use tokio::io::AsyncReadExt; use tokio_util::sync::CancellationToken; use tracing::{error, warn}; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::prelude::*; use tracing_subscriber::{EnvFilter, fmt}; use utils::fs_ext; use utils::id::{TenantId, TenantTimelineId, TimelineId}; const MAX_RETRIES: usize = 20; const CLOUD_ADMIN_API_TOKEN_ENV_VAR: &str = "CLOUD_ADMIN_API_TOKEN"; #[derive(Debug, Clone)] pub struct S3Target { pub desc_str: String, /// This `prefix_in_bucket` is only equal to the PS/SK config of the same /// name for the RootTarget: other instances of S3Target will have prefix_in_bucket /// with extra parts. pub prefix_in_bucket: String, pub delimiter: String, } /// Convenience for referring to timelines within a particular shard: more ergonomic /// than using a 2-tuple. /// /// This is the shard-aware equivalent of TenantTimelineId. It's defined here rather /// than somewhere more broadly exposed, because this kind of thing is rarely needed /// in the pageserver, as all timeline objects existing in the scope of a particular /// tenant: the scrubber is different in that it handles collections of data referring to many /// TenantShardTimelineIds in on place. #[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct TenantShardTimelineId { tenant_shard_id: TenantShardId, timeline_id: TimelineId, } impl TenantShardTimelineId { fn new(tenant_shard_id: TenantShardId, timeline_id: TimelineId) -> Self { Self { tenant_shard_id, timeline_id, } } fn as_tenant_timeline_id(&self) -> TenantTimelineId { TenantTimelineId::new(self.tenant_shard_id.tenant_id, self.timeline_id) } } impl Display for TenantShardTimelineId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}/{}", self.tenant_shard_id, self.timeline_id) } } #[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] pub enum TraversingDepth { Tenant, Timeline, } impl Display for TraversingDepth { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Tenant => "tenant", Self::Timeline => "timeline", }) } } #[derive(ValueEnum, Clone, Copy, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum NodeKind { Safekeeper, Pageserver, } impl NodeKind { fn as_str(&self) -> &'static str { match self { Self::Safekeeper => "safekeeper", Self::Pageserver => "pageserver", } } } impl Display for NodeKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } impl S3Target { pub fn with_sub_segment(&self, new_segment: &str) -> Self { let mut new_self = self.clone(); if new_self.prefix_in_bucket.is_empty() { new_self.prefix_in_bucket = format!("/{new_segment}/"); } else { if new_self.prefix_in_bucket.ends_with('/') { new_self.prefix_in_bucket.pop(); } new_self.prefix_in_bucket = [&new_self.prefix_in_bucket, new_segment, ""].join(&new_self.delimiter); } new_self } } #[derive(Clone)] pub enum RootTarget { Pageserver(S3Target), Safekeeper(S3Target), } impl RootTarget { pub fn tenants_root(&self) -> S3Target { match self { Self::Pageserver(root) => root.with_sub_segment(TENANTS_SEGMENT_NAME), Self::Safekeeper(root) => root.clone(), } } pub fn tenant_root(&self, tenant_id: &TenantShardId) -> S3Target { match self { Self::Pageserver(_) => self.tenants_root().with_sub_segment(&tenant_id.to_string()), Self::Safekeeper(_) => self .tenants_root() .with_sub_segment(&tenant_id.tenant_id.to_string()), } } pub(crate) fn tenant_shards_prefix(&self, tenant_id: &TenantId) -> S3Target { // Only pageserver remote storage contains tenant-shards assert!(matches!(self, Self::Pageserver(_))); let Self::Pageserver(root) = self else { panic!(); }; S3Target { desc_str: root.desc_str.clone(), prefix_in_bucket: format!( "{}/{TENANTS_SEGMENT_NAME}/{tenant_id}", root.prefix_in_bucket ), delimiter: root.delimiter.clone(), } } pub fn timelines_root(&self, tenant_id: &TenantShardId) -> S3Target { match self { Self::Pageserver(_) => self.tenant_root(tenant_id).with_sub_segment("timelines"), Self::Safekeeper(_) => self.tenant_root(tenant_id), } } pub fn timeline_root(&self, id: &TenantShardTimelineId) -> S3Target { self.timelines_root(&id.tenant_shard_id) .with_sub_segment(&id.timeline_id.to_string()) } /// Given RemotePath "tenants/foo/timelines/bar/layerxyz", prefix it to a literal /// key in the S3 bucket. pub fn absolute_key(&self, key: &RemotePath) -> String { let root = match self { Self::Pageserver(root) => root, Self::Safekeeper(root) => root, }; let prefix = &root.prefix_in_bucket; if prefix.ends_with('/') { format!("{prefix}{key}") } else { format!("{prefix}/{key}") } } pub fn desc_str(&self) -> &str { match self { Self::Pageserver(root) => &root.desc_str, Self::Safekeeper(root) => &root.desc_str, } } pub fn delimiter(&self) -> &str { match self { Self::Pageserver(root) => &root.delimiter, Self::Safekeeper(root) => &root.delimiter, } } } pub fn remote_timeline_path_id(id: &TenantShardTimelineId) -> RemotePath { remote_timeline_path(&id.tenant_shard_id, &id.timeline_id) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct BucketConfig(RemoteStorageConfig); impl BucketConfig { pub fn from_env() -> anyhow::Result<Self> { if let Ok(legacy) = Self::from_env_legacy() { return Ok(legacy); } let config_toml = env::var("REMOTE_STORAGE_CONFIG").context("'REMOTE_STORAGE_CONFIG' retrieval")?; let remote_config = RemoteStorageConfig::from_toml_str(&config_toml)?; Ok(BucketConfig(remote_config)) } fn from_env_legacy() -> anyhow::Result<Self> { let bucket_region = env::var("REGION").context("'REGION' param retrieval")?; let bucket_name = env::var("BUCKET").context("'BUCKET' param retrieval")?; let prefix_in_bucket = env::var("BUCKET_PREFIX").ok(); let endpoint = env::var("AWS_ENDPOINT_URL").ok(); // Create a json object which we then deserialize so that we don't // have to repeat all of the S3Config fields. let s3_config_json = serde_json::json!({ "bucket_name": bucket_name, "bucket_region": bucket_region, "prefix_in_bucket": prefix_in_bucket, "endpoint": endpoint, }); let config: RemoteStorageConfig = serde_json::from_value(s3_config_json)?; Ok(BucketConfig(config)) } pub fn desc_str(&self) -> String { match &self.0.storage { RemoteStorageKind::LocalFs { local_path } => { format!("local path {local_path}") } RemoteStorageKind::AwsS3(config) => format!( "bucket {}, region {}", config.bucket_name, config.bucket_region ), RemoteStorageKind::AzureContainer(config) => format!( "container {}, storage account {:?}, region {}", config.container_name, config.storage_account, config.container_region ), RemoteStorageKind::GCS(config) => format!("bucket {}", config.bucket_name), } } pub fn bucket_name(&self) -> Option<&str> { self.0.storage.bucket_name() } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct BucketConfigLegacy { pub region: String, pub bucket: String, pub prefix_in_bucket: Option<String>, } pub struct ControllerClientConfig { /// URL to storage controller. e.g. http://127.0.0.1:1234 when using `neon_local` pub controller_api: Url, /// JWT token for authenticating with storage controller. Requires scope 'scrubber' or 'admin'. pub controller_jwt: String, } impl ControllerClientConfig { pub fn build_client(self, http_client: reqwest::Client) -> control_api::Client { control_api::Client::new(http_client, self.controller_api, Some(self.controller_jwt)) } } pub struct ConsoleConfig { pub token: String, pub base_url: Url, } impl ConsoleConfig { pub fn from_env() -> anyhow::Result<Self> { let base_url: Url = env::var("CLOUD_ADMIN_API_URL") .context("'CLOUD_ADMIN_API_URL' param retrieval")? .parse() .context("'CLOUD_ADMIN_API_URL' param parsing")?; let token = env::var(CLOUD_ADMIN_API_TOKEN_ENV_VAR) .context("'CLOUD_ADMIN_API_TOKEN' environment variable fetch")?; Ok(Self { base_url, token }) } } pub fn init_logging(file_name: &str) -> Option<WorkerGuard> { let stderr_logs = fmt::Layer::new() .with_target(false) .with_writer(std::io::stderr); let disable_file_logging = match std::env::var("PAGESERVER_DISABLE_FILE_LOGGING") { Ok(s) => s == "1" || s.to_lowercase() == "true", Err(_) => false, }; if disable_file_logging { tracing_subscriber::registry() .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))) .with(stderr_logs) .init(); None } else { let (file_writer, guard) = tracing_appender::non_blocking(tracing_appender::rolling::never("./logs/", file_name)); let file_logs = fmt::Layer::new() .with_target(false) .with_ansi(false) .with_writer(file_writer); tracing_subscriber::registry() .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))) .with(stderr_logs) .with(file_logs) .init(); Some(guard) } } fn default_prefix_in_bucket(node_kind: NodeKind) -> &'static str { match node_kind { NodeKind::Pageserver => "pageserver/v1/", NodeKind::Safekeeper => "wal/", } } fn make_root_target(desc_str: String, prefix_in_bucket: String, node_kind: NodeKind) -> RootTarget { let s3_target = S3Target { desc_str, prefix_in_bucket, delimiter: "/".to_string(), }; match node_kind { NodeKind::Pageserver => RootTarget::Pageserver(s3_target), NodeKind::Safekeeper => RootTarget::Safekeeper(s3_target), } } async fn init_remote( mut storage_config: BucketConfig, node_kind: NodeKind, ) -> anyhow::Result<(GenericRemoteStorage, RootTarget)> { let desc_str = storage_config.desc_str(); let default_prefix = default_prefix_in_bucket(node_kind).to_string(); match &mut storage_config.0.storage { RemoteStorageKind::AwsS3(config) => { config.prefix_in_bucket.get_or_insert(default_prefix); } RemoteStorageKind::AzureContainer(config) => { config.prefix_in_container.get_or_insert(default_prefix); } RemoteStorageKind::LocalFs { .. } => (), RemoteStorageKind::GCS(config) => { config.prefix_in_bucket.get_or_insert(default_prefix); } } // We already pass the prefix to the remote client above let prefix_in_root_target = String::new(); let root_target = make_root_target(desc_str, prefix_in_root_target, node_kind); let client = GenericRemoteStorage::from_config(&storage_config.0).await?; Ok((client, root_target)) } /// Listing possibly large amounts of keys in a streaming fashion. fn stream_objects_with_retries<'a>( storage_client: &'a GenericRemoteStorage, listing_mode: ListingMode, s3_target: &'a S3Target, ) -> impl Stream<Item = Result<Listing, anyhow::Error>> + 'a { async_stream::stream! { let mut trial = 0; let cancel = CancellationToken::new(); let prefix_str = &s3_target .prefix_in_bucket .strip_prefix("/") .unwrap_or(&s3_target.prefix_in_bucket); let prefix = RemotePath::from_string(prefix_str)?; let mut list_stream = storage_client.list_streaming(Some(&prefix), listing_mode, None, &cancel); while let Some(res) = list_stream.next().await { match res { Err(err) => { let yield_err = if err.is_permanent() { true } else { let backoff_time = 1 << trial.min(5); tokio::time::sleep(Duration::from_secs(backoff_time)).await; trial += 1; trial == MAX_RETRIES - 1 }; if yield_err { yield Err(err) .with_context(|| format!("Failed to list objects {MAX_RETRIES} times")); break; } } Ok(res) => { trial = 0; yield Ok(res); } } } } } /// If you want to list a bounded amount of prefixes or keys. For larger numbers of keys/prefixes, /// use [`stream_objects_with_retries`] instead. async fn list_objects_with_retries( remote_client: &GenericRemoteStorage, listing_mode: ListingMode, s3_target: &S3Target, ) -> anyhow::Result<Listing> { let cancel = CancellationToken::new(); let prefix_str = &s3_target .prefix_in_bucket .strip_prefix("/") .unwrap_or(&s3_target.prefix_in_bucket); let prefix = RemotePath::from_string(prefix_str)?; for trial in 0..MAX_RETRIES { match remote_client .list(Some(&prefix), listing_mode, None, &cancel) .await { Ok(response) => return Ok(response), Err(e) => { if trial == MAX_RETRIES - 1 { return Err(e) .with_context(|| format!("Failed to list objects {MAX_RETRIES} times")); } warn!( "list_objects_v2 query failed: bucket_name={}, prefix={}, delimiter={}, error={}", remote_client.bucket_name().unwrap_or_default(), s3_target.prefix_in_bucket, s3_target.delimiter, e, ); let backoff_time = 1 << trial.min(5); tokio::time::sleep(Duration::from_secs(backoff_time)).await; } } } panic!("MAX_RETRIES is not allowed to be 0"); } /// Returns content, last modified time async fn download_object_with_retries( remote_client: &GenericRemoteStorage, key: &RemotePath, ) -> anyhow::Result<(Vec<u8>, SystemTime)> { let cancel = CancellationToken::new(); for trial in 0..MAX_RETRIES { let mut buf = Vec::new(); let download = match remote_client .download(key, &DownloadOpts::default(), &cancel) .await { Ok(response) => response, Err(e) => { error!("Failed to download object for key {key}: {e}"); let backoff_time = 1 << trial.min(5); tokio::time::sleep(Duration::from_secs(backoff_time)).await; continue; } }; match tokio_util::io::StreamReader::new(download.download_stream) .read_to_end(&mut buf) .await { Ok(bytes_read) => { tracing::debug!("Downloaded {bytes_read} bytes for object {key}"); return Ok((buf, download.last_modified)); } Err(e) => { error!("Failed to stream object body for key {key}: {e}"); let backoff_time = 1 << trial.min(5); tokio::time::sleep(Duration::from_secs(backoff_time)).await; } } } anyhow::bail!("Failed to download objects with key {key} {MAX_RETRIES} times") } async fn download_object_to_file( remote_storage: &GenericRemoteStorage, key: &RemotePath, version_id: Option<VersionId>, local_path: &Utf8Path, ) -> anyhow::Result<()> { let opts = DownloadOpts { version_id: version_id.clone(), ..Default::default() }; let tmp_path = Utf8PathBuf::from(format!("{local_path}.tmp")); let cancel = CancellationToken::new(); for _ in 0..MAX_RETRIES { tokio::fs::remove_file(&tmp_path) .await .or_else(fs_ext::ignore_not_found)?; let mut file = tokio::fs::File::create(&tmp_path) .await .context("Opening output file")?; let res = remote_storage.download(key, &opts, &cancel).await; let download = match res { Ok(response) => response, Err(e) => { error!( "Failed to download object for key {key} version {:?}: {e:#}", &version_id.as_ref().unwrap_or(&VersionId(String::new())) ); tokio::time::sleep(Duration::from_secs(1)).await; continue; } }; //response_stream.download_stream let mut body = tokio_util::io::StreamReader::new(download.download_stream); tokio::io::copy(&mut body, &mut file).await?; tokio::fs::rename(&tmp_path, local_path).await?; return Ok(()); } anyhow::bail!("Failed to download objects with key {key} {MAX_RETRIES} times") }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/checks.rs
storage_scrubber/src/checks.rs
use std::collections::{HashMap, HashSet}; use std::time::SystemTime; use futures_util::StreamExt; use itertools::Itertools; use pageserver::tenant::IndexPart; use pageserver::tenant::checks::check_valid_layermap; use pageserver::tenant::layer_map::LayerMap; use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata; use pageserver::tenant::remote_timeline_client::manifest::TenantManifest; use pageserver::tenant::remote_timeline_client::{ parse_remote_index_path, parse_remote_tenant_manifest_path, remote_layer_path, }; use pageserver::tenant::storage_layer::LayerName; use pageserver_api::shard::ShardIndex; use remote_storage::{DownloadError, GenericRemoteStorage, ListingObject, RemotePath}; use tokio_util::sync::CancellationToken; use tracing::{info, warn}; use utils::generation::Generation; use utils::id::TimelineId; use utils::shard::TenantShardId; use crate::cloud_admin_api::BranchData; use crate::metadata_stream::stream_listing; use crate::{RootTarget, TenantShardTimelineId, download_object_with_retries}; pub(crate) struct TimelineAnalysis { /// Anomalies detected pub(crate) errors: Vec<String>, /// Healthy-but-noteworthy, like old-versioned structures that are readable but /// worth reporting for awareness that we must not remove that old version decoding /// yet. pub(crate) warnings: Vec<String>, /// Objects whose keys were not recognized at all, i.e. not layer files, not indices, and not initdb archive. pub(crate) unknown_keys: Vec<String>, } impl TimelineAnalysis { fn new() -> Self { Self { errors: Vec::new(), warnings: Vec::new(), unknown_keys: Vec::new(), } } /// Whether a timeline is healthy. pub(crate) fn is_healthy(&self) -> bool { self.errors.is_empty() && self.warnings.is_empty() } } pub(crate) async fn branch_cleanup_and_check_errors( remote_client: &GenericRemoteStorage, id: &TenantShardTimelineId, tenant_objects: &mut TenantObjectListing, s3_active_branch: Option<&BranchData>, console_branch: Option<BranchData>, s3_data: Option<RemoteTimelineBlobData>, ) -> TimelineAnalysis { let mut result = TimelineAnalysis::new(); info!("Checking timeline"); if let Some(s3_active_branch) = s3_active_branch { info!( "Checking console status for timeline for branch {:?}/{:?}", s3_active_branch.project_id, s3_active_branch.id ); match console_branch { Some(_) => {result.errors.push(format!("Timeline has deleted branch data in the console (id = {:?}, project_id = {:?}), recheck whether it got removed during the check", s3_active_branch.id, s3_active_branch.project_id)) }, None => { result.errors.push(format!("Timeline has no branch data in the console (id = {:?}, project_id = {:?}), recheck whether it got removed during the check", s3_active_branch.id, s3_active_branch.project_id)) } }; } match s3_data { Some(s3_data) => { result .unknown_keys .extend(s3_data.unknown_keys.into_iter().map(|k| k.key.to_string())); match s3_data.blob_data { BlobDataParseResult::Parsed { index_part, index_part_generation: _, s3_layers: _, index_part_last_modified_time, index_part_snapshot_time, } => { // Ignore missing file error if index_part downloaded is different from the one when listing the layer files. let ignore_error = index_part_snapshot_time < index_part_last_modified_time && !cfg!(debug_assertions); if !IndexPart::KNOWN_VERSIONS.contains(&index_part.version()) { result .errors .push(format!("index_part.json version: {}", index_part.version())) } let mut newest_versions = IndexPart::KNOWN_VERSIONS.iter().rev().take(3); if !newest_versions.any(|ip| ip == &index_part.version()) { info!( "index_part.json version is not latest: {}", index_part.version() ); } if index_part.metadata.disk_consistent_lsn() != index_part.duplicated_disk_consistent_lsn() { // Tech debt: let's get rid of one of these, they are redundant // https://github.com/neondatabase/neon/issues/8343 result.errors.push(format!( "Mismatching disk_consistent_lsn in TimelineMetadata ({}) and in the index_part ({})", index_part.metadata.disk_consistent_lsn(), index_part.duplicated_disk_consistent_lsn(), )) } if index_part.layer_metadata.is_empty() { if index_part.metadata.ancestor_timeline().is_none() { // The initial timeline with no ancestor should ALWAYS have layers. result.errors.push( "index_part.json has no layers (ancestor_timeline=None)" .to_string(), ); } else { // Not an error, can happen for branches with zero writes, but notice that info!("index_part.json has no layers (ancestor_timeline exists)"); } } let layer_names = index_part.layer_metadata.keys().cloned().collect_vec(); if let Some(err) = check_valid_layermap(&layer_names) { result.warnings.push(format!( "index_part.json contains invalid layer map structure: {err}" )); } for (layer, metadata) in index_part.layer_metadata { if metadata.file_size == 0 { result.errors.push(format!( "index_part.json contains a layer {layer} that has 0 size in its layer metadata", )) } if !tenant_objects.check_ref(id.timeline_id, &layer, &metadata) { let path = remote_layer_path( &id.tenant_shard_id.tenant_id, &id.timeline_id, metadata.shard, &layer, metadata.generation, ); // HEAD request used here to address a race condition when an index was uploaded concurrently // with our scan. We check if the object is uploaded to S3 after taking the listing snapshot. let response = remote_client .head_object(&path, &CancellationToken::new()) .await; match response { Ok(_) => {} Err(DownloadError::NotFound) => { // Object is not present. let is_l0 = LayerMap::is_l0(layer.key_range(), layer.is_delta()); let msg = format!( "index_part.json contains a layer {}{} (shard {}) that is not present in remote storage (layer_is_l0: {})", layer, metadata.generation.get_suffix(), metadata.shard, is_l0, ); if is_l0 || ignore_error { result.warnings.push(msg); } else { result.errors.push(msg); } } Err(e) => { tracing::warn!( "cannot check if the layer {}{} is present in remote storage (error: {})", layer, metadata.generation.get_suffix(), e, ); } } } } } BlobDataParseResult::Relic => {} BlobDataParseResult::Incorrect { errors, s3_layers: _, } => result.errors.extend( errors .into_iter() .map(|error| format!("parse error: {error}")), ), } } None => result .errors .push("Timeline has no data on S3 at all".to_string()), } if result.errors.is_empty() { info!("No check errors found"); } else { warn!("Timeline metadata errors: {0:?}", result.errors); } if !result.warnings.is_empty() { warn!("Timeline metadata warnings: {0:?}", result.warnings); } if !result.unknown_keys.is_empty() { warn!( "The following keys are not recognized: {0:?}", result.unknown_keys ) } result } #[derive(Default)] pub(crate) struct LayerRef { ref_count: usize, } /// Top-level index of objects in a tenant. This may be used by any shard-timeline within /// the tenant to query whether an object exists. #[derive(Default)] pub(crate) struct TenantObjectListing { shard_timelines: HashMap<(ShardIndex, TimelineId), HashMap<(LayerName, Generation), LayerRef>>, } impl TenantObjectListing { /// Having done an S3 listing of the keys within a timeline prefix, merge them into the overall /// list of layer keys for the Tenant. pub(crate) fn push( &mut self, ttid: TenantShardTimelineId, layers: HashSet<(LayerName, Generation)>, ) { let shard_index = ShardIndex::new( ttid.tenant_shard_id.shard_number, ttid.tenant_shard_id.shard_count, ); let replaced = self.shard_timelines.insert( (shard_index, ttid.timeline_id), layers .into_iter() .map(|l| (l, LayerRef::default())) .collect(), ); assert!( replaced.is_none(), "Built from an S3 object listing, which should never repeat a key" ); } /// Having loaded a timeline index, check if a layer referenced by the index exists. If it does, /// the layer's refcount will be incremented. Later, after calling this for all references in all indices /// in a tenant, orphan layers may be detected by their zero refcounts. /// /// Returns true if the layer exists pub(crate) fn check_ref( &mut self, timeline_id: TimelineId, layer_file: &LayerName, metadata: &LayerFileMetadata, ) -> bool { let Some(shard_tl) = self.shard_timelines.get_mut(&(metadata.shard, timeline_id)) else { return false; }; let Some(layer_ref) = shard_tl.get_mut(&(layer_file.clone(), metadata.generation)) else { return false; }; layer_ref.ref_count += 1; true } pub(crate) fn get_orphans(&self) -> Vec<(ShardIndex, TimelineId, LayerName, Generation)> { let mut result = Vec::new(); for ((shard_index, timeline_id), layers) in &self.shard_timelines { for ((layer_file, generation), layer_ref) in layers { if layer_ref.ref_count == 0 { result.push((*shard_index, *timeline_id, layer_file.clone(), *generation)) } } } result } } #[derive(Debug)] pub(crate) struct RemoteTimelineBlobData { pub(crate) blob_data: BlobDataParseResult, /// Index objects that were not used when loading `blob_data`, e.g. those from old generations pub(crate) unused_index_keys: Vec<ListingObject>, /// Objects whose keys were not recognized at all, i.e. not layer files, not indices pub(crate) unknown_keys: Vec<ListingObject>, } #[derive(Debug)] pub(crate) enum BlobDataParseResult { Parsed { index_part: Box<IndexPart>, index_part_generation: Generation, index_part_last_modified_time: SystemTime, index_part_snapshot_time: SystemTime, s3_layers: HashSet<(LayerName, Generation)>, }, /// The remains of an uncleanly deleted Timeline or aborted timeline creation(e.g. an initdb archive only, or some layer without an index) Relic, Incorrect { errors: Vec<String>, s3_layers: HashSet<(LayerName, Generation)>, }, } pub(crate) fn parse_layer_object_name(name: &str) -> Result<(LayerName, Generation), String> { match name.rsplit_once('-') { // FIXME: this is gross, just use a regex? Some((layer_filename, gen_)) if gen_.len() == 8 => { let layer = layer_filename.parse::<LayerName>()?; let gen_ = Generation::parse_suffix(gen_).ok_or("Malformed generation suffix".to_string())?; Ok((layer, gen_)) } _ => Ok((name.parse::<LayerName>()?, Generation::none())), } } /// Note (<https://github.com/neondatabase/neon/issues/8872>): /// Since we do not gurantee the order of the listing, we could list layer keys right before /// pageserver `RemoteTimelineClient` deletes the layer files and then the index. /// In the rare case, this would give back a transient error where the index key is missing. /// /// To avoid generating false positive, we try streaming the listing for a second time. pub(crate) async fn list_timeline_blobs( remote_client: &GenericRemoteStorage, id: TenantShardTimelineId, root_target: &RootTarget, ) -> anyhow::Result<RemoteTimelineBlobData> { let res = list_timeline_blobs_impl(remote_client, id, root_target).await?; match res { ListTimelineBlobsResult::Ready(data) => Ok(data), ListTimelineBlobsResult::MissingIndexPart(_) => { tracing::warn!("listing raced with removal of an index, retrying"); // Retry if listing raced with removal of an index let data = list_timeline_blobs_impl(remote_client, id, root_target) .await? .into_data(); Ok(data) } } } enum ListTimelineBlobsResult { /// Blob data is ready to be intepreted. Ready(RemoteTimelineBlobData), /// The listing contained an index but when we tried to fetch it, we couldn't MissingIndexPart(RemoteTimelineBlobData), } impl ListTimelineBlobsResult { /// Get the inner blob data regardless the status. pub fn into_data(self) -> RemoteTimelineBlobData { match self { ListTimelineBlobsResult::Ready(data) => data, ListTimelineBlobsResult::MissingIndexPart(data) => data, } } } /// Returns [`ListTimelineBlobsResult::MissingIndexPart`] if blob data has layer files /// but is missing [`IndexPart`], otherwise returns [`ListTimelineBlobsResult::Ready`]. async fn list_timeline_blobs_impl( remote_client: &GenericRemoteStorage, id: TenantShardTimelineId, root_target: &RootTarget, ) -> anyhow::Result<ListTimelineBlobsResult> { let mut s3_layers = HashSet::new(); let mut errors = Vec::new(); let mut unknown_keys = Vec::new(); let mut timeline_dir_target = root_target.timeline_root(&id); timeline_dir_target.delimiter = String::new(); let mut index_part_keys: Vec<ListingObject> = Vec::new(); let mut initdb_archive: bool = false; let prefix_str = &timeline_dir_target .prefix_in_bucket .strip_prefix("/") .unwrap_or(&timeline_dir_target.prefix_in_bucket); let mut stream = std::pin::pin!(stream_listing(remote_client, &timeline_dir_target)); while let Some(obj) = stream.next().await { let (key, Some(obj)) = obj? else { panic!("ListingObject not specified"); }; let blob_name = key.get_path().as_str().strip_prefix(prefix_str); match blob_name { Some(name) if name.starts_with("index_part.json") => { tracing::debug!("Index key {key}"); index_part_keys.push(obj) } Some("initdb.tar.zst") => { tracing::debug!("initdb archive {key}"); initdb_archive = true; } Some("initdb-preserved.tar.zst") => { tracing::info!("initdb archive preserved {key}"); } Some(maybe_layer_name) => match parse_layer_object_name(maybe_layer_name) { Ok((new_layer, gen_)) => { tracing::debug!("Parsed layer key: {new_layer} {gen_:?}"); s3_layers.insert((new_layer, gen_)); } Err(e) => { tracing::info!("Error parsing {maybe_layer_name} as layer name: {e}"); unknown_keys.push(obj); } }, None => { tracing::info!("S3 listed an unknown key: {key}"); unknown_keys.push(obj); } } } if index_part_keys.is_empty() && s3_layers.is_empty() { tracing::info!("Timeline is empty: expected post-deletion state."); if initdb_archive { tracing::info!("Timeline is post deletion but initdb archive is still present."); } return Ok(ListTimelineBlobsResult::Ready(RemoteTimelineBlobData { blob_data: BlobDataParseResult::Relic, unused_index_keys: index_part_keys, unknown_keys, })); } // Choose the index_part with the highest generation let (index_part_object, index_part_generation) = match index_part_keys .iter() .filter_map(|key| { // Stripping the index key to the last part, because RemotePath doesn't // like absolute paths, and depending on prefix_in_bucket it's possible // for the keys we read back to start with a slash. let basename = key.key.get_path().as_str().rsplit_once('/').unwrap().1; parse_remote_index_path(RemotePath::from_string(basename).unwrap()).map(|g| (key, g)) }) .max_by_key(|i| i.1) .map(|(k, g)| (k.clone(), g)) { Some((key, gen_)) => (Some::<ListingObject>(key.to_owned()), gen_), None => { // Legacy/missing case: one or zero index parts, which did not have a generation (index_part_keys.pop(), Generation::none()) } }; match index_part_object.as_ref() { Some(selected) => index_part_keys.retain(|k| k != selected), None => { // This case does not indicate corruption, but it should be very unusual. It can // happen if: // - timeline creation is in progress (first layer is written before index is written) // - timeline deletion happened while a stale pageserver was still attached, it might upload // a layer after the deletion is done. tracing::info!( "S3 list response got no index_part.json file but still has layer files" ); return Ok(ListTimelineBlobsResult::Ready(RemoteTimelineBlobData { blob_data: BlobDataParseResult::Relic, unused_index_keys: index_part_keys, unknown_keys, })); } } if let Some(index_part_object_key) = index_part_object.as_ref() { let (index_part_bytes, index_part_last_modified_time) = match download_object_with_retries(remote_client, &index_part_object_key.key).await { Ok(data) => data, Err(e) => { // It is possible that the branch gets deleted in-between we list the objects // and we download the index part file. errors.push(format!("failed to download index_part.json: {e}")); return Ok(ListTimelineBlobsResult::MissingIndexPart( RemoteTimelineBlobData { blob_data: BlobDataParseResult::Incorrect { errors, s3_layers }, unused_index_keys: index_part_keys, unknown_keys, }, )); } }; let index_part_snapshot_time = index_part_object_key.last_modified; match serde_json::from_slice(&index_part_bytes) { Ok(index_part) => { return Ok(ListTimelineBlobsResult::Ready(RemoteTimelineBlobData { blob_data: BlobDataParseResult::Parsed { index_part: Box::new(index_part), index_part_generation, s3_layers, index_part_last_modified_time, index_part_snapshot_time, }, unused_index_keys: index_part_keys, unknown_keys, })); } Err(index_parse_error) => errors.push(format!( "index_part.json body parsing error: {index_parse_error}" )), } } if errors.is_empty() { errors.push( "Unexpected: no errors did not lead to a successfully parsed blob return".to_string(), ); } Ok(ListTimelineBlobsResult::Ready(RemoteTimelineBlobData { blob_data: BlobDataParseResult::Incorrect { errors, s3_layers }, unused_index_keys: index_part_keys, unknown_keys, })) } pub(crate) struct RemoteTenantManifestInfo { pub(crate) generation: Generation, pub(crate) manifest: TenantManifest, pub(crate) listing_object: ListingObject, } pub(crate) enum ListTenantManifestResult { WithErrors { errors: Vec<(String, String)>, #[allow(dead_code)] unknown_keys: Vec<ListingObject>, }, NoErrors { latest_generation: Option<RemoteTenantManifestInfo>, manifests: Vec<(Generation, ListingObject)>, }, } /// Lists the tenant manifests in remote storage and parses the latest one, returning a [`ListTenantManifestResult`] object. pub(crate) async fn list_tenant_manifests( remote_client: &GenericRemoteStorage, tenant_id: TenantShardId, root_target: &RootTarget, ) -> anyhow::Result<ListTenantManifestResult> { let mut errors = Vec::new(); let mut unknown_keys = Vec::new(); let mut tenant_root_target = root_target.tenant_root(&tenant_id); let original_prefix = tenant_root_target.prefix_in_bucket.clone(); const TENANT_MANIFEST_STEM: &str = "tenant-manifest"; tenant_root_target.prefix_in_bucket += TENANT_MANIFEST_STEM; tenant_root_target.delimiter = String::new(); let mut manifests: Vec<(Generation, ListingObject)> = Vec::new(); let prefix_str = &original_prefix .strip_prefix("/") .unwrap_or(&original_prefix); let mut stream = std::pin::pin!(stream_listing(remote_client, &tenant_root_target)); 'outer: while let Some(obj) = stream.next().await { let (key, Some(obj)) = obj? else { panic!("ListingObject not specified"); }; 'err: { // TODO a let chain would be nicer here. let Some(name) = key.object_name() else { break 'err; }; if !name.starts_with(TENANT_MANIFEST_STEM) { break 'err; } let Some(generation) = parse_remote_tenant_manifest_path(key.clone()) else { break 'err; }; tracing::debug!("tenant manifest {key}"); manifests.push((generation, obj)); continue 'outer; } tracing::info!("Listed an unknown key: {key}"); unknown_keys.push(obj); } if !unknown_keys.is_empty() { errors.push(((*prefix_str).to_owned(), "unknown keys listed".to_string())); return Ok(ListTenantManifestResult::WithErrors { errors, unknown_keys, }); } if manifests.is_empty() { tracing::debug!("No manifest for timeline."); return Ok(ListTenantManifestResult::NoErrors { latest_generation: None, manifests, }); } // Find the manifest with the highest generation let (latest_generation, latest_listing_object) = manifests .iter() .max_by_key(|i| i.0) .map(|(g, obj)| (*g, obj.clone())) .unwrap(); manifests.retain(|(gen_, _obj)| gen_ != &latest_generation); let manifest_bytes = match download_object_with_retries(remote_client, &latest_listing_object.key).await { Ok((bytes, _)) => bytes, Err(e) => { // It is possible that the tenant gets deleted in-between we list the objects // and we download the manifest file. errors.push(( latest_listing_object.key.get_path().as_str().to_owned(), format!("failed to download tenant-manifest.json: {e}"), )); return Ok(ListTenantManifestResult::WithErrors { errors, unknown_keys, }); } }; match TenantManifest::from_json_bytes(&manifest_bytes) { Ok(manifest) => { return Ok(ListTenantManifestResult::NoErrors { latest_generation: Some(RemoteTenantManifestInfo { generation: latest_generation, manifest, listing_object: latest_listing_object, }), manifests, }); } Err(parse_error) => errors.push(( latest_listing_object.key.get_path().as_str().to_owned(), format!("tenant-manifest.json body parsing error: {parse_error}"), )), } if errors.is_empty() { errors.push(( (*prefix_str).to_owned(), "Unexpected: no errors did not lead to a successfully parsed blob return".to_string(), )); } Ok(ListTenantManifestResult::WithErrors { errors, unknown_keys, }) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/scan_pageserver_metadata.rs
storage_scrubber/src/scan_pageserver_metadata.rs
use std::collections::{HashMap, HashSet}; use futures_util::{StreamExt, TryStreamExt}; use pageserver::tenant::remote_timeline_client::remote_layer_path; use pageserver_api::controller_api::MetadataHealthUpdateRequest; use pageserver_api::shard::TenantShardId; use remote_storage::GenericRemoteStorage; use serde::Serialize; use tracing::{Instrument, info_span}; use utils::id::TenantId; use utils::shard::ShardCount; use crate::checks::{ BlobDataParseResult, RemoteTimelineBlobData, TenantObjectListing, TimelineAnalysis, branch_cleanup_and_check_errors, list_timeline_blobs, }; use crate::metadata_stream::{stream_tenant_timelines, stream_tenants}; use crate::{BucketConfig, NodeKind, RootTarget, TenantShardTimelineId, init_remote}; #[derive(Serialize, Default)] pub struct MetadataSummary { tenant_count: usize, timeline_count: usize, timeline_shard_count: usize, /// Tenant-shard timeline (key) mapping to errors. The key has to be a string because it will be serialized to a JSON. /// The key is generated using `TenantShardTimelineId::to_string()`. with_errors: HashMap<String, Vec<String>>, /// Tenant-shard timeline (key) mapping to warnings. The key has to be a string because it will be serialized to a JSON. /// The key is generated using `TenantShardTimelineId::to_string()`. with_warnings: HashMap<String, Vec<String>>, with_orphans: HashSet<TenantShardTimelineId>, indices_by_version: HashMap<usize, usize>, #[serde(skip)] pub(crate) healthy_tenant_shards: HashSet<TenantShardId>, #[serde(skip)] pub(crate) unhealthy_tenant_shards: HashSet<TenantShardId>, } impl MetadataSummary { fn new() -> Self { Self::default() } fn update_data(&mut self, data: &RemoteTimelineBlobData) { self.timeline_shard_count += 1; if let BlobDataParseResult::Parsed { index_part, index_part_generation: _, s3_layers: _, index_part_last_modified_time: _, index_part_snapshot_time: _, } = &data.blob_data { *self .indices_by_version .entry(index_part.version()) .or_insert(0) += 1; } } fn update_analysis( &mut self, id: &TenantShardTimelineId, analysis: &TimelineAnalysis, verbose: bool, ) { if analysis.is_healthy() { self.healthy_tenant_shards.insert(id.tenant_shard_id); } else { self.healthy_tenant_shards.remove(&id.tenant_shard_id); self.unhealthy_tenant_shards.insert(id.tenant_shard_id); } if !analysis.errors.is_empty() { let entry = self.with_errors.entry(id.to_string()).or_default(); if verbose { entry.extend(analysis.errors.iter().cloned()); } } if !analysis.warnings.is_empty() { let entry = self.with_warnings.entry(id.to_string()).or_default(); if verbose { entry.extend(analysis.warnings.iter().cloned()); } } } fn notify_timeline_orphan(&mut self, ttid: &TenantShardTimelineId) { self.with_orphans.insert(*ttid); } /// Long-form output for printing at end of a scan pub fn summary_string(&self) -> String { let version_summary: String = itertools::join( self.indices_by_version .iter() .map(|(k, v)| format!("{k}: {v}")), ", ", ); format!( "Tenants: {} Timelines: {} Timeline-shards: {} With errors: {} With warnings: {} With orphan layers: {} Index versions: {version_summary} ", self.tenant_count, self.timeline_count, self.timeline_shard_count, self.with_errors.len(), self.with_warnings.len(), self.with_orphans.len(), ) } pub fn is_fatal(&self) -> bool { !self.with_errors.is_empty() } pub fn is_empty(&self) -> bool { self.timeline_shard_count == 0 } pub fn build_health_update_request(&self) -> MetadataHealthUpdateRequest { MetadataHealthUpdateRequest { healthy_tenant_shards: self.healthy_tenant_shards.clone(), unhealthy_tenant_shards: self.unhealthy_tenant_shards.clone(), } } } /// Scan the pageserver metadata in an S3 bucket, reporting errors and statistics. pub async fn scan_pageserver_metadata( bucket_config: BucketConfig, tenant_ids: Vec<TenantShardId>, verbose: bool, ) -> anyhow::Result<MetadataSummary> { let (remote_client, target) = init_remote(bucket_config, NodeKind::Pageserver).await?; let tenants = if tenant_ids.is_empty() { futures::future::Either::Left(stream_tenants(&remote_client, &target)) } else { futures::future::Either::Right(futures::stream::iter(tenant_ids.into_iter().map(Ok))) }; // How many tenants to process in parallel. We need to be mindful of pageservers // accessing the same per tenant prefixes, so use a lower setting than pageservers. const CONCURRENCY: usize = 32; // Generate a stream of TenantTimelineId let timelines = tenants.map_ok(|t| { tracing::info!("Found tenant: {}", t); stream_tenant_timelines(&remote_client, &target, t) }); let timelines = timelines.try_buffered(CONCURRENCY); let timelines = timelines.try_flatten(); // Generate a stream of S3TimelineBlobData async fn report_on_timeline( remote_client: &GenericRemoteStorage, target: &RootTarget, ttid: TenantShardTimelineId, ) -> anyhow::Result<(TenantShardTimelineId, RemoteTimelineBlobData)> { let data = list_timeline_blobs(remote_client, ttid, target).await?; Ok((ttid, data)) } let timelines = timelines.map_ok(|ttid| report_on_timeline(&remote_client, &target, ttid)); let mut timelines = std::pin::pin!(timelines.try_buffered(CONCURRENCY)); // We must gather all the TenantShardTimelineId->S3TimelineBlobData for each tenant, because different // shards in the same tenant might refer to one anothers' keys if a shard split has happened. let mut tenant_id = None; let mut tenant_objects = TenantObjectListing::default(); let mut tenant_timeline_results = Vec::new(); async fn analyze_tenant( remote_client: &GenericRemoteStorage, tenant_id: TenantId, summary: &mut MetadataSummary, mut tenant_objects: TenantObjectListing, timelines: Vec<(TenantShardTimelineId, RemoteTimelineBlobData)>, highest_shard_count: ShardCount, verbose: bool, ) { summary.tenant_count += 1; let mut timeline_ids = HashSet::new(); let mut timeline_generations = HashMap::new(); for (ttid, data) in timelines { async { if ttid.tenant_shard_id.shard_count == highest_shard_count { // Only analyze `TenantShardId`s with highest shard count. // Stash the generation of each timeline, for later use identifying orphan layers if let BlobDataParseResult::Parsed { index_part, index_part_generation, s3_layers: _, index_part_last_modified_time: _, index_part_snapshot_time: _, } = &data.blob_data { if index_part.deleted_at.is_some() { // skip deleted timeline. tracing::info!( "Skip analysis of {} b/c timeline is already deleted", ttid ); return; } timeline_generations.insert(ttid, *index_part_generation); } // Apply checks to this timeline shard's metadata, and in the process update `tenant_objects` // reference counts for layers across the tenant. let analysis = branch_cleanup_and_check_errors( remote_client, &ttid, &mut tenant_objects, None, None, Some(data), ) .await; summary.update_analysis(&ttid, &analysis, verbose); timeline_ids.insert(ttid.timeline_id); } else { tracing::info!( "Skip analysis of {} b/c a lower shard count than {}", ttid, highest_shard_count.0, ); } } .instrument( info_span!("analyze-timeline", shard = %ttid.tenant_shard_id.shard_slug(), timeline = %ttid.timeline_id), ) .await } summary.timeline_count += timeline_ids.len(); // Identifying orphan layers must be done on a tenant-wide basis, because individual // shards' layers may be referenced by other shards. // // Orphan layers are not a corruption, and not an indication of a problem. They are just // consuming some space in remote storage, and may be cleaned up at leisure. for (shard_index, timeline_id, layer_file, generation) in tenant_objects.get_orphans() { let ttid = TenantShardTimelineId { tenant_shard_id: TenantShardId { tenant_id, shard_count: shard_index.shard_count, shard_number: shard_index.shard_number, }, timeline_id, }; if let Some(timeline_generation) = timeline_generations.get(&ttid) { if &generation >= timeline_generation { // Candidate orphan layer is in the current or future generation relative // to the index we read for this timeline shard, so its absence from the index // doesn't make it an orphan: more likely, it is a case where the layer was // uploaded, but the index referencing the layer wasn't written yet. continue; } } let orphan_path = remote_layer_path( &tenant_id, &timeline_id, shard_index, &layer_file, generation, ); tracing::info!("Orphan layer detected: {orphan_path}"); summary.notify_timeline_orphan(&ttid); } } // Iterate through all the timeline results. These are in key-order, so // all results for the same tenant will be adjacent. We accumulate these, // and then call `analyze_tenant` to flush, when we see the next tenant ID. let mut summary = MetadataSummary::new(); let mut highest_shard_count = ShardCount::MIN; while let Some(i) = timelines.next().await { let (ttid, data) = i?; summary.update_data(&data); match tenant_id { Some(prev_tenant_id) => { if prev_tenant_id != ttid.tenant_shard_id.tenant_id { // New tenant: analyze this tenant's timelines, clear accumulated tenant_timeline_results let tenant_objects = std::mem::take(&mut tenant_objects); let timelines = std::mem::take(&mut tenant_timeline_results); analyze_tenant( &remote_client, prev_tenant_id, &mut summary, tenant_objects, timelines, highest_shard_count, verbose, ) .instrument(info_span!("analyze-tenant", tenant = %prev_tenant_id)) .await; tenant_id = Some(ttid.tenant_shard_id.tenant_id); highest_shard_count = ttid.tenant_shard_id.shard_count; } else { highest_shard_count = highest_shard_count.max(ttid.tenant_shard_id.shard_count); } } None => { tenant_id = Some(ttid.tenant_shard_id.tenant_id); highest_shard_count = highest_shard_count.max(ttid.tenant_shard_id.shard_count); } } match &data.blob_data { BlobDataParseResult::Parsed { index_part: _, index_part_generation: _index_part_generation, s3_layers, index_part_last_modified_time: _, index_part_snapshot_time: _, } => { tenant_objects.push(ttid, s3_layers.clone()); } BlobDataParseResult::Relic => (), BlobDataParseResult::Incorrect { errors: _, s3_layers, } => { tenant_objects.push(ttid, s3_layers.clone()); } } tenant_timeline_results.push((ttid, data)); } if !tenant_timeline_results.is_empty() { let tenant_id = tenant_id.expect("Must be set if results are present"); analyze_tenant( &remote_client, tenant_id, &mut summary, tenant_objects, tenant_timeline_results, highest_shard_count, verbose, ) .instrument(info_span!("analyze-tenant", tenant = %tenant_id)) .await; } Ok(summary) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/scan_safekeeper_metadata.rs
storage_scrubber/src/scan_safekeeper_metadata.rs
use std::collections::HashSet; use std::str::FromStr; use std::sync::Arc; use anyhow::{Context, bail}; use futures::stream::{StreamExt, TryStreamExt}; use once_cell::sync::OnceCell; use pageserver_api::shard::TenantShardId; use postgres_ffi::{PG_TLI, XLogFileName}; use remote_storage::GenericRemoteStorage; use rustls::crypto::ring; use serde::Serialize; use tokio_postgres::types::PgLsn; use tracing::{debug, error, info}; use utils::id::{TenantId, TenantTimelineId, TimelineId}; use utils::lsn::Lsn; use crate::cloud_admin_api::CloudAdminApiClient; use crate::metadata_stream::stream_listing; use crate::{ BucketConfig, ConsoleConfig, NodeKind, RootTarget, TenantShardTimelineId, init_remote, }; /// Generally we should ask safekeepers, but so far we use everywhere default 16MB. const WAL_SEGSIZE: usize = 16 * 1024 * 1024; #[derive(Serialize)] pub struct MetadataSummary { timeline_count: usize, with_errors: HashSet<TenantTimelineId>, deleted_count: usize, } impl MetadataSummary { fn new() -> Self { Self { timeline_count: 0, with_errors: HashSet::new(), deleted_count: 0, } } pub fn summary_string(&self) -> String { format!( "timeline_count: {}, with_errors: {}", self.timeline_count, self.with_errors.len() ) } pub fn is_empty(&self) -> bool { self.timeline_count == 0 } pub fn is_fatal(&self) -> bool { !self.with_errors.is_empty() } } #[derive(serde::Deserialize)] pub struct TimelineLsnData { tenant_id: String, timeline_id: String, timeline_start_lsn: Lsn, backup_lsn: Lsn, } pub enum DatabaseOrList { Database { tenant_ids: Vec<TenantId>, connstr: String, table: String, }, List(Vec<TimelineLsnData>), } /// Scan the safekeeper metadata in an S3 bucket, reporting errors and /// statistics. /// /// It works by listing timelines along with timeline_start_lsn and backup_lsn /// in debug dump in dump_db_table and verifying its s3 contents. If some WAL /// segments are missing, before complaining control plane is queried to check if /// the project wasn't deleted in the meanwhile. pub async fn scan_safekeeper_metadata( bucket_config: BucketConfig, db_or_list: DatabaseOrList, ) -> anyhow::Result<MetadataSummary> { info!("checking {}", bucket_config.desc_str()); let (remote_client, target) = init_remote(bucket_config, NodeKind::Safekeeper).await?; let console_config = ConsoleConfig::from_env()?; let cloud_admin_api_client = CloudAdminApiClient::new(console_config); let timelines = match db_or_list { DatabaseOrList::Database { tenant_ids, connstr, table, } => load_timelines_from_db(tenant_ids, connstr, table).await?, DatabaseOrList::List(list) => list, }; info!("loaded {} timelines", timelines.len()); let checks = futures::stream::iter(timelines.into_iter().map(Ok)).map_ok(|timeline| { let tenant_id = TenantId::from_str(&timeline.tenant_id).expect("failed to parse tenant_id"); let timeline_id = TimelineId::from_str(&timeline.timeline_id).expect("failed to parse tenant_id"); let ttid = TenantTimelineId::new(tenant_id, timeline_id); check_timeline( &remote_client, &target, &cloud_admin_api_client, ttid, timeline.timeline_start_lsn, timeline.backup_lsn, ) }); // Run multiple check_timeline's concurrently. const CONCURRENCY: usize = 32; let mut timelines = checks.try_buffered(CONCURRENCY); let mut summary = MetadataSummary::new(); while let Some(r) = timelines.next().await { let res = r?; summary.timeline_count += 1; if !res.is_ok { summary.with_errors.insert(res.ttid); } if res.is_deleted { summary.deleted_count += 1; } } Ok(summary) } struct TimelineCheckResult { ttid: TenantTimelineId, is_ok: bool, is_deleted: bool, // timeline is deleted in cplane } /// List s3 and check that is has all expected WAL for the ttid. Consistency /// errors are logged to stderr; returns Ok(true) if timeline is consistent, /// Ok(false) if not, Err if failed to check. async fn check_timeline( remote_client: &GenericRemoteStorage, root: &RootTarget, api_client: &CloudAdminApiClient, ttid: TenantTimelineId, timeline_start_lsn: Lsn, backup_lsn: Lsn, ) -> anyhow::Result<TimelineCheckResult> { debug!( "checking ttid {}, should contain WAL [{}-{}]", ttid, timeline_start_lsn, backup_lsn ); // calculate expected segfiles let expected_first_segno = timeline_start_lsn.segment_number(WAL_SEGSIZE); let expected_last_segno = backup_lsn.segment_number(WAL_SEGSIZE); let mut expected_segfiles: HashSet<String> = HashSet::from_iter( (expected_first_segno..expected_last_segno) .map(|segno| XLogFileName(PG_TLI, segno, WAL_SEGSIZE)), ); let expected_files_num = expected_segfiles.len(); debug!("expecting {} files", expected_segfiles.len(),); // now list s3 and check if it misses something let ttshid = TenantShardTimelineId::new(TenantShardId::unsharded(ttid.tenant_id), ttid.timeline_id); let mut timeline_dir_target = root.timeline_root(&ttshid); // stream_listing yields only common_prefixes if delimiter is not empty, but // we need files, so unset it. timeline_dir_target.delimiter = String::new(); let prefix_str = &timeline_dir_target .prefix_in_bucket .strip_prefix("/") .unwrap_or(&timeline_dir_target.prefix_in_bucket); let mut stream = std::pin::pin!(stream_listing(remote_client, &timeline_dir_target)); while let Some(obj) = stream.next().await { let (key, _obj) = obj?; let seg_name = key .get_path() .as_str() .strip_prefix(prefix_str) .expect("failed to extract segment name"); expected_segfiles.remove(seg_name); } if !expected_segfiles.is_empty() { // Before complaining check cplane, probably timeline is already deleted. let bdata = api_client .find_timeline_branch(ttid.tenant_id, ttid.timeline_id) .await?; let deleted = match bdata { Some(bdata) => bdata.deleted, None => { // note: should be careful with selecting proper cplane address info!("ttid {} not found, assuming it is deleted", ttid); true } }; if deleted { // ok, branch is deleted return Ok(TimelineCheckResult { ttid, is_ok: true, is_deleted: true, }); } error!( "ttid {}: missing {} files out of {}, timeline_start_lsn {}, wal_backup_lsn {}", ttid, expected_segfiles.len(), expected_files_num, timeline_start_lsn, backup_lsn, ); return Ok(TimelineCheckResult { ttid, is_ok: false, is_deleted: false, }); } Ok(TimelineCheckResult { ttid, is_ok: true, is_deleted: false, }) } fn load_certs() -> anyhow::Result<Arc<rustls::RootCertStore>> { let der_certs = rustls_native_certs::load_native_certs(); if !der_certs.errors.is_empty() { bail!("could not load native tls certs: {:?}", der_certs.errors); } let mut store = rustls::RootCertStore::empty(); store.add_parsable_certificates(der_certs.certs); Ok(Arc::new(store)) } static TLS_ROOTS: OnceCell<Arc<rustls::RootCertStore>> = OnceCell::new(); async fn load_timelines_from_db( tenant_ids: Vec<TenantId>, dump_db_connstr: String, dump_db_table: String, ) -> anyhow::Result<Vec<TimelineLsnData>> { info!("loading from table {dump_db_table}"); // Use rustls (Neon requires TLS) let root_store = TLS_ROOTS.get_or_try_init(load_certs)?.clone(); let client_config = rustls::ClientConfig::builder_with_provider(Arc::new(ring::default_provider())) .with_safe_default_protocol_versions() .context("ring should support the default protocol versions")? .with_root_certificates(root_store) .with_no_client_auth(); let tls_connector = tokio_postgres_rustls::MakeRustlsConnect::new(client_config); let (client, connection) = tokio_postgres::connect(&dump_db_connstr, tls_connector).await?; // The connection object performs the actual communication with the database, // so spawn it off to run on its own. tokio::spawn(async move { if let Err(e) = connection.await { eprintln!("connection error: {e}"); } }); let tenant_filter_clause = if !tenant_ids.is_empty() { format!( "and tenant_id in ({})", tenant_ids .iter() .map(|t| format!("'{t}'")) .collect::<Vec<_>>() .join(", ") ) } else { "".to_owned() }; let query = format!( "select tenant_id, timeline_id, min(timeline_start_lsn), max(backup_lsn) \ from \"{dump_db_table}\" \ where not is_cancelled {tenant_filter_clause} \ group by tenant_id, timeline_id;" ); info!("query is {}", query); let timelines = client.query(&query, &[]).await?; let timelines = timelines .into_iter() .map(|row| { let tenant_id = row.get(0); let timeline_id = row.get(1); let timeline_start_lsn_pg: PgLsn = row.get(2); let backup_lsn_pg: PgLsn = row.get(3); TimelineLsnData { tenant_id, timeline_id, timeline_start_lsn: Lsn(u64::from(timeline_start_lsn_pg)), backup_lsn: Lsn(u64::from(backup_lsn_pg)), } }) .collect::<Vec<TimelineLsnData>>(); Ok(timelines) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/cloud_admin_api.rs
storage_scrubber/src/cloud_admin_api.rs
use std::error::Error as _; use chrono::{DateTime, Utc}; use futures::Future; use hex::FromHex; use reqwest::{Client, StatusCode, Url, header}; use serde::Deserialize; use tokio::sync::Semaphore; use tokio_util::sync::CancellationToken; use utils::backoff; use utils::id::{TenantId, TimelineId}; use utils::lsn::Lsn; use crate::ConsoleConfig; #[derive(Debug)] pub struct Error { context: String, kind: ErrorKind, } impl Error { fn new(context: String, kind: ErrorKind) -> Self { Self { context, kind } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ErrorKind::RequestSend(e) => write!( f, "Failed to send a request. Context: {}, error: {}{}", self.context, e, e.source().map(|e| format!(": {e}")).unwrap_or_default() ), ErrorKind::BodyRead(e) => { write!( f, "Failed to read a request body. Context: {}, error: {}{}", self.context, e, e.source().map(|e| format!(": {e}")).unwrap_or_default() ) } ErrorKind::ResponseStatus(status) => { write!(f, "Bad response status {}: {}", status, self.context) } ErrorKind::UnexpectedState => write!(f, "Unexpected state: {}", self.context), } } } #[derive(Debug, Clone, serde::Deserialize, Hash, PartialEq, Eq)] #[serde(transparent)] pub struct ProjectId(pub String); #[derive(Clone, Debug, serde::Deserialize, Hash, PartialEq, Eq)] #[serde(transparent)] pub struct BranchId(pub String); impl std::error::Error for Error {} #[derive(Debug)] pub enum ErrorKind { RequestSend(reqwest::Error), BodyRead(reqwest::Error), ResponseStatus(StatusCode), UnexpectedState, } pub struct CloudAdminApiClient { request_limiter: Semaphore, token: String, base_url: Url, http_client: Client, } #[derive(Debug, serde::Deserialize)] struct AdminApiResponse<T> { data: T, total: Option<usize>, } #[derive(Debug, serde::Deserialize)] pub struct PageserverData { pub id: u64, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub region_id: String, pub version: i64, pub instance_id: String, pub port: u16, pub http_host: String, pub http_port: u16, pub active: bool, pub projects_count: usize, pub availability_zone_id: String, } #[derive(Debug, Clone, serde::Deserialize)] pub struct SafekeeperData { pub id: u64, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub region_id: String, pub version: i64, pub instance_id: String, pub active: bool, pub host: String, pub port: u16, pub projects_count: usize, pub availability_zone_id: String, } /// For ID fields, the Console API does not always return a value or null. It will /// sometimes return an empty string. Our native Id type does not consider this acceptable /// (nor should it), so we use a wrapper for talking to the Console API. fn from_nullable_id<'de, D>(deserializer: D) -> Result<TenantId, D::Error> where D: serde::de::Deserializer<'de>, { if deserializer.is_human_readable() { let id_str = String::deserialize(deserializer)?; if id_str.is_empty() { // This is a bogus value, but for the purposes of the scrubber all that // matters is that it doesn't collide with any real IDs. Ok(TenantId::from([0u8; 16])) } else { TenantId::from_hex(&id_str).map_err(|e| serde::de::Error::custom(format!("{e}"))) } } else { let id_arr = <[u8; 16]>::deserialize(deserializer)?; Ok(TenantId::from(id_arr)) } } #[derive(Debug, Clone, serde::Deserialize)] pub struct ProjectData { pub id: ProjectId, pub name: String, pub region_id: String, pub platform_id: String, pub user_id: Option<String>, pub pageserver_id: Option<u64>, #[serde(deserialize_with = "from_nullable_id")] pub tenant: TenantId, pub safekeepers: Vec<SafekeeperData>, pub deleted: bool, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub pg_version: u32, pub max_project_size: i64, pub remote_storage_size: u64, pub resident_size: u64, pub synthetic_storage_size: u64, pub compute_time: u64, pub data_transfer: u64, pub data_storage: u64, pub maintenance_set: Option<String>, } #[derive(Debug, Clone, serde::Deserialize)] pub struct BranchData { pub id: BranchId, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub name: String, pub project_id: ProjectId, pub timeline_id: TimelineId, #[serde(default)] pub parent_id: Option<BranchId>, #[serde(default)] pub parent_lsn: Option<Lsn>, pub default: bool, pub deleted: bool, pub logical_size: Option<u64>, pub physical_size: Option<u64>, pub written_size: Option<u64>, } pub trait MaybeDeleted { fn is_deleted(&self) -> bool; } impl MaybeDeleted for ProjectData { fn is_deleted(&self) -> bool { self.deleted } } impl MaybeDeleted for BranchData { fn is_deleted(&self) -> bool { self.deleted } } impl CloudAdminApiClient { pub fn new(config: ConsoleConfig) -> Self { Self { token: config.token, base_url: config.base_url, request_limiter: Semaphore::new(200), http_client: Client::new(), // TODO timeout configs at least } } pub async fn find_tenant_project( &self, tenant_id: TenantId, ) -> Result<Option<ProjectData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = CloudAdminApiClient::with_retries( || async { let response = self .http_client .get(self.append_url("/projects")) .query(&[ ("tenant_id", tenant_id.to_string()), ("show_deleted", "true".to_string()), ]) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| { Error::new( "Find project for tenant".to_string(), ErrorKind::RequestSend(e), ) })?; let response: AdminApiResponse<Vec<ProjectData>> = response.json().await.map_err(|e| { Error::new( "Find project for tenant".to_string(), ErrorKind::BodyRead(e), ) })?; Ok(response) }, "find_tenant_project", ) .await?; match response.data.len() { 0 => Ok(None), 1 => Ok(Some( response .data .into_iter() .next() .expect("Should have exactly one element"), )), too_many => Err(Error::new( format!("Find project for tenant returned {too_many} projects instead of 0 or 1"), ErrorKind::UnexpectedState, )), } } pub async fn list_projects(&self) -> Result<Vec<ProjectData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let mut pagination_offset = 0; const PAGINATION_LIMIT: usize = 512; let mut result: Vec<ProjectData> = Vec::with_capacity(PAGINATION_LIMIT); loop { let response_bytes = CloudAdminApiClient::with_retries( || async { let response = self .http_client .get(self.append_url("/projects")) .query(&[ ("show_deleted", "false".to_string()), ("limit", format!("{PAGINATION_LIMIT}")), ("offset", format!("{pagination_offset}")), ]) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| { Error::new( "List active projects".to_string(), ErrorKind::RequestSend(e), ) })?; response.bytes().await.map_err(|e| { Error::new("List active projects".to_string(), ErrorKind::BodyRead(e)) }) }, "list_projects", ) .await?; let decode_result = serde_json::from_slice::<AdminApiResponse<Vec<ProjectData>>>(&response_bytes); let mut response = match decode_result { Ok(r) => r, Err(decode) => { tracing::error!( "Failed to decode response body: {}\n{}", decode, String::from_utf8(response_bytes.to_vec()).unwrap() ); panic!("we out"); } }; pagination_offset += response.data.len(); result.append(&mut response.data); if pagination_offset >= response.total.unwrap_or(0) { break; } } Ok(result) } pub async fn find_timeline_branch( &self, tenant_id: TenantId, timeline_id: TimelineId, ) -> Result<Option<BranchData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = CloudAdminApiClient::with_retries( || async { let response = self .http_client .get(self.append_url("/branches")) .query(&[ ("timeline_id", timeline_id.to_string()), ("show_deleted", "true".to_string()), ]) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| { Error::new( "Find branch for timeline".to_string(), ErrorKind::RequestSend(e), ) })?; let response: AdminApiResponse<Vec<BranchData>> = response.json().await.map_err(|e| { Error::new( "Find branch for timeline".to_string(), ErrorKind::BodyRead(e), ) })?; Ok(response) }, "find_timeline_branch", ) .await?; let mut branches: Vec<BranchData> = response.data.into_iter().collect(); // Normally timeline_id is unique. However, we do have at least one case // of the same timeline_id in two different projects, apparently after // manual recovery. So always recheck project_id (discovered through // tenant_id). let project_data = match self.find_tenant_project(tenant_id).await? { Some(pd) => pd, None => return Ok(None), }; branches.retain(|b| b.project_id == project_data.id); if branches.len() < 2 { Ok(branches.first().cloned()) } else { Err(Error::new( format!( "Find branch for timeline {}/{} returned {} branches instead of 0 or 1", tenant_id, timeline_id, branches.len() ), ErrorKind::UnexpectedState, )) } } pub async fn list_pageservers(&self) -> Result<Vec<PageserverData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = self .http_client .get(self.append_url("/pageservers")) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| Error::new("List pageservers".to_string(), ErrorKind::RequestSend(e)))?; let response: AdminApiResponse<Vec<PageserverData>> = response .json() .await .map_err(|e| Error::new("List pageservers".to_string(), ErrorKind::BodyRead(e)))?; Ok(response.data) } pub async fn list_safekeepers(&self) -> Result<Vec<SafekeeperData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = self .http_client .get(self.append_url("/safekeepers")) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| Error::new("List safekeepers".to_string(), ErrorKind::RequestSend(e)))?; let response: AdminApiResponse<Vec<SafekeeperData>> = response .json() .await .map_err(|e| Error::new("List safekeepers".to_string(), ErrorKind::BodyRead(e)))?; Ok(response.data) } pub async fn projects_for_pageserver( &self, pageserver_id: u64, show_deleted: bool, ) -> Result<Vec<ProjectData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = self .http_client .get(self.append_url("/projects")) .query(&[ ("pageserver_id", &pageserver_id.to_string()), ("show_deleted", &show_deleted.to_string()), ]) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| Error::new("Project for tenant".to_string(), ErrorKind::RequestSend(e)))?; let response: AdminApiResponse<Vec<ProjectData>> = response .json() .await .map_err(|e| Error::new("Project for tenant".to_string(), ErrorKind::BodyRead(e)))?; Ok(response.data) } pub async fn project_for_tenant( &self, tenant_id: TenantId, show_deleted: bool, ) -> Result<Option<ProjectData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = self .http_client .get(self.append_url("/projects")) .query(&[ ("search", &tenant_id.to_string()), ("show_deleted", &show_deleted.to_string()), ]) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| Error::new("Project for tenant".to_string(), ErrorKind::RequestSend(e)))?; let response: AdminApiResponse<Vec<ProjectData>> = response .json() .await .map_err(|e| Error::new("Project for tenant".to_string(), ErrorKind::BodyRead(e)))?; match response.data.as_slice() { [] => Ok(None), [_single] => Ok(Some(response.data.into_iter().next().unwrap())), multiple => Err(Error::new( format!("Got more than one project for tenant {tenant_id} : {multiple:?}"), ErrorKind::UnexpectedState, )), } } pub async fn branches_for_project( &self, project_id: &ProjectId, show_deleted: bool, ) -> Result<Vec<BranchData>, Error> { let _permit = self .request_limiter .acquire() .await .expect("Semaphore is not closed"); let response = self .http_client .get(self.append_url("/branches")) .query(&[ ("project_id", &project_id.0), ("show_deleted", &show_deleted.to_string()), ]) .header(header::ACCEPT, "application/json") .bearer_auth(&self.token) .send() .await .map_err(|e| Error::new("Project for tenant".to_string(), ErrorKind::RequestSend(e)))?; let response: AdminApiResponse<Vec<BranchData>> = response .json() .await .map_err(|e| Error::new("Project for tenant".to_string(), ErrorKind::BodyRead(e)))?; Ok(response.data) } fn append_url(&self, subpath: &str) -> Url { // TODO fugly, but `.join` does not work when called (self.base_url.to_string() + subpath) .parse() .unwrap_or_else(|e| panic!("Could not append {subpath} to base url: {e}")) } async fn with_retries<T, O, F>(op: O, description: &str) -> Result<T, Error> where O: FnMut() -> F, F: Future<Output = Result<T, Error>>, { let cancel = CancellationToken::new(); // not really used backoff::retry(op, |_| false, 1, 20, description, &cancel) .await .expect("cancellations are disabled") } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/garbage.rs
storage_scrubber/src/garbage.rs
//! Functionality for finding and purging garbage, as in "garbage collection". //! //! Garbage means S3 objects which are either not referenced by any metadata, //! or are referenced by a control plane tenant/timeline in a deleted state. use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::Duration; use anyhow::Context; use futures_util::TryStreamExt; use pageserver_api::shard::TenantShardId; use remote_storage::{GenericRemoteStorage, ListingMode, ListingObject, RemotePath}; use serde::{Deserialize, Serialize}; use tokio_stream::StreamExt; use tokio_util::sync::CancellationToken; use utils::backoff; use utils::id::TenantId; use crate::cloud_admin_api::{CloudAdminApiClient, MaybeDeleted, ProjectData}; use crate::metadata_stream::{stream_tenant_timelines, stream_tenants_maybe_prefix}; use crate::{ BucketConfig, ConsoleConfig, MAX_RETRIES, NodeKind, TenantShardTimelineId, TraversingDepth, init_remote, list_objects_with_retries, }; #[derive(Serialize, Deserialize, Debug)] enum GarbageReason { DeletedInConsole, MissingInConsole, // The remaining data relates to a known deletion issue, and we're sure that purging this // will not delete any real data, for example https://github.com/neondatabase/neon/pull/7928 where // there is nothing in a tenant path apart from a heatmap file. KnownBug, } #[derive(Serialize, Deserialize, Debug)] enum GarbageEntity { Tenant(TenantShardId), Timeline(TenantShardTimelineId), } #[derive(Serialize, Deserialize, Debug)] struct GarbageItem { entity: GarbageEntity, reason: GarbageReason, } #[derive(Serialize, Deserialize, Debug)] pub struct GarbageList { /// Remember what NodeKind we were finding garbage for, so that we can /// purge the list without re-stating it. node_kind: NodeKind, /// Embed the identity of the bucket, so that we do not risk executing /// the wrong list against the wrong bucket, and so that the user does not have /// to re-state the bucket details when purging. bucket_config: BucketConfig, items: Vec<GarbageItem>, /// Advisory information to enable consumers to do a validation that if we /// see garbage, we saw some active tenants too. This protects against classes of bugs /// in the scrubber that might otherwise generate a "deleted all" result. active_tenant_count: usize, active_timeline_count: usize, } impl GarbageList { fn new(node_kind: NodeKind, bucket_config: BucketConfig) -> Self { Self { items: Vec::new(), active_tenant_count: 0, active_timeline_count: 0, node_kind, bucket_config, } } /// If an entity has been identified as requiring purge due to a known bug, e.g. /// a particular type of object left behind after an incomplete deletion. fn append_buggy(&mut self, entity: GarbageEntity) { self.items.push(GarbageItem { entity, reason: GarbageReason::KnownBug, }); } /// Return true if appended, false if not. False means the result was not garbage. fn maybe_append<T>(&mut self, entity: GarbageEntity, result: Option<T>) -> bool where T: MaybeDeleted, { match result { Some(result_item) if result_item.is_deleted() => { self.items.push(GarbageItem { entity, reason: GarbageReason::DeletedInConsole, }); true } Some(_) => false, None => { self.items.push(GarbageItem { entity, reason: GarbageReason::MissingInConsole, }); true } } } } pub async fn find_garbage( bucket_config: BucketConfig, console_config: ConsoleConfig, depth: TraversingDepth, node_kind: NodeKind, tenant_id_prefix: Option<String>, output_path: String, ) -> anyhow::Result<()> { let garbage = find_garbage_inner( bucket_config, console_config, depth, node_kind, tenant_id_prefix, ) .await?; let serialized = serde_json::to_vec_pretty(&garbage)?; tokio::fs::write(&output_path, &serialized).await?; tracing::info!("Wrote garbage report to {output_path}"); Ok(()) } // How many concurrent S3 operations to issue (approximately): this is the concurrency // for things like listing the timelines within tenant prefixes. const S3_CONCURRENCY: usize = 32; // How many concurrent API requests to make to the console API. // // Be careful increasing this; roughly we shouldn't have more than ~100 rps. It // would be better to implement real rsp limiter. const CONSOLE_CONCURRENCY: usize = 16; struct ConsoleCache { /// Set of tenants found in the control plane API projects: HashMap<TenantId, ProjectData>, /// Set of tenants for which the control plane API returned 404 not_found: HashSet<TenantId>, } async fn find_garbage_inner( bucket_config: BucketConfig, console_config: ConsoleConfig, depth: TraversingDepth, node_kind: NodeKind, tenant_id_prefix: Option<String>, ) -> anyhow::Result<GarbageList> { // Construct clients for S3 and for Console API let (remote_client, target) = init_remote(bucket_config.clone(), node_kind).await?; let cloud_admin_api_client = Arc::new(CloudAdminApiClient::new(console_config)); // Build a set of console-known tenants, for quickly eliminating known-active tenants without having // to issue O(N) console API requests. let console_projects: HashMap<TenantId, ProjectData> = cloud_admin_api_client .list_projects() .await? .into_iter() .map(|t| (t.tenant, t)) .collect(); tracing::info!( "Loaded {} console projects tenant IDs", console_projects.len() ); // Because many tenant shards may look up the same TenantId, we maintain a cache. let console_cache = Arc::new(std::sync::Mutex::new(ConsoleCache { projects: console_projects, not_found: HashSet::new(), })); // Enumerate Tenants in S3, and check if each one exists in Console tracing::info!("Finding all tenants in {}...", bucket_config.desc_str()); let tenants = stream_tenants_maybe_prefix(&remote_client, &target, tenant_id_prefix); let tenants_checked = tenants.map_ok(|t| { let api_client = cloud_admin_api_client.clone(); let console_cache = console_cache.clone(); async move { // Check cache before issuing API call let project_data = { let cache = console_cache.lock().unwrap(); let result = cache.projects.get(&t.tenant_id).cloned(); if result.is_none() && cache.not_found.contains(&t.tenant_id) { return Ok((t, None)); } result }; match project_data { Some(project_data) => Ok((t, Some(project_data.clone()))), None => { let project_data = api_client .find_tenant_project(t.tenant_id) .await .map_err(|e| anyhow::anyhow!(e)); // Populate cache with result of API call { let mut cache = console_cache.lock().unwrap(); if let Ok(Some(project_data)) = &project_data { cache.projects.insert(t.tenant_id, project_data.clone()); } else if let Ok(None) = &project_data { cache.not_found.insert(t.tenant_id); } } project_data.map(|r| (t, r)) } } } }); let mut tenants_checked = std::pin::pin!(tenants_checked.try_buffer_unordered(CONSOLE_CONCURRENCY)); // Process the results of Tenant checks. If a Tenant is garbage, it goes into // the `GarbageList`. Else it goes into `active_tenants` for more detailed timeline // checks if they are enabled by the `depth` parameter. let mut garbage = GarbageList::new(node_kind, bucket_config); let mut active_tenants: Vec<TenantShardId> = vec![]; let mut counter = 0; while let Some(result) = tenants_checked.next().await { let (tenant_shard_id, console_result) = result?; // Paranoia check if let Some(project) = &console_result { assert!(project.tenant == tenant_shard_id.tenant_id); } // Special case: If it's missing in console, check for known bugs that would enable us to conclusively // identify it as purge-able anyway if console_result.is_none() { let timelines = stream_tenant_timelines(&remote_client, &target, tenant_shard_id) .await? .collect::<Vec<_>>() .await; if timelines.is_empty() { // No timelines, but a heatmap: the deletion bug where we deleted everything but heatmaps let tenant_objects = list_objects_with_retries( &remote_client, ListingMode::WithDelimiter, &target.tenant_root(&tenant_shard_id), ) .await?; if let Some(object) = tenant_objects.keys.first() { if object.key.get_path().as_str().ends_with("heatmap-v1.json") { tracing::info!( "Tenant {tenant_shard_id}: is missing in console and is only a heatmap (known historic deletion bug)" ); garbage.append_buggy(GarbageEntity::Tenant(tenant_shard_id)); continue; } else { tracing::info!( "Tenant {tenant_shard_id} is missing in console and contains one object: {}", object.key ); } } else { tracing::info!( "Tenant {tenant_shard_id} is missing in console appears to have been deleted while we ran" ); } } else { // A console-unknown tenant with timelines: check if these timelines only contain initdb.tar.zst, from the initial // rollout of WAL DR in which we never deleted these. let mut any_non_initdb = false; for timeline_r in timelines { let timeline = timeline_r?; let timeline_objects = list_objects_with_retries( &remote_client, ListingMode::WithDelimiter, &target.timeline_root(&timeline), ) .await?; if !timeline_objects.prefixes.is_empty() { // Sub-paths? Unexpected any_non_initdb = true; } else { let object = timeline_objects.keys.first().unwrap(); if object.key.get_path().as_str().ends_with("initdb.tar.zst") { tracing::info!("Timeline {timeline} contains only initdb.tar.zst"); } else { any_non_initdb = true; } } } if any_non_initdb { tracing::info!( "Tenant {tenant_shard_id}: is missing in console and contains timelines, one or more of which are more than just initdb" ); } else { tracing::info!( "Tenant {tenant_shard_id}: is missing in console and contains only timelines that only contain initdb" ); garbage.append_buggy(GarbageEntity::Tenant(tenant_shard_id)); continue; } } } if garbage.maybe_append(GarbageEntity::Tenant(tenant_shard_id), console_result) { tracing::debug!("Tenant {tenant_shard_id} is garbage"); } else { tracing::debug!("Tenant {tenant_shard_id} is active"); active_tenants.push(tenant_shard_id); garbage.active_tenant_count = active_tenants.len(); } counter += 1; if counter % 1000 == 0 { tracing::info!( "Progress: {counter} tenants checked, {} active, {} garbage", active_tenants.len(), garbage.items.len() ); } } tracing::info!( "Found {}/{} garbage tenants", garbage.items.len(), garbage.items.len() + active_tenants.len() ); // If we are only checking tenant-deep, we are done. Otherwise we must // proceed to check the individual timelines of the active tenants. if depth == TraversingDepth::Tenant { return Ok(garbage); } tracing::info!( "Checking timelines for {} active tenants", active_tenants.len(), ); // Construct a stream of all timelines within active tenants let active_tenants = tokio_stream::iter(active_tenants.iter().map(Ok)); let timelines = active_tenants.map_ok(|t| stream_tenant_timelines(&remote_client, &target, *t)); let timelines = timelines.try_buffer_unordered(S3_CONCURRENCY); let timelines = timelines.try_flatten(); // For all timelines within active tenants, call into console API to check their existence let timelines_checked = timelines.map_ok(|ttid| { let api_client = cloud_admin_api_client.clone(); async move { api_client .find_timeline_branch(ttid.tenant_shard_id.tenant_id, ttid.timeline_id) .await .map_err(|e| anyhow::anyhow!(e)) .map(|r| (ttid, r)) } }); let mut timelines_checked = std::pin::pin!(timelines_checked.try_buffer_unordered(CONSOLE_CONCURRENCY)); // Update the GarbageList with any timelines which appear not to exist. let mut active_timelines: Vec<TenantShardTimelineId> = vec![]; while let Some(result) = timelines_checked.next().await { let (ttid, console_result) = result?; if garbage.maybe_append(GarbageEntity::Timeline(ttid), console_result) { tracing::debug!("Timeline {ttid} is garbage"); } else { tracing::debug!("Timeline {ttid} is active"); active_timelines.push(ttid); garbage.active_timeline_count = active_timelines.len(); } } let num_garbage_timelines = garbage .items .iter() .filter(|g| matches!(g.entity, GarbageEntity::Timeline(_))) .count(); tracing::info!( "Found {}/{} garbage timelines in active tenants", num_garbage_timelines, active_timelines.len(), ); Ok(garbage) } #[derive(clap::ValueEnum, Debug, Clone)] pub enum PurgeMode { /// The safest mode: only delete tenants that were explicitly reported as deleted /// by Console API. DeletedOnly, /// Delete all garbage tenants, including those which are only presumed to be deleted, /// because the Console API could not find them. DeletedAndMissing, } impl std::fmt::Display for PurgeMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PurgeMode::DeletedOnly => write!(f, "deleted-only"), PurgeMode::DeletedAndMissing => write!(f, "deleted-and-missing"), } } } pub async fn get_tenant_objects( s3_client: &GenericRemoteStorage, tenant_shard_id: TenantShardId, ) -> anyhow::Result<Vec<ListingObject>> { tracing::debug!("Listing objects in tenant {tenant_shard_id}"); let tenant_root = super::remote_tenant_path(&tenant_shard_id); // TODO: apply extra validation based on object modification time. Don't purge // tenants where any timeline's index_part.json has been touched recently. let cancel = CancellationToken::new(); let list = backoff::retry( || s3_client.list(Some(&tenant_root), ListingMode::NoDelimiter, None, &cancel), |_| false, 3, MAX_RETRIES as u32, "get_tenant_objects", &cancel, ) .await .expect("dummy cancellation token")?; Ok(list.keys) } pub async fn get_timeline_objects( s3_client: &GenericRemoteStorage, ttid: TenantShardTimelineId, ) -> anyhow::Result<Vec<ListingObject>> { tracing::debug!("Listing objects in timeline {ttid}"); let timeline_root = super::remote_timeline_path_id(&ttid); let cancel = CancellationToken::new(); let list = backoff::retry( || { s3_client.list( Some(&timeline_root), ListingMode::NoDelimiter, None, &cancel, ) }, |_| false, 3, MAX_RETRIES as u32, "get_timeline_objects", &cancel, ) .await .expect("dummy cancellation token")?; Ok(list.keys) } /// Drain a buffer of keys into DeleteObjects requests /// /// If `drain` is true, drains keys completely; otherwise stops when < /// `max_keys_per_delete`` keys are left. /// `num_deleted` returns number of deleted keys. async fn do_delete( remote_client: &GenericRemoteStorage, keys: &mut Vec<ListingObject>, dry_run: bool, drain: bool, progress_tracker: &mut DeletionProgressTracker, ) -> anyhow::Result<()> { let cancel = CancellationToken::new(); let max_keys_per_delete = remote_client.max_keys_per_delete(); while (!keys.is_empty() && drain) || (keys.len() >= max_keys_per_delete) { let request_keys = keys.split_off(keys.len() - (std::cmp::min(max_keys_per_delete, keys.len()))); let request_keys: Vec<RemotePath> = request_keys.into_iter().map(|o| o.key).collect(); let num_deleted = request_keys.len(); if dry_run { tracing::info!("Dry-run deletion of objects: "); for k in request_keys { tracing::info!(" {k:?}"); } } else { remote_client .delete_objects(&request_keys, &cancel) .await .context("deletetion request")?; progress_tracker.register(num_deleted); } } Ok(()) } /// Simple tracker reporting each 10k deleted keys. #[derive(Default)] struct DeletionProgressTracker { num_deleted: usize, last_reported_num_deleted: usize, } impl DeletionProgressTracker { fn register(&mut self, n: usize) { self.num_deleted += n; if self.num_deleted - self.last_reported_num_deleted > 10000 { tracing::info!("progress: deleted {} keys", self.num_deleted); self.last_reported_num_deleted = self.num_deleted; } } } pub async fn purge_garbage( input_path: String, mode: PurgeMode, min_age: Duration, dry_run: bool, ) -> anyhow::Result<()> { let list_bytes = tokio::fs::read(&input_path).await?; let garbage_list = serde_json::from_slice::<GarbageList>(&list_bytes)?; tracing::info!( "Loaded {} items in garbage list from {}", garbage_list.items.len(), input_path ); let (remote_client, _target) = init_remote(garbage_list.bucket_config.clone(), garbage_list.node_kind).await?; assert_eq!( garbage_list.bucket_config.bucket_name().unwrap(), remote_client.bucket_name().unwrap() ); // Sanity checks on the incoming list if garbage_list.active_tenant_count == 0 { anyhow::bail!("Refusing to purge a garbage list that reports 0 active tenants"); } if garbage_list .items .iter() .any(|g| matches!(g.entity, GarbageEntity::Timeline(_))) && garbage_list.active_timeline_count == 0 { anyhow::bail!( "Refusing to purge a garbage list containing garbage timelines that reports 0 active timelines" ); } let filtered_items = garbage_list .items .iter() .filter(|i| match (&mode, &i.reason) { (PurgeMode::DeletedAndMissing, _) => true, (PurgeMode::DeletedOnly, GarbageReason::DeletedInConsole) => true, (PurgeMode::DeletedOnly, GarbageReason::KnownBug) => true, (PurgeMode::DeletedOnly, GarbageReason::MissingInConsole) => false, }); tracing::info!( "Filtered down to {} garbage items based on mode {}", garbage_list.items.len(), mode ); let items = tokio_stream::iter(filtered_items.map(Ok)); let get_objects_results = items.map_ok(|i| { let remote_client = remote_client.clone(); async move { match i.entity { GarbageEntity::Tenant(tenant_id) => { get_tenant_objects(&remote_client, tenant_id).await } GarbageEntity::Timeline(ttid) => get_timeline_objects(&remote_client, ttid).await, } } }); let mut get_objects_results = std::pin::pin!(get_objects_results.try_buffer_unordered(S3_CONCURRENCY)); let mut objects_to_delete = Vec::new(); let mut progress_tracker = DeletionProgressTracker::default(); while let Some(result) = get_objects_results.next().await { let mut object_list = result?; // Extra safety check: even if a collection of objects is garbage, check max() of modification // times before purging, so that if we incorrectly marked a live tenant as garbage then we would // notice that its index has been written recently and would omit deleting it. if object_list.is_empty() { // Simplify subsequent code by ensuring list always has at least one item // Usually, this only occurs if there is parallel deletions racing us, as there is no empty prefixes continue; } let max_mtime = object_list.iter().map(|o| o.last_modified).max().unwrap(); let age = max_mtime.elapsed(); match age { Err(_) => { tracing::warn!("Bad last_modified time"); continue; } Ok(a) if a < min_age => { // Failed age check. This doesn't mean we did something wrong: a tenant might really be garbage and recently // written, but out of an abundance of caution we still don't purge it. tracing::info!( "Skipping tenant with young objects {}..{}", object_list.first().as_ref().unwrap().key, object_list.last().as_ref().unwrap().key ); continue; } Ok(_) => { // Passed age check } } objects_to_delete.append(&mut object_list); if objects_to_delete.len() >= remote_client.max_keys_per_delete() { do_delete( &remote_client, &mut objects_to_delete, dry_run, false, &mut progress_tracker, ) .await?; } } do_delete( &remote_client, &mut objects_to_delete, dry_run, true, &mut progress_tracker, ) .await?; tracing::info!("{} keys deleted in total", progress_tracker.num_deleted); Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/metadata_stream.rs
storage_scrubber/src/metadata_stream.rs
use std::str::FromStr; use anyhow::{Context, anyhow}; use async_stream::{stream, try_stream}; use futures::StreamExt; use pageserver_api::shard::TenantShardId; use remote_storage::{GenericRemoteStorage, ListingMode, ListingObject, RemotePath}; use tokio_stream::Stream; use utils::id::{TenantId, TimelineId}; use crate::{ RootTarget, S3Target, TenantShardTimelineId, list_objects_with_retries, stream_objects_with_retries, }; /// Given a remote storage and a target, output a stream of TenantIds discovered via listing prefixes pub fn stream_tenants<'a>( remote_client: &'a GenericRemoteStorage, target: &'a RootTarget, ) -> impl Stream<Item = anyhow::Result<TenantShardId>> + 'a { stream_tenants_maybe_prefix(remote_client, target, None) } /// Given a remote storage and a target, output a stream of TenantIds discovered via listing prefixes pub fn stream_tenants_maybe_prefix<'a>( remote_client: &'a GenericRemoteStorage, target: &'a RootTarget, tenant_id_prefix: Option<String>, ) -> impl Stream<Item = anyhow::Result<TenantShardId>> + 'a { try_stream! { let mut tenants_target = target.tenants_root(); if let Some(tenant_id_prefix) = tenant_id_prefix { tenants_target.prefix_in_bucket += &tenant_id_prefix; } let mut tenants_stream = std::pin::pin!(stream_objects_with_retries(remote_client, ListingMode::WithDelimiter, &tenants_target)); while let Some(chunk) = tenants_stream.next().await { let chunk = chunk?; let entry_ids = chunk.prefixes.iter() .map(|prefix| prefix.get_path().file_name().ok_or_else(|| anyhow!("no final component in path '{prefix}'"))); for dir_name_res in entry_ids { let dir_name = dir_name_res?; let id = TenantShardId::from_str(dir_name)?; yield id; } } } } pub async fn stream_tenant_shards<'a>( remote_client: &'a GenericRemoteStorage, target: &'a RootTarget, tenant_id: TenantId, ) -> anyhow::Result<impl Stream<Item = Result<TenantShardId, anyhow::Error>> + 'a> { let shards_target = target.tenant_shards_prefix(&tenant_id); let strip_prefix = target.tenants_root().prefix_in_bucket; let prefix_str = &strip_prefix.strip_prefix("/").unwrap_or(&strip_prefix); tracing::info!("Listing shards in {}", shards_target.prefix_in_bucket); let listing = list_objects_with_retries(remote_client, ListingMode::WithDelimiter, &shards_target) .await?; let tenant_shard_ids = listing .prefixes .iter() .map(|prefix| prefix.get_path().as_str()) .filter_map(|prefix| -> Option<&str> { prefix.strip_prefix(prefix_str) }) .map(|entry_id_str| { let first_part = entry_id_str.split('/').next().unwrap(); first_part .parse::<TenantShardId>() .with_context(|| format!("Incorrect tenant entry id str: {first_part}")) }) .collect::<Vec<_>>(); tracing::debug!("Yielding {} shards for {tenant_id}", tenant_shard_ids.len()); Ok(stream! { for i in tenant_shard_ids { let id = i?; yield Ok(id); } }) } /// Given a `TenantShardId`, output a stream of the timelines within that tenant, discovered /// using a listing. /// /// The listing is done before the stream is built, so that this /// function can be used to generate concurrency on a stream using buffer_unordered. pub async fn stream_tenant_timelines<'a>( remote_client: &'a GenericRemoteStorage, target: &'a RootTarget, tenant: TenantShardId, ) -> anyhow::Result<impl Stream<Item = Result<TenantShardTimelineId, anyhow::Error>> + 'a> { let mut timeline_ids: Vec<Result<TimelineId, anyhow::Error>> = Vec::new(); let timelines_target = target.timelines_root(&tenant); let prefix_str = &timelines_target .prefix_in_bucket .strip_prefix("/") .unwrap_or(&timelines_target.prefix_in_bucket); let mut objects_stream = std::pin::pin!(stream_objects_with_retries( remote_client, ListingMode::WithDelimiter, &timelines_target )); loop { tracing::debug!("Listing in {tenant}"); let fetch_response = match objects_stream.next().await { None => break, Some(Err(e)) => { timeline_ids.push(Err(e)); break; } Some(Ok(r)) => r, }; let new_entry_ids = fetch_response .prefixes .iter() .filter_map(|prefix| -> Option<&str> { prefix.get_path().as_str().strip_prefix(prefix_str) }) .map(|entry_id_str| { let first_part = entry_id_str.split('/').next().unwrap(); first_part .parse::<TimelineId>() .with_context(|| format!("Incorrect timeline entry id str: {entry_id_str}")) }); for i in new_entry_ids { timeline_ids.push(i); } } tracing::debug!("Yielding {} timelines for {}", timeline_ids.len(), tenant); Ok(stream! { for i in timeline_ids { let id = i?; yield Ok(TenantShardTimelineId::new(tenant, id)); } }) } pub(crate) fn stream_listing<'a>( remote_client: &'a GenericRemoteStorage, target: &'a S3Target, ) -> impl Stream<Item = anyhow::Result<(RemotePath, Option<ListingObject>)>> + 'a { let listing_mode = if target.delimiter.is_empty() { ListingMode::NoDelimiter } else { ListingMode::WithDelimiter }; try_stream! { let mut objects_stream = std::pin::pin!(stream_objects_with_retries( remote_client, listing_mode, target, )); while let Some(list) = objects_stream.next().await { let list = list?; if target.delimiter.is_empty() { for key in list.keys { yield (key.key.clone(), Some(key)); } } else { for key in list.prefixes { yield (key, None); } } } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/main.rs
storage_scrubber/src/main.rs
use anyhow::{Context, anyhow, bail}; use camino::Utf8PathBuf; use clap::{Parser, Subcommand}; use pageserver_api::controller_api::{MetadataHealthUpdateRequest, MetadataHealthUpdateResponse}; use pageserver_api::shard::TenantShardId; use reqwest::{Certificate, Method, Url}; use storage_controller_client::control_api; use storage_scrubber::garbage::{PurgeMode, find_garbage, purge_garbage}; use storage_scrubber::pageserver_physical_gc::{GcMode, pageserver_physical_gc}; use storage_scrubber::scan_pageserver_metadata::scan_pageserver_metadata; use storage_scrubber::scan_safekeeper_metadata::{DatabaseOrList, scan_safekeeper_metadata}; use storage_scrubber::tenant_snapshot::SnapshotDownloader; use storage_scrubber::{ BucketConfig, ConsoleConfig, ControllerClientConfig, NodeKind, TraversingDepth, find_large_objects, init_logging, }; use utils::id::TenantId; use utils::{project_build_tag, project_git_version}; project_git_version!(GIT_VERSION); project_build_tag!(BUILD_TAG); #[derive(Parser)] #[command(author, version, about, long_about = None)] #[command(arg_required_else_help(true))] struct Cli { #[command(subcommand)] command: Command, #[arg(short, long, default_value_t = false)] delete: bool, #[arg(long)] /// URL to storage controller. e.g. http://127.0.0.1:1234 when using `neon_local` controller_api: Option<Url>, #[arg(long)] /// JWT token for authenticating with storage controller. Requires scope 'scrubber' or 'admin'. controller_jwt: Option<String>, /// If set to true, the scrubber will exit with error code on fatal error. #[arg(long, default_value_t = false)] exit_code: bool, /// Trusted root CA certificates to use in https APIs. #[arg(long)] ssl_ca_file: Option<Utf8PathBuf>, } #[derive(Subcommand, Debug)] enum Command { FindGarbage { #[arg(short, long)] node_kind: NodeKind, #[arg(short, long, default_value_t=TraversingDepth::Tenant)] depth: TraversingDepth, #[arg(short, long, default_value=None)] tenant_id_prefix: Option<String>, #[arg(short, long, default_value_t = String::from("garbage.json"))] output_path: String, }, PurgeGarbage { #[arg(short, long)] input_path: String, #[arg(short, long, default_value_t = PurgeMode::DeletedOnly)] mode: PurgeMode, #[arg(long = "min-age")] min_age: humantime::Duration, }, #[command(verbatim_doc_comment)] ScanMetadata { #[arg(short, long)] node_kind: NodeKind, #[arg(short, long, default_value_t = false)] json: bool, #[arg(long = "tenant-id", num_args = 0..)] tenant_ids: Vec<TenantShardId>, #[arg(long = "post", default_value_t = false)] post_to_storcon: bool, #[arg(long, default_value = None)] /// For safekeeper node_kind only, points to db with debug dump dump_db_connstr: Option<String>, /// For safekeeper node_kind only, table in the db with debug dump #[arg(long, default_value = None)] dump_db_table: Option<String>, /// For safekeeper node_kind only, json list of timelines and their lsn info #[arg(long, default_value = None)] timeline_lsns: Option<String>, #[arg(long, default_value_t = false)] verbose: bool, }, TenantSnapshot { #[arg(long = "tenant-id")] tenant_id: TenantId, #[arg(long = "concurrency", short = 'j', default_value_t = 8)] concurrency: usize, #[arg(short, long)] output_path: Utf8PathBuf, }, PageserverPhysicalGc { #[arg(long = "tenant-id", num_args = 0..)] tenant_ids: Vec<TenantShardId>, #[arg(long = "min-age")] min_age: humantime::Duration, #[arg(short, long, default_value_t = GcMode::IndicesOnly)] mode: GcMode, }, FindLargeObjects { #[arg(long = "min-size")] min_size: u64, #[arg(short, long, default_value_t = false)] ignore_deltas: bool, #[arg(long = "concurrency", short = 'j', default_value_t = 64)] concurrency: usize, }, CronJob { // PageserverPhysicalGc #[arg(long = "min-age")] gc_min_age: humantime::Duration, #[arg(short, long, default_value_t = GcMode::IndicesOnly)] gc_mode: GcMode, // ScanMetadata #[arg(long = "post", default_value_t = false)] post_to_storcon: bool, }, } #[tokio::main] async fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let bucket_config = BucketConfig::from_env()?; let command_log_name = match &cli.command { Command::ScanMetadata { .. } => "scan", Command::FindGarbage { .. } => "find-garbage", Command::PurgeGarbage { .. } => "purge-garbage", Command::TenantSnapshot { .. } => "tenant-snapshot", Command::PageserverPhysicalGc { .. } => "pageserver-physical-gc", Command::FindLargeObjects { .. } => "find-large-objects", Command::CronJob { .. } => "cron-job", }; let _guard = init_logging(&format!( "{}_{}_{}_{}.log", std::env::args().next().unwrap(), command_log_name, bucket_config.bucket_name().unwrap_or("nobucket"), chrono::Utc::now().format("%Y_%m_%d__%H_%M_%S") )); tracing::info!("version: {}, build_tag {}", GIT_VERSION, BUILD_TAG); let ssl_ca_certs = match cli.ssl_ca_file.as_ref() { Some(ssl_ca_file) => { tracing::info!("Using ssl root CA file: {ssl_ca_file:?}"); let buf = tokio::fs::read(ssl_ca_file).await?; Certificate::from_pem_bundle(&buf)? } None => Vec::new(), }; let mut http_client = reqwest::Client::builder(); for cert in ssl_ca_certs { http_client = http_client.add_root_certificate(cert); } let http_client = http_client.build()?; let controller_client = cli.controller_api.map(|controller_api| { ControllerClientConfig { controller_api, // Default to no key: this is a convenience when working in a development environment controller_jwt: cli.controller_jwt.unwrap_or("".to_owned()), } .build_client(http_client) }); match cli.command { Command::ScanMetadata { json, tenant_ids, node_kind, post_to_storcon, dump_db_connstr, dump_db_table, timeline_lsns, verbose, } => { if let NodeKind::Safekeeper = node_kind { let db_or_list = match (timeline_lsns, dump_db_connstr) { (Some(timeline_lsns), _) => { let timeline_lsns = serde_json::from_str(&timeline_lsns) .context("parsing timeline_lsns")?; DatabaseOrList::List(timeline_lsns) } (None, Some(dump_db_connstr)) => { let dump_db_table = dump_db_table .ok_or_else(|| anyhow::anyhow!("dump_db_table not specified"))?; let tenant_ids = tenant_ids.iter().map(|tshid| tshid.tenant_id).collect(); DatabaseOrList::Database { tenant_ids, connstr: dump_db_connstr, table: dump_db_table, } } (None, None) => anyhow::bail!( "neither `timeline_lsns` specified, nor `dump_db_connstr` and `dump_db_table`" ), }; let summary = scan_safekeeper_metadata(bucket_config.clone(), db_or_list).await?; if json { println!("{}", serde_json::to_string(&summary).unwrap()) } else { println!("{}", summary.summary_string()); } if summary.is_fatal() { bail!("Fatal scrub errors detected"); } if summary.is_empty() { // Strictly speaking an empty bucket is a valid bucket, but if someone ran the // scrubber they were likely expecting to scan something, and if we see no timelines // at all then it's likely due to some configuration issues like a bad prefix bail!("No timelines found in {}", bucket_config.desc_str()); } Ok(()) } else { scan_pageserver_metadata_cmd( bucket_config, controller_client.as_ref(), tenant_ids, json, post_to_storcon, verbose, cli.exit_code, ) .await } } Command::FindGarbage { node_kind, depth, tenant_id_prefix, output_path, } => { let console_config = ConsoleConfig::from_env()?; find_garbage( bucket_config, console_config, depth, node_kind, tenant_id_prefix, output_path, ) .await } Command::PurgeGarbage { input_path, mode, min_age, } => purge_garbage(input_path, mode, min_age.into(), !cli.delete).await, Command::TenantSnapshot { tenant_id, output_path, concurrency, } => { let downloader = SnapshotDownloader::new(bucket_config, tenant_id, output_path, concurrency).await?; downloader.download().await } Command::PageserverPhysicalGc { tenant_ids, min_age, mode, } => { pageserver_physical_gc_cmd( &bucket_config, controller_client.as_ref(), tenant_ids, min_age, mode, ) .await } Command::FindLargeObjects { min_size, ignore_deltas, concurrency, } => { let summary = find_large_objects::find_large_objects( bucket_config, min_size, ignore_deltas, concurrency, ) .await?; println!("{}", serde_json::to_string(&summary).unwrap()); Ok(()) } Command::CronJob { gc_min_age, gc_mode, post_to_storcon, } => { run_cron_job( bucket_config, controller_client.as_ref(), gc_min_age, gc_mode, post_to_storcon, cli.exit_code, ) .await } } } /// Runs the scrubber cron job. /// 1. Do pageserver physical gc /// 2. Scan pageserver metadata pub async fn run_cron_job( bucket_config: BucketConfig, controller_client: Option<&control_api::Client>, gc_min_age: humantime::Duration, gc_mode: GcMode, post_to_storcon: bool, exit_code: bool, ) -> anyhow::Result<()> { tracing::info!(%gc_min_age, %gc_mode, "Running pageserver-physical-gc"); pageserver_physical_gc_cmd( &bucket_config, controller_client, Vec::new(), gc_min_age, gc_mode, ) .await?; tracing::info!(%post_to_storcon, node_kind = %NodeKind::Pageserver, "Running scan-metadata"); scan_pageserver_metadata_cmd( bucket_config, controller_client, Vec::new(), true, post_to_storcon, false, // default to non-verbose mode exit_code, ) .await?; Ok(()) } pub async fn pageserver_physical_gc_cmd( bucket_config: &BucketConfig, controller_client: Option<&control_api::Client>, tenant_shard_ids: Vec<TenantShardId>, min_age: humantime::Duration, mode: GcMode, ) -> anyhow::Result<()> { match (controller_client, mode) { (Some(_), _) => { // Any mode may run when controller API is set } (None, GcMode::Full) => { // The part of physical GC where we erase ancestor layers cannot be done safely without // confirming the most recent complete shard split with the controller. Refuse to run, rather // than doing it unsafely. return Err(anyhow!( "Full physical GC requires `--controller-api` and `--controller-jwt` to run" )); } (None, GcMode::DryRun | GcMode::IndicesOnly) => { // These GcModes do not require the controller to run. } } let summary = pageserver_physical_gc( bucket_config, controller_client, tenant_shard_ids, min_age.into(), mode, ) .await?; println!("{}", serde_json::to_string(&summary).unwrap()); Ok(()) } pub async fn scan_pageserver_metadata_cmd( bucket_config: BucketConfig, controller_client: Option<&control_api::Client>, tenant_shard_ids: Vec<TenantShardId>, json: bool, post_to_storcon: bool, verbose: bool, exit_code: bool, ) -> anyhow::Result<()> { if controller_client.is_none() && post_to_storcon { return Err(anyhow!( "Posting pageserver scan health status to storage controller requires `--controller-api` and `--controller-jwt` to run" )); } match scan_pageserver_metadata(bucket_config.clone(), tenant_shard_ids, verbose).await { Err(e) => { tracing::error!("Failed: {e}"); Err(e) } Ok(summary) => { if json { println!("{}", serde_json::to_string(&summary).unwrap()) } else { println!("{}", summary.summary_string()); } if post_to_storcon { if let Some(client) = controller_client { let body = summary.build_health_update_request(); client .dispatch::<MetadataHealthUpdateRequest, MetadataHealthUpdateResponse>( Method::POST, "control/v1/metadata_health/update".to_string(), Some(body), ) .await?; } } if summary.is_fatal() { tracing::error!("Fatal scrub errors detected"); if exit_code { std::process::exit(1); } } else if summary.is_empty() { // Strictly speaking an empty bucket is a valid bucket, but if someone ran the // scrubber they were likely expecting to scan something, and if we see no timelines // at all then it's likely due to some configuration issues like a bad prefix tracing::error!("No timelines found in {}", bucket_config.desc_str()); if exit_code { std::process::exit(1); } } Ok(()) } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/find_large_objects.rs
storage_scrubber/src/find_large_objects.rs
use std::pin::pin; use futures::{StreamExt, TryStreamExt}; use pageserver::tenant::storage_layer::LayerName; use remote_storage::ListingMode; use serde::{Deserialize, Serialize}; use crate::checks::parse_layer_object_name; use crate::metadata_stream::stream_tenants; use crate::{BucketConfig, NodeKind, init_remote, stream_objects_with_retries}; #[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq)] enum LargeObjectKind { DeltaLayer, ImageLayer, Other, } impl LargeObjectKind { fn from_key(key: &str) -> Self { let fname = key.split('/').next_back().unwrap(); let Ok((layer_name, _generation)) = parse_layer_object_name(fname) else { return LargeObjectKind::Other; }; match layer_name { LayerName::Image(_) => LargeObjectKind::ImageLayer, LayerName::Delta(_) => LargeObjectKind::DeltaLayer, } } } #[derive(Serialize, Deserialize, Clone)] pub struct LargeObject { pub key: String, pub size: u64, kind: LargeObjectKind, } #[derive(Serialize, Deserialize)] pub struct LargeObjectListing { pub objects: Vec<LargeObject>, } pub async fn find_large_objects( bucket_config: BucketConfig, min_size: u64, ignore_deltas: bool, concurrency: usize, ) -> anyhow::Result<LargeObjectListing> { let (remote_client, target) = init_remote(bucket_config.clone(), NodeKind::Pageserver).await?; let tenants = pin!(stream_tenants(&remote_client, &target)); let objects_stream = tenants.map_ok(|tenant_shard_id| { let mut tenant_root = target.tenant_root(&tenant_shard_id); let remote_client = remote_client.clone(); async move { let mut objects = Vec::new(); let mut total_objects_ctr = 0u64; // We want the objects and not just common prefixes tenant_root.delimiter.clear(); let mut objects_stream = pin!(stream_objects_with_retries( &remote_client, ListingMode::NoDelimiter, &tenant_root )); while let Some(listing) = objects_stream.next().await { let listing = listing?; for obj in listing.keys.iter().filter(|obj| min_size <= obj.size) { let key = obj.key.to_string(); let kind = LargeObjectKind::from_key(&key); if ignore_deltas && kind == LargeObjectKind::DeltaLayer { continue; } objects.push(LargeObject { key, size: obj.size, kind, }) } total_objects_ctr += listing.keys.len() as u64; } Ok((tenant_shard_id, objects, total_objects_ctr)) } }); let mut objects_stream = std::pin::pin!(objects_stream.try_buffer_unordered(concurrency)); let mut objects = Vec::new(); let mut tenant_ctr = 0u64; let mut object_ctr = 0u64; while let Some(res) = objects_stream.next().await { let (tenant_shard_id, objects_slice, total_objects_ctr) = res?; objects.extend_from_slice(&objects_slice); object_ctr += total_objects_ctr; tenant_ctr += 1; if tenant_ctr % 100 == 0 { tracing::info!( "Scanned {tenant_ctr} shards. objects={object_ctr}, found={}, current={tenant_shard_id}.", objects.len() ); } } let desc_str = target.desc_str(); tracing::info!( "Scan of {desc_str} finished. Scanned {tenant_ctr} shards. objects={object_ctr}, found={}.", objects.len() ); Ok(LargeObjectListing { objects }) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/storage_scrubber/src/tenant_snapshot.rs
storage_scrubber/src/tenant_snapshot.rs
use std::collections::HashMap; use anyhow::Context; use async_stream::stream; use camino::Utf8PathBuf; use futures::{StreamExt, TryStreamExt}; use pageserver::tenant::IndexPart; use pageserver::tenant::remote_timeline_client::index::LayerFileMetadata; use pageserver::tenant::remote_timeline_client::remote_layer_path; use pageserver::tenant::storage_layer::LayerName; use pageserver_api::shard::TenantShardId; use remote_storage::GenericRemoteStorage; use tokio_util::sync::CancellationToken; use utils::generation::Generation; use utils::id::TenantId; use crate::checks::{BlobDataParseResult, RemoteTimelineBlobData, list_timeline_blobs}; use crate::metadata_stream::{stream_tenant_shards, stream_tenant_timelines}; use crate::{ BucketConfig, NodeKind, RootTarget, TenantShardTimelineId, download_object_to_file, init_remote, }; pub struct SnapshotDownloader { remote_client: GenericRemoteStorage, #[allow(dead_code)] target: RootTarget, tenant_id: TenantId, output_path: Utf8PathBuf, concurrency: usize, } impl SnapshotDownloader { pub async fn new( bucket_config: BucketConfig, tenant_id: TenantId, output_path: Utf8PathBuf, concurrency: usize, ) -> anyhow::Result<Self> { let (remote_client, target) = init_remote(bucket_config.clone(), NodeKind::Pageserver).await?; Ok(Self { remote_client, target, tenant_id, output_path, concurrency, }) } async fn download_layer( &self, ttid: TenantShardTimelineId, layer_name: LayerName, layer_metadata: LayerFileMetadata, ) -> anyhow::Result<(LayerName, LayerFileMetadata)> { let cancel = CancellationToken::new(); // Note this is local as in a local copy of S3 data, not local as in the pageserver's local format. They use // different layer names (remote-style has the generation suffix) let local_path = self.output_path.join(format!( "{}/timelines/{}/{}{}", ttid.tenant_shard_id, ttid.timeline_id, layer_name, layer_metadata.generation.get_suffix() )); // We should only be called for layers that are owned by the input TTID assert_eq!(layer_metadata.shard, ttid.tenant_shard_id.to_index()); // Assumption: we always write layer files atomically, and layer files are immutable. Therefore if the file // already exists on local disk, we assume it is fully correct and skip it. if tokio::fs::try_exists(&local_path).await? { tracing::debug!("{} already exists", local_path); return Ok((layer_name, layer_metadata)); } else { tracing::debug!("{} requires download...", local_path); let remote_path = remote_layer_path( &ttid.tenant_shard_id.tenant_id, &ttid.timeline_id, layer_metadata.shard, &layer_name, layer_metadata.generation, ); let mode = remote_storage::ListingMode::NoDelimiter; // List versions: the object might be deleted. let versions = self .remote_client .list_versions(Some(&remote_path), mode, None, &cancel) .await?; let Some(version) = versions.versions.first() else { return Err(anyhow::anyhow!("No versions found for {remote_path}")); }; download_object_to_file( &self.remote_client, &remote_path, version.version_id().cloned(), &local_path, ) .await?; tracing::debug!("Downloaded successfully to {local_path}"); } Ok((layer_name, layer_metadata)) } /// Download many layers belonging to the same TTID, with some concurrency async fn download_layers( &self, ttid: TenantShardTimelineId, layers: Vec<(LayerName, LayerFileMetadata)>, ) -> anyhow::Result<()> { let layer_count = layers.len(); tracing::info!("Downloading {} layers for timeline {ttid}...", layer_count); let layers_stream = stream! { for (layer_name, layer_metadata) in layers { yield self.download_layer(ttid, layer_name, layer_metadata); } }; tokio::fs::create_dir_all(self.output_path.join(format!( "{}/timelines/{}", ttid.tenant_shard_id, ttid.timeline_id ))) .await?; let layer_results = layers_stream.buffered(self.concurrency); let mut layer_results = std::pin::pin!(layer_results); let mut err = None; let mut download_count = 0; while let Some(i) = layer_results.next().await { download_count += 1; match i { Ok((layer_name, layer_metadata)) => { tracing::info!( "[{download_count}/{layer_count}] OK: {} bytes {ttid} {}", layer_metadata.file_size, layer_name ); } Err(e) => { // Warn and continue: we will download what we can tracing::warn!("Download error: {e}"); err = Some(e); } } } if let Some(e) = err { tracing::warn!("Some errors occurred downloading {ttid} layers, last error: {e}"); Err(e) } else { Ok(()) } } async fn download_timeline( &self, ttid: TenantShardTimelineId, index_part: Box<IndexPart>, index_part_generation: Generation, ancestor_layers: &mut HashMap<TenantShardTimelineId, HashMap<LayerName, LayerFileMetadata>>, ) -> anyhow::Result<()> { let index_bytes = serde_json::to_string(&index_part).unwrap(); let layers = index_part .layer_metadata .into_iter() .filter_map(|(layer_name, layer_metadata)| { if layer_metadata.shard.shard_count != ttid.tenant_shard_id.shard_count { // Accumulate ancestor layers for later download let ancestor_ttid = TenantShardTimelineId::new( TenantShardId { tenant_id: ttid.tenant_shard_id.tenant_id, shard_number: layer_metadata.shard.shard_number, shard_count: layer_metadata.shard.shard_count, }, ttid.timeline_id, ); let ancestor_ttid_layers = ancestor_layers.entry(ancestor_ttid).or_default(); use std::collections::hash_map::Entry; match ancestor_ttid_layers.entry(layer_name) { Entry::Occupied(entry) => { // Descendent shards that reference a layer from an ancestor should always have matching metadata, // as their siblings, because it is read atomically during a shard split. assert_eq!(entry.get(), &layer_metadata); } Entry::Vacant(entry) => { entry.insert(layer_metadata); } } None } else { Some((layer_name, layer_metadata)) } }) .collect(); let download_result = self.download_layers(ttid, layers).await; // Write index last, once all the layers it references are downloaded let local_index_path = self.output_path.join(format!( "{}/timelines/{}/index_part.json{}", ttid.tenant_shard_id, ttid.timeline_id, index_part_generation.get_suffix() )); tokio::fs::write(&local_index_path, index_bytes) .await .context("writing index")?; download_result } pub async fn download(&self) -> anyhow::Result<()> { // Generate a stream of TenantShardId let shards = stream_tenant_shards(&self.remote_client, &self.target, self.tenant_id).await?; let shards: Vec<TenantShardId> = shards.try_collect().await?; // Only read from shards that have the highest count: avoids redundantly downloading // from ancestor shards. let Some(shard_count) = shards.iter().map(|s| s.shard_count).max() else { anyhow::bail!("No shards found"); }; // We will build a collection of layers in anccestor shards to download (this will only // happen if this tenant has been split at some point) let mut ancestor_layers: HashMap< TenantShardTimelineId, HashMap<LayerName, LayerFileMetadata>, > = Default::default(); for shard in shards.into_iter().filter(|s| s.shard_count == shard_count) { // Generate a stream of TenantTimelineId let timelines = stream_tenant_timelines(&self.remote_client, &self.target, shard).await?; // Generate a stream of S3TimelineBlobData async fn load_timeline_index( remote_client: &GenericRemoteStorage, target: &RootTarget, ttid: TenantShardTimelineId, ) -> anyhow::Result<(TenantShardTimelineId, RemoteTimelineBlobData)> { let data = list_timeline_blobs(remote_client, ttid, target).await?; Ok((ttid, data)) } let timelines = timelines .map_ok(|ttid| load_timeline_index(&self.remote_client, &self.target, ttid)); let mut timelines = std::pin::pin!(timelines.try_buffered(8)); while let Some(i) = timelines.next().await { let (ttid, data) = i?; match data.blob_data { BlobDataParseResult::Parsed { index_part, index_part_generation, s3_layers: _, index_part_last_modified_time: _, index_part_snapshot_time: _, } => { self.download_timeline( ttid, index_part, index_part_generation, &mut ancestor_layers, ) .await .context("Downloading timeline")?; } BlobDataParseResult::Relic => {} BlobDataParseResult::Incorrect { .. } => { tracing::error!("Bad metadata in timeline {ttid}"); } }; } } for (ttid, layers) in ancestor_layers.into_iter() { tracing::info!( "Downloading {} layers from ancestor timeline {ttid}...", layers.len() ); self.download_layers(ttid, layers.into_iter().collect()) .await?; } Ok(()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/hadron.rs
safekeeper/src/hadron.rs
use once_cell::sync::Lazy; use pem::Pem; use safekeeper_api::models::PullTimelineRequest; use std::{ collections::HashMap, env::VarError, net::IpAddr, sync::Arc, sync::atomic::AtomicBool, time::Duration, }; use tokio::time::sleep; use tokio_util::sync::CancellationToken; use url::Url; use utils::{backoff, critical_timeline, id::TenantTimelineId, ip_address}; use anyhow::{Result, anyhow}; use pageserver_api::controller_api::{ AvailabilityZone, NodeRegisterRequest, SafekeeperTimeline, SafekeeperTimelinesResponse, }; use crate::{ GlobalTimelines, SafeKeeperConf, metrics::{ SK_RECOVERY_PULL_TIMELINE_ERRORS, SK_RECOVERY_PULL_TIMELINE_OKS, SK_RECOVERY_PULL_TIMELINE_SECONDS, SK_RECOVERY_PULL_TIMELINES_SECONDS, }, pull_timeline, timelines_global_map::DeleteOrExclude, }; // Extract information in the SafeKeeperConf to build a NodeRegisterRequest used to register the safekeeper with the HCC. fn build_node_registeration_request( conf: &SafeKeeperConf, node_ip_addr: Option<IpAddr>, ) -> Result<NodeRegisterRequest> { let advertise_pg_addr_with_port = conf .advertise_pg_addr_tenant_only .as_deref() .expect("advertise_pg_addr_tenant_only is required to register with HCC"); // Extract host/port from the string. let (advertise_host_addr, pg_port_str) = advertise_pg_addr_with_port.split_at( advertise_pg_addr_with_port .rfind(':') .ok_or(anyhow::anyhow!("Invalid advertise_pg_addr"))?, ); // Need the `[1..]` to remove the leading ':'. let pg_port = pg_port_str[1..] .parse::<u16>() .map_err(|e| anyhow::anyhow!("Cannot parse PG port: {}", e))?; let (_, http_port_str) = conf.listen_http_addr.split_at( conf.listen_http_addr .rfind(':') .ok_or(anyhow::anyhow!("Invalid listen_http_addr"))?, ); let http_port = http_port_str[1..] .parse::<u16>() .map_err(|e| anyhow::anyhow!("Cannot parse HTTP port: {}", e))?; Ok(NodeRegisterRequest { node_id: conf.my_id, listen_pg_addr: advertise_host_addr.to_string(), listen_pg_port: pg_port, listen_http_addr: advertise_host_addr.to_string(), listen_http_port: http_port, node_ip_addr, availability_zone_id: AvailabilityZone("todo".to_string()), listen_grpc_addr: None, listen_grpc_port: None, listen_https_port: None, }) } // Retrieve the JWT token used for authenticating with HCC from the environment variable. // Returns None if the token cannot be retrieved. fn get_hcc_auth_token() -> Option<String> { match std::env::var("HCC_AUTH_TOKEN") { Ok(v) => { tracing::info!("Loaded JWT token for authentication with HCC"); Some(v) } Err(VarError::NotPresent) => { tracing::info!("No JWT token for authentication with HCC detected"); None } Err(_) => { tracing::info!( "Failed to either load to detect non-present HCC_AUTH_TOKEN environment variable" ); None } } } async fn send_safekeeper_register_request( request_url: &Url, auth_token: &Option<String>, request: &NodeRegisterRequest, ) -> Result<()> { let client = reqwest::Client::new(); let mut req_builder = client .post(request_url.clone()) .header("Content-Type", "application/json"); if let Some(token) = auth_token { req_builder = req_builder.bearer_auth(token); } req_builder .json(&request) .send() .await? .error_for_status()?; Ok(()) } /// Registers this safe keeper with the HCC. pub async fn register(conf: &SafeKeeperConf) -> Result<()> { match conf.hcc_base_url.as_ref() { None => { tracing::info!("HCC base URL is not set, skipping registration"); Ok(()) } Some(hcc_base_url) => { // The following operations acquiring the auth token and the node IP address both read environment // variables. It's fine for now as this `register()` function is only called once during startup. // If we start to talk to HCC more regularly in the safekeeper we should probably consider // refactoring things into a "HadronClusterCoordinatorClient" struct. let auth_token = get_hcc_auth_token(); let node_ip_addr = ip_address::read_node_ip_addr_from_env().expect("Error reading node IP address."); let request = build_node_registeration_request(conf, node_ip_addr)?; let cancel = CancellationToken::new(); let request_url = hcc_base_url.clone().join("/hadron-internal/v1/sk")?; backoff::retry( || async { send_safekeeper_register_request(&request_url, &auth_token, &request).await }, |_| false, 3, u32::MAX, "Calling the HCC safekeeper register API", &cancel, ) .await .ok_or(anyhow::anyhow!( "Error in forever retry loop. This error should never be surfaced." ))? } } } async fn safekeeper_list_timelines_request( conf: &SafeKeeperConf, ) -> Result<pageserver_api::controller_api::SafekeeperTimelinesResponse> { if conf.hcc_base_url.is_none() { tracing::info!("HCC base URL is not set, skipping registration"); return Err(anyhow::anyhow!("HCC base URL is not set")); } // The following operations acquiring the auth token and the node IP address both read environment // variables. It's fine for now as this `register()` function is only called once during startup. // If we start to talk to HCC more regularly in the safekeeper we should probably consider // refactoring things into a "HadronClusterCoordinatorClient" struct. let auth_token = get_hcc_auth_token(); let method = format!("/control/v1/safekeeper/{}/timelines", conf.my_id.0); let request_url = conf.hcc_base_url.as_ref().unwrap().clone().join(&method)?; let client = reqwest::Client::new(); let mut req_builder = client .get(request_url.clone()) .header("Content-Type", "application/json") .query(&[("id", conf.my_id.0)]); if let Some(token) = auth_token { req_builder = req_builder.bearer_auth(token); } let response = req_builder .send() .await? .error_for_status()? .json::<pageserver_api::controller_api::SafekeeperTimelinesResponse>() .await?; Ok(response) } // Returns true on success, false otherwise. pub async fn hcc_pull_timeline( timeline: SafekeeperTimeline, conf: &SafeKeeperConf, global_timelines: Arc<GlobalTimelines>, nodeid_http: &HashMap<u64, String>, ) -> bool { let mut request = PullTimelineRequest { tenant_id: timeline.tenant_id, timeline_id: timeline.timeline_id, http_hosts: Vec::new(), mconf: None, }; for host in timeline.peers { if host.0 == conf.my_id.0 { continue; } if let Some(http_host) = nodeid_http.get(&host.0) { request.http_hosts.push(http_host.clone()); } } let ca_certs = match conf .ssl_ca_certs .iter() .map(Pem::contents) .map(reqwest::Certificate::from_der) .collect::<Result<Vec<_>, _>>() { Ok(result) => result, Err(_) => { return false; } }; match pull_timeline::handle_request( request, conf.sk_auth_token.clone(), ca_certs, global_timelines.clone(), true, ) .await { Ok(resp) => { tracing::info!( "Completed pulling tenant {} timeline {} from SK {:?}", timeline.tenant_id, timeline.timeline_id, resp.safekeeper_host ); return true; } Err(e) => { tracing::error!( "Failed to pull tenant {} timeline {} from SK {}", timeline.tenant_id, timeline.timeline_id, e ); let ttid = TenantTimelineId { tenant_id: timeline.tenant_id, timeline_id: timeline.timeline_id, }; // Revert the failed timeline pull. // Notice that not found timeline returns OK also. match global_timelines .delete_or_exclude(&ttid, DeleteOrExclude::DeleteLocal) .await { Ok(dr) => { tracing::info!( "Deleted tenant {} timeline {} DirExists: {}", timeline.tenant_id, timeline.timeline_id, dr.dir_existed, ); } Err(e) => { tracing::error!( "Failed to delete tenant {} timeline {} from global_timelines: {}", timeline.tenant_id, timeline.timeline_id, e ); } } } } false } pub async fn hcc_pull_timeline_till_success( timeline: SafekeeperTimeline, conf: &SafeKeeperConf, global_timelines: Arc<GlobalTimelines>, nodeid_http: &HashMap<u64, String>, ) { const MAX_PULL_TIMELINE_RETRIES: u64 = 100; for i in 0..MAX_PULL_TIMELINE_RETRIES { if hcc_pull_timeline( timeline.clone(), conf, global_timelines.clone(), nodeid_http, ) .await { SK_RECOVERY_PULL_TIMELINE_OKS.inc(); return; } tracing::error!( "Failed to pull timeline {} from SK peers, retrying {}/{}", timeline.timeline_id, i + 1, MAX_PULL_TIMELINE_RETRIES ); tokio::time::sleep(std::time::Duration::from_secs(1)).await; } SK_RECOVERY_PULL_TIMELINE_ERRORS.inc(); } pub async fn hcc_pull_timelines( conf: &SafeKeeperConf, global_timelines: Arc<GlobalTimelines>, ) -> Result<()> { let _timer = SK_RECOVERY_PULL_TIMELINES_SECONDS.start_timer(); tracing::info!("Start pulling timelines from SK peers"); let mut response = SafekeeperTimelinesResponse { timelines: Vec::new(), safekeeper_peers: Vec::new(), }; for i in 0..100 { match safekeeper_list_timelines_request(conf).await { Ok(timelines) => { response = timelines; } Err(e) => { tracing::error!("Failed to list timelines from HCC: {}", e); if i == 99 { return Err(e); } } } sleep(Duration::from_millis(100)).await; } let mut nodeid_http = HashMap::new(); for sk in response.safekeeper_peers { nodeid_http.insert( sk.node_id.0, format!("http://{}:{}", sk.listen_http_addr, sk.http_port), ); } tracing::info!("Received {} timelines from HCC", response.timelines.len()); for timeline in response.timelines { let _timer = SK_RECOVERY_PULL_TIMELINE_SECONDS .with_label_values(&[ &timeline.tenant_id.to_string(), &timeline.timeline_id.to_string(), ]) .start_timer(); hcc_pull_timeline_till_success(timeline, conf, global_timelines.clone(), &nodeid_http) .await; } Ok(()) } /// true if the last background scan found total usage > limit pub static GLOBAL_DISK_LIMIT_EXCEEDED: Lazy<AtomicBool> = Lazy::new(|| AtomicBool::new(false)); /// Returns filesystem usage in bytes for the filesystem containing the given path. // Need to suppress the clippy::unnecessary_cast warning because the casts on the block count and the // block size are required on macOS (they are 32-bit integers on macOS, apparantly). #[allow(clippy::unnecessary_cast)] pub fn get_filesystem_usage(path: &std::path::Path) -> u64 { // Allow overriding disk usage via failpoint for tests fail::fail_point!("sk-global-disk-usage", |val| { // val is Option<String>; parse payload if present val.and_then(|s| s.parse::<u64>().ok()).unwrap_or(0) }); // Call statvfs(3) for filesystem usage use nix::sys::statvfs::statvfs; match statvfs(path) { Ok(stat) => { // fragment size (f_frsize) if non-zero else block size (f_bsize) let frsize = stat.fragment_size(); let blocksz = if frsize > 0 { frsize } else { stat.block_size() }; // used blocks = total blocks - available blocks for unprivileged let used_blocks = stat.blocks().saturating_sub(stat.blocks_available()); used_blocks as u64 * blocksz as u64 } Err(e) => { // The global disk usage watcher aren't associated with a tenant or timeline, so we just // pass placeholder (all-zero) tenant and timeline IDs to the critical!() macro. let placeholder_ttid = TenantTimelineId::empty(); critical_timeline!( placeholder_ttid.tenant_id, placeholder_ttid.timeline_id, None::<&AtomicBool>, "Global disk usage watcher failed to read filesystem usage: {:?}", e ); 0 } } } /// Returns the total capacity of the current working directory's filesystem in bytes. #[allow(clippy::unnecessary_cast)] pub fn get_filesystem_capacity(path: &std::path::Path) -> Result<u64> { // Call statvfs(3) for filesystem stats use nix::sys::statvfs::statvfs; match statvfs(path) { Ok(stat) => { // fragment size (f_frsize) if non-zero else block size (f_bsize) let frsize = stat.fragment_size(); let blocksz = if frsize > 0 { frsize } else { stat.block_size() }; Ok(stat.blocks() as u64 * blocksz as u64) } Err(e) => Err(anyhow!("Failed to read filesystem capacity: {:?}", e)), } } #[cfg(test)] mod tests { use super::*; use utils::id::NodeId; #[test] fn test_build_node_registeration_request() { // Test that: // 1. We always extract the host name and port used to register with the HCC from the // `advertise_pg_addr` if it is set. // 2. The correct ports are extracted from `advertise_pg_addr` and `listen_http_addr`. let mut conf = SafeKeeperConf::dummy(); conf.my_id = NodeId(1); conf.advertise_pg_addr_tenant_only = Some("safe-keeper-1.safe-keeper.hadron.svc.cluster.local:5454".to_string()); // `listen_pg_addr` and `listen_pg_addr_tenant_only` are not used for node registration. Set them to a different // host and port values and make sure that they don't show up in the node registration request. conf.listen_pg_addr = "0.0.0.0:5456".to_string(); conf.listen_pg_addr_tenant_only = Some("0.0.0.0:5456".to_string()); conf.listen_http_addr = "0.0.0.0:7676".to_string(); let node_ip_addr: Option<IpAddr> = Some("127.0.0.1".parse().unwrap()); let request = build_node_registeration_request(&conf, node_ip_addr).unwrap(); assert_eq!(request.node_id, NodeId(1)); assert_eq!( request.listen_pg_addr, "safe-keeper-1.safe-keeper.hadron.svc.cluster.local" ); assert_eq!(request.listen_pg_port, 5454); assert_eq!( request.listen_http_addr, "safe-keeper-1.safe-keeper.hadron.svc.cluster.local" ); assert_eq!(request.listen_http_port, 7676); assert_eq!( request.node_ip_addr, Some(IpAddr::V4("127.0.0.1".parse().unwrap())) ); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/receive_wal.rs
safekeeper/src/receive_wal.rs
//! Safekeeper communication endpoint to WAL proposer (compute node). //! Gets messages from the network, passes them down to consensus module and //! sends replies back. use std::future; use std::net::SocketAddr; use std::sync::Arc; use anyhow::{Context, anyhow}; use bytes::BytesMut; use parking_lot::{MappedMutexGuard, Mutex, MutexGuard}; use postgres_backend::{CopyStreamHandlerEnd, PostgresBackend, PostgresBackendReader, QueryError}; use pq_proto::BeMessage; use safekeeper_api::ServerInfo; use safekeeper_api::membership::Configuration; use safekeeper_api::models::{ConnectionId, WalReceiverState, WalReceiverStatus}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::sync::mpsc::error::SendTimeoutError; use tokio::sync::mpsc::{Receiver, Sender, channel}; use tokio::task; use tokio::task::JoinHandle; use tokio::time::{Duration, Instant, MissedTickBehavior}; use tracing::*; use utils::id::TenantTimelineId; use utils::lsn::Lsn; use utils::pageserver_feedback::PageserverFeedback; use crate::GlobalTimelines; use crate::handler::SafekeeperPostgresHandler; use crate::metrics::{ WAL_RECEIVER_QUEUE_DEPTH, WAL_RECEIVER_QUEUE_DEPTH_TOTAL, WAL_RECEIVER_QUEUE_SIZE_TOTAL, WAL_RECEIVERS, }; use crate::safekeeper::{AcceptorProposerMessage, ProposerAcceptorMessage}; use crate::timeline::{TimelineError, WalResidentTimeline}; const DEFAULT_FEEDBACK_CAPACITY: usize = 8; /// Registry of WalReceivers (compute connections). Timeline holds it (wrapped /// in Arc). pub struct WalReceivers { mutex: Mutex<WalReceiversShared>, pageserver_feedback_tx: tokio::sync::broadcast::Sender<PageserverFeedback>, num_computes_tx: tokio::sync::watch::Sender<usize>, num_computes_rx: tokio::sync::watch::Receiver<usize>, } /// Id under which walreceiver is registered in shmem. type WalReceiverId = usize; impl WalReceivers { pub fn new() -> Arc<WalReceivers> { let (pageserver_feedback_tx, _) = tokio::sync::broadcast::channel(DEFAULT_FEEDBACK_CAPACITY); let (num_computes_tx, num_computes_rx) = tokio::sync::watch::channel(0usize); Arc::new(WalReceivers { mutex: Mutex::new(WalReceiversShared { slots: Vec::new() }), pageserver_feedback_tx, num_computes_tx, num_computes_rx, }) } /// Register new walreceiver. Returned guard provides access to the slot and /// automatically deregisters in Drop. pub fn register(self: &Arc<WalReceivers>, conn_id: Option<ConnectionId>) -> WalReceiverGuard { let mut shared = self.mutex.lock(); let slots = &mut shared.slots; let walreceiver = WalReceiverState { conn_id, status: WalReceiverStatus::Voting, }; // find empty slot or create new one let pos = if let Some(pos) = slots.iter().position(|s| s.is_none()) { slots[pos] = Some(walreceiver); pos } else { let pos = slots.len(); slots.push(Some(walreceiver)); pos }; self.update_num(&shared); WAL_RECEIVERS.inc(); WalReceiverGuard { id: pos, walreceivers: self.clone(), } } /// Get reference to locked slot contents. Slot must exist (registered /// earlier). fn get_slot( self: &Arc<WalReceivers>, id: WalReceiverId, ) -> MappedMutexGuard<'_, WalReceiverState> { MutexGuard::map(self.mutex.lock(), |locked| { locked.slots[id] .as_mut() .expect("walreceiver doesn't exist") }) } /// Get number of walreceivers (compute connections). pub fn get_num(self: &Arc<WalReceivers>) -> usize { self.mutex.lock().get_num() } /// Get channel for number of walreceivers. pub fn get_num_rx(self: &Arc<WalReceivers>) -> tokio::sync::watch::Receiver<usize> { self.num_computes_rx.clone() } /// Should get called after every update of slots. fn update_num(self: &Arc<WalReceivers>, shared: &MutexGuard<WalReceiversShared>) { let num = shared.get_num(); self.num_computes_tx.send_replace(num); } /// Get state of all walreceivers. pub fn get_all(self: &Arc<WalReceivers>) -> Vec<WalReceiverState> { self.mutex.lock().slots.iter().flatten().cloned().collect() } /// Get number of streaming walreceivers (normally 0 or 1) from compute. pub fn get_num_streaming(self: &Arc<WalReceivers>) -> usize { self.mutex .lock() .slots .iter() .flatten() // conn_id.is_none skips recovery which also registers here .filter(|s| s.conn_id.is_some() && matches!(s.status, WalReceiverStatus::Streaming)) .count() } /// Unregister walreceiver. fn unregister(self: &Arc<WalReceivers>, id: WalReceiverId) { let mut shared = self.mutex.lock(); shared.slots[id] = None; self.update_num(&shared); WAL_RECEIVERS.dec(); } /// Broadcast pageserver feedback to connected walproposers. pub fn broadcast_pageserver_feedback(&self, feedback: PageserverFeedback) { // Err means there is no subscribers, it is fine. let _ = self.pageserver_feedback_tx.send(feedback); } } /// Only a few connections are expected (normally one), so store in Vec. struct WalReceiversShared { slots: Vec<Option<WalReceiverState>>, } impl WalReceiversShared { /// Get number of walreceivers (compute connections). fn get_num(&self) -> usize { self.slots.iter().flatten().count() } } /// Scope guard to access slot in WalReceivers registry and unregister from /// it in Drop. pub struct WalReceiverGuard { id: WalReceiverId, walreceivers: Arc<WalReceivers>, } impl WalReceiverGuard { /// Get reference to locked shared state contents. fn get(&self) -> MappedMutexGuard<WalReceiverState> { self.walreceivers.get_slot(self.id) } } impl Drop for WalReceiverGuard { fn drop(&mut self) { self.walreceivers.unregister(self.id); } } pub const MSG_QUEUE_SIZE: usize = 256; pub const REPLY_QUEUE_SIZE: usize = 16; impl SafekeeperPostgresHandler { /// Wrapper around handle_start_wal_push_guts handling result. Error is /// handled here while we're still in walreceiver ttid span; with API /// extension, this can probably be moved into postgres_backend. pub async fn handle_start_wal_push<IO: AsyncRead + AsyncWrite + Unpin>( &mut self, pgb: &mut PostgresBackend<IO>, proto_version: u32, allow_timeline_creation: bool, ) -> Result<(), QueryError> { let mut tli: Option<WalResidentTimeline> = None; if let Err(end) = self .handle_start_wal_push_guts(pgb, &mut tli, proto_version, allow_timeline_creation) .await { // Log the result and probably send it to the client, closing the stream. let handle_end_fut = pgb.handle_copy_stream_end(end); // If we managed to create the timeline, augment logging with current LSNs etc. if let Some(tli) = tli { let info = tli.get_safekeeper_info(&self.conf).await; handle_end_fut .instrument(info_span!("", term=%info.term, last_log_term=%info.last_log_term, flush_lsn=%Lsn(info.flush_lsn), commit_lsn=%Lsn(info.commit_lsn))) .await; } else { handle_end_fut.await; } } Ok(()) } pub async fn handle_start_wal_push_guts<IO: AsyncRead + AsyncWrite + Unpin>( &mut self, pgb: &mut PostgresBackend<IO>, tli: &mut Option<WalResidentTimeline>, proto_version: u32, allow_timeline_creation: bool, ) -> Result<(), CopyStreamHandlerEnd> { // The `tli` parameter is only used for passing _out_ a timeline, one should // not have been passed in. assert!(tli.is_none()); // Notify the libpq client that it's allowed to send `CopyData` messages pgb.write_message(&BeMessage::CopyBothResponse).await?; // Experiments [1] confirm that doing network IO in one (this) thread and // processing with disc IO in another significantly improves // performance; we spawn off WalAcceptor thread for message processing // to this end. // // [1] https://github.com/neondatabase/neon/pull/1318 let (msg_tx, msg_rx) = channel(MSG_QUEUE_SIZE); let (reply_tx, reply_rx) = channel(REPLY_QUEUE_SIZE); let mut acceptor_handle: Option<JoinHandle<anyhow::Result<()>>> = None; // Concurrently receive and send data; replies are not synchronized with // sends, so this avoids deadlocks. let mut pgb_reader = pgb.split().context("START_WAL_PUSH split")?; let peer_addr = *pgb.get_peer_addr(); let mut network_reader = NetworkReader { ttid: self.ttid, conn_id: self.conn_id, pgb_reader: &mut pgb_reader, peer_addr, proto_version, acceptor_handle: &mut acceptor_handle, global_timelines: self.global_timelines.clone(), }; // Read first message and create timeline if needed and allowed. This // won't be when timelines will be always created by storcon and // allow_timeline_creation becomes false. let res = network_reader .read_first_message(allow_timeline_creation) .await; let network_res = if let Ok((timeline, next_msg)) = res { let pageserver_feedback_rx: tokio::sync::broadcast::Receiver<PageserverFeedback> = timeline .get_walreceivers() .pageserver_feedback_tx .subscribe(); *tli = Some(timeline.wal_residence_guard().await?); let timeline_cancel = timeline.cancel.clone(); tokio::select! { // todo: add read|write .context to these errors r = network_reader.run(msg_tx, msg_rx, reply_tx, timeline, next_msg) => r, r = network_write(pgb, reply_rx, pageserver_feedback_rx, proto_version) => r, _ = timeline_cancel.cancelled() => { return Err(CopyStreamHandlerEnd::Cancelled); } } } else { res.map(|_| ()) }; // Join pg backend back. pgb.unsplit(pgb_reader)?; // Join the spawned WalAcceptor. At this point chans to/from it passed // to network routines are dropped, so it will exit as soon as it // touches them. match acceptor_handle { None => { // failed even before spawning; read_network should have error Err(network_res.expect_err("no error with WalAcceptor not spawn")) } Some(handle) => { let wal_acceptor_res = handle.await; // If there was any network error, return it. network_res?; // Otherwise, WalAcceptor thread must have errored. match wal_acceptor_res { Ok(Ok(_)) => Ok(()), // Clean shutdown Ok(Err(e)) => Err(CopyStreamHandlerEnd::Other(e.context("WAL acceptor"))), Err(_) => Err(CopyStreamHandlerEnd::Other(anyhow!( "WalAcceptor task panicked", ))), } } } } } struct NetworkReader<'a, IO> { ttid: TenantTimelineId, conn_id: ConnectionId, pgb_reader: &'a mut PostgresBackendReader<IO>, peer_addr: SocketAddr, proto_version: u32, // WalAcceptor is spawned when we learn server info from walproposer and // create timeline; handle is put here. acceptor_handle: &'a mut Option<JoinHandle<anyhow::Result<()>>>, global_timelines: Arc<GlobalTimelines>, } impl<IO: AsyncRead + AsyncWrite + Unpin> NetworkReader<'_, IO> { async fn read_first_message( &mut self, allow_timeline_creation: bool, ) -> Result<(WalResidentTimeline, ProposerAcceptorMessage), CopyStreamHandlerEnd> { // Receive information about server to create timeline, if not yet. let next_msg = read_message(self.pgb_reader, self.proto_version).await?; let tli = match next_msg { ProposerAcceptorMessage::Greeting(ref greeting) => { info!( "start handshake with walproposer {} sysid {}", self.peer_addr, greeting.system_id, ); let server_info = ServerInfo { pg_version: greeting.pg_version, system_id: greeting.system_id, wal_seg_size: greeting.wal_seg_size, }; let tli = if allow_timeline_creation { self.global_timelines .create( self.ttid, Configuration::empty(), server_info, Lsn::INVALID, Lsn::INVALID, ) .await .context("create timeline")? } else { let timeline_res = self.global_timelines.get(self.ttid); match timeline_res { Ok(tl) => tl, Err(TimelineError::NotFound(_)) => { return Err(CopyStreamHandlerEnd::TimelineNoCreate); } other => other.context("get_timeline")?, } }; tli.wal_residence_guard().await? } _ => { return Err(CopyStreamHandlerEnd::Other(anyhow::anyhow!( "unexpected message {next_msg:?} instead of greeting" ))); } }; Ok((tli, next_msg)) } /// This function is cancellation-safe (only does network I/O and channel read/writes). async fn run( self, msg_tx: Sender<ProposerAcceptorMessage>, msg_rx: Receiver<ProposerAcceptorMessage>, reply_tx: Sender<AcceptorProposerMessage>, tli: WalResidentTimeline, next_msg: ProposerAcceptorMessage, ) -> Result<(), CopyStreamHandlerEnd> { *self.acceptor_handle = Some(WalAcceptor::spawn( tli, msg_rx, reply_tx, Some(self.conn_id), )); // Forward all messages to WalAcceptor read_network_loop(self.pgb_reader, msg_tx, next_msg, self.proto_version).await } } /// Read next message from walproposer. /// TODO: Return Ok(None) on graceful termination. async fn read_message<IO: AsyncRead + AsyncWrite + Unpin>( pgb_reader: &mut PostgresBackendReader<IO>, proto_version: u32, ) -> Result<ProposerAcceptorMessage, CopyStreamHandlerEnd> { let copy_data = pgb_reader.read_copy_message().await?; let msg = ProposerAcceptorMessage::parse(copy_data, proto_version)?; Ok(msg) } async fn read_network_loop<IO: AsyncRead + AsyncWrite + Unpin>( pgb_reader: &mut PostgresBackendReader<IO>, msg_tx: Sender<ProposerAcceptorMessage>, mut next_msg: ProposerAcceptorMessage, proto_version: u32, ) -> Result<(), CopyStreamHandlerEnd> { /// Threshold for logging slow WalAcceptor sends. const SLOW_THRESHOLD: Duration = Duration::from_secs(5); loop { let started = Instant::now(); let size = next_msg.size(); match msg_tx.send_timeout(next_msg, SLOW_THRESHOLD).await { Ok(()) => {} // Slow send, log a message and keep trying. Log context has timeline ID. Err(SendTimeoutError::Timeout(next_msg)) => { warn!( "slow WalAcceptor send blocked for {:.3}s", Instant::now().duration_since(started).as_secs_f64() ); if msg_tx.send(next_msg).await.is_err() { return Ok(()); // WalAcceptor terminated } warn!( "slow WalAcceptor send completed after {:.3}s", Instant::now().duration_since(started).as_secs_f64() ) } // WalAcceptor terminated. Err(SendTimeoutError::Closed(_)) => return Ok(()), } // Update metrics. Will be decremented in WalAcceptor. WAL_RECEIVER_QUEUE_DEPTH_TOTAL.inc(); WAL_RECEIVER_QUEUE_SIZE_TOTAL.add(size as i64); next_msg = read_message(pgb_reader, proto_version).await?; } } /// Read replies from WalAcceptor and pass them back to socket. Returns Ok(()) /// if reply_rx closed; it must mean WalAcceptor terminated, joining it should /// tell the error. /// /// This function is cancellation-safe (only does network I/O and channel read/writes). async fn network_write<IO: AsyncRead + AsyncWrite + Unpin>( pgb_writer: &mut PostgresBackend<IO>, mut reply_rx: Receiver<AcceptorProposerMessage>, mut pageserver_feedback_rx: tokio::sync::broadcast::Receiver<PageserverFeedback>, proto_version: u32, ) -> Result<(), CopyStreamHandlerEnd> { let mut buf = BytesMut::with_capacity(128); // storing append_response to inject PageserverFeedback into it let mut last_append_response = None; loop { // trying to read either AcceptorProposerMessage or PageserverFeedback let msg = tokio::select! { reply = reply_rx.recv() => { if let Some(msg) = reply { if let AcceptorProposerMessage::AppendResponse(append_response) = &msg { last_append_response = Some(append_response.clone()); } Some(msg) } else { return Ok(()); // chan closed, WalAcceptor terminated } } feedback = pageserver_feedback_rx.recv() => match (feedback, &last_append_response) { (Ok(feedback), Some(append_response)) => { // clone AppendResponse and inject PageserverFeedback into it let mut append_response = append_response.clone(); append_response.pageserver_feedback = Some(feedback); Some(AcceptorProposerMessage::AppendResponse(append_response)) } _ => None, }, }; let Some(msg) = msg else { continue; }; buf.clear(); msg.serialize(&mut buf, proto_version)?; pgb_writer.write_message(&BeMessage::CopyData(&buf)).await?; } } /// The WAL flush interval. This ensures we periodically flush the WAL and send AppendResponses to /// walproposer, even when it's writing a steady stream of messages. const FLUSH_INTERVAL: Duration = Duration::from_secs(1); /// The metrics computation interval. /// /// The Prometheus poll interval is 60 seconds at the time of writing. We sample the queue depth /// every 5 seconds, for 12 samples per poll. This will give a count of up to 12x active timelines. const METRICS_INTERVAL: Duration = Duration::from_secs(5); /// Encapsulates a task which takes messages from msg_rx, processes and pushes /// replies to reply_tx. /// /// Reading from socket and writing to disk in parallel is beneficial for /// performance, this struct provides the writing to disk part. pub struct WalAcceptor { tli: WalResidentTimeline, msg_rx: Receiver<ProposerAcceptorMessage>, reply_tx: Sender<AcceptorProposerMessage>, conn_id: Option<ConnectionId>, } impl WalAcceptor { /// Spawn task with WalAcceptor running, return handle to it. Task returns /// Ok(()) if either of channels has closed, and Err if any error during /// message processing is encountered. /// /// conn_id None means WalAcceptor is used by recovery initiated at this safekeeper. pub fn spawn( tli: WalResidentTimeline, msg_rx: Receiver<ProposerAcceptorMessage>, reply_tx: Sender<AcceptorProposerMessage>, conn_id: Option<ConnectionId>, ) -> JoinHandle<anyhow::Result<()>> { task::spawn(async move { let mut wa = WalAcceptor { tli, msg_rx, reply_tx, conn_id, }; let span_ttid = wa.tli.ttid; // satisfy borrow checker wa.run() .instrument( info_span!("WAL acceptor", cid = %conn_id.unwrap_or(0), ttid = %span_ttid), ) .await }) } /// The main loop. Returns Ok(()) if either msg_rx or reply_tx got closed; /// it must mean that network thread terminated. /// /// This function is *not* cancellation safe, it does local disk I/O: it should always /// be allowed to run to completion. It respects Timeline::cancel and shuts down cleanly /// when that gets triggered. async fn run(&mut self) -> anyhow::Result<()> { let walreceiver_guard = self.tli.get_walreceivers().register(self.conn_id); // Periodically flush the WAL and compute metrics. let mut flush_ticker = tokio::time::interval(FLUSH_INTERVAL); flush_ticker.set_missed_tick_behavior(MissedTickBehavior::Delay); flush_ticker.tick().await; // skip the initial, immediate tick let mut metrics_ticker = tokio::time::interval(METRICS_INTERVAL); metrics_ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); // Tracks whether we have unflushed appends. let mut dirty = false; while !self.tli.is_cancelled() { let reply = tokio::select! { // Process inbound message. msg = self.msg_rx.recv() => { // If disconnected, break to flush WAL and return. let Some(mut msg) = msg else { break; }; // Update gauge metrics. WAL_RECEIVER_QUEUE_DEPTH_TOTAL.dec(); WAL_RECEIVER_QUEUE_SIZE_TOTAL.sub(msg.size() as i64); // Update walreceiver state in shmem for reporting. if let ProposerAcceptorMessage::Elected(_) = &msg { walreceiver_guard.get().status = WalReceiverStatus::Streaming; } // Don't flush the WAL on every append, only periodically via flush_ticker. // This batches multiple appends per fsync. If the channel is empty after // sending the reply, we'll schedule an immediate flush. // // Note that a flush can still happen on segment bounds, which will result // in an AppendResponse. if let ProposerAcceptorMessage::AppendRequest(append_request) = msg { msg = ProposerAcceptorMessage::NoFlushAppendRequest(append_request); dirty = true; } self.tli.process_msg(&msg).await? } // While receiving AppendRequests, flush the WAL periodically and respond with an // AppendResponse to let walproposer know we're still alive. _ = flush_ticker.tick(), if dirty => { dirty = false; self.tli .process_msg(&ProposerAcceptorMessage::FlushWAL) .await? } // If there are no pending messages, flush the WAL immediately. // // TODO: this should be done via flush_ticker.reset_immediately(), but that's always // delayed by 1ms due to this bug: https://github.com/tokio-rs/tokio/issues/6866. _ = future::ready(()), if dirty && self.msg_rx.is_empty() => { dirty = false; flush_ticker.reset(); self.tli .process_msg(&ProposerAcceptorMessage::FlushWAL) .await? } // Update histogram metrics periodically. _ = metrics_ticker.tick() => { WAL_RECEIVER_QUEUE_DEPTH.observe(self.msg_rx.len() as f64); None // no reply } _ = self.tli.cancel.cancelled() => { break; } }; // Send reply, if any. if let Some(reply) = reply { if self.reply_tx.send(reply).await.is_err() { break; // disconnected, break to flush WAL and return } } } // Flush WAL on disconnect, see https://github.com/neondatabase/neon/issues/9259. if dirty && !self.tli.cancel.is_cancelled() { self.tli .process_msg(&ProposerAcceptorMessage::FlushWAL) .await?; } Ok(()) } } /// On drop, drain msg_rx and update metrics to avoid leaks. impl Drop for WalAcceptor { fn drop(&mut self) { self.msg_rx.close(); // prevent further sends while let Ok(msg) = self.msg_rx.try_recv() { WAL_RECEIVER_QUEUE_DEPTH_TOTAL.dec(); WAL_RECEIVER_QUEUE_SIZE_TOTAL.sub(msg.size() as i64); } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/timeline_guard.rs
safekeeper/src/timeline_guard.rs
//! Timeline residence guard //! //! It is needed to ensure that WAL segments are present on disk, //! as long as the code is holding the guard. This file implements guard logic, to issue //! and drop guards, and to notify the manager when the guard is dropped. use std::collections::HashSet; use tracing::debug; use utils::sync::gate::GateGuard; use crate::timeline_manager::ManagerCtlMessage; #[derive(Debug, Clone, Copy)] pub struct GuardId(u64); pub struct ResidenceGuard { manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>, guard_id: GuardId, /// [`ResidenceGuard`] represents a guarantee that a timeline's data remains resident, /// which by extension also means the timeline is not shut down (since after shut down /// our data may be deleted). Therefore everyone holding a residence guard must also /// hold a guard on [`crate::timeline::Timeline::gate`] _gate_guard: GateGuard, } impl Drop for ResidenceGuard { fn drop(&mut self) { // notify the manager that the guard is dropped let res = self .manager_tx .send(ManagerCtlMessage::GuardDrop(self.guard_id)); if let Err(e) = res { debug!("failed to send GuardDrop message: {:?}", e); } } } /// AccessService is responsible for issuing and dropping residence guards. /// All guards are stored in the `guards` set. /// TODO: it's possible to add `String` name to each guard, for better observability. pub(crate) struct AccessService { next_guard_id: u64, guards: HashSet<u64>, manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>, } impl AccessService { pub(crate) fn new(manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>) -> Self { Self { next_guard_id: 0, guards: HashSet::new(), manager_tx, } } pub(crate) fn is_empty(&self) -> bool { self.guards.is_empty() } /// `timeline_gate_guard` is a guarantee that the timeline is not shut down pub(crate) fn create_guard(&mut self, timeline_gate_guard: GateGuard) -> ResidenceGuard { let guard_id = self.next_guard_id; self.next_guard_id += 1; self.guards.insert(guard_id); let guard_id = GuardId(guard_id); debug!("issued a new guard {:?}", guard_id); ResidenceGuard { manager_tx: self.manager_tx.clone(), guard_id, _gate_guard: timeline_gate_guard, } } pub(crate) fn drop_guard(&mut self, guard_id: GuardId) { debug!("dropping guard {:?}", guard_id); assert!(self.guards.remove(&guard_id.0)); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/rate_limit.rs
safekeeper/src/rate_limit.rs
use std::sync::Arc; use rand::Rng; use crate::metrics::MISC_OPERATION_SECONDS; /// Global rate limiter for background tasks. #[derive(Clone)] pub struct RateLimiter { partial_backup: Arc<tokio::sync::Semaphore>, eviction: Arc<tokio::sync::Semaphore>, } impl RateLimiter { /// Create a new rate limiter. /// - `partial_backup_max`: maximum number of concurrent partial backups. /// - `eviction_max`: maximum number of concurrent timeline evictions. pub fn new(partial_backup_max: usize, eviction_max: usize) -> Self { Self { partial_backup: Arc::new(tokio::sync::Semaphore::new(partial_backup_max)), eviction: Arc::new(tokio::sync::Semaphore::new(eviction_max)), } } /// Get a permit for partial backup. This will block if the maximum number of concurrent /// partial backups is reached. pub async fn acquire_partial_backup(&self) -> tokio::sync::OwnedSemaphorePermit { let _timer = MISC_OPERATION_SECONDS .with_label_values(&["partial_permit_acquire"]) .start_timer(); self.partial_backup .clone() .acquire_owned() .await .expect("semaphore is closed") } /// Try to get a permit for timeline eviction. This will return None if the maximum number of /// concurrent timeline evictions is reached. pub fn try_acquire_eviction(&self) -> Option<tokio::sync::OwnedSemaphorePermit> { self.eviction.clone().try_acquire_owned().ok() } } /// Generate a random duration that is a fraction of the given duration. pub fn rand_duration(duration: &std::time::Duration) -> std::time::Duration { let randf64 = rand::rng().random_range(0.0..1.0); duration.mul_f64(randf64) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/timelines_global_map.rs
safekeeper/src/timelines_global_map.rs
//! This module contains global `(tenant_id, timeline_id)` -> `Arc<Timeline>` mapping. //! All timelines should always be present in this map, this is done by loading them //! all from the disk on startup and keeping them in memory. use std::collections::HashMap; use std::str::FromStr; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail}; use camino::Utf8PathBuf; use camino_tempfile::Utf8TempDir; use safekeeper_api::membership::{Configuration, SafekeeperGeneration}; use safekeeper_api::models::{SafekeeperUtilization, TimelineDeleteResult}; use safekeeper_api::{ServerInfo, membership}; use tokio::fs; use tracing::*; use utils::crashsafe::{durable_rename, fsync_async_opt}; use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId}; use utils::lsn::Lsn; use crate::defaults::DEFAULT_EVICTION_CONCURRENCY; use crate::http::routes::DeleteOrExcludeError; use crate::rate_limit::RateLimiter; use crate::state::TimelinePersistentState; use crate::timeline::{Timeline, TimelineError, delete_dir, get_tenant_dir, get_timeline_dir}; use crate::timelines_set::TimelinesSet; use crate::wal_backup::WalBackup; use crate::wal_storage::Storage; use crate::{SafeKeeperConf, control_file, wal_storage}; // Timeline entry in the global map: either a ready timeline, or mark that it is // being created. #[derive(Clone)] enum GlobalMapTimeline { CreationInProgress, Timeline(Arc<Timeline>), } struct GlobalTimelinesState { timelines: HashMap<TenantTimelineId, GlobalMapTimeline>, /// A tombstone indicates this timeline used to exist has been deleted. These are used to prevent /// on-demand timeline creation from recreating deleted timelines. This is only soft-enforced, as /// this map is dropped on restart. /// The timeline might also be locally deleted (excluded) via safekeeper migration algorithm. In that case, /// the tombsone contains the corresponding safekeeper generation. The pull_timeline requests with /// higher generation ignore such tombstones and can recreate the timeline. timeline_tombstones: HashMap<TenantTimelineId, TimelineTombstone>, /// A tombstone indicates that the tenant used to exist has been deleted. /// These are created only by tenant_delete requests. They are always valid regardless of the /// request generation. /// This is only soft-enforced, as this map is dropped on restart. tenant_tombstones: HashMap<TenantId, Instant>, conf: Arc<SafeKeeperConf>, broker_active_set: Arc<TimelinesSet>, global_rate_limiter: RateLimiter, wal_backup: Arc<WalBackup>, } impl GlobalTimelinesState { /// Get dependencies for a timeline constructor. fn get_dependencies( &self, ) -> ( Arc<SafeKeeperConf>, Arc<TimelinesSet>, RateLimiter, Arc<WalBackup>, ) { ( self.conf.clone(), self.broker_active_set.clone(), self.global_rate_limiter.clone(), self.wal_backup.clone(), ) } /// Get timeline from the map. Returns error if timeline doesn't exist or /// creation is in progress. fn get(&self, ttid: &TenantTimelineId) -> Result<Arc<Timeline>, TimelineError> { match self.timelines.get(ttid).cloned() { Some(GlobalMapTimeline::Timeline(tli)) => Ok(tli), Some(GlobalMapTimeline::CreationInProgress) => { Err(TimelineError::CreationInProgress(*ttid)) } None => { if self.has_tombstone(ttid, None) { Err(TimelineError::Deleted(*ttid)) } else { Err(TimelineError::NotFound(*ttid)) } } } } fn has_timeline_tombstone( &self, ttid: &TenantTimelineId, generation: Option<SafekeeperGeneration>, ) -> bool { if let Some(generation) = generation { self.timeline_tombstones .get(ttid) .is_some_and(|t| t.is_valid(generation)) } else { self.timeline_tombstones.contains_key(ttid) } } fn has_tenant_tombstone(&self, tenant_id: &TenantId) -> bool { self.tenant_tombstones.contains_key(tenant_id) } /// Check if the state has a tenant or a timeline tombstone. /// If `generation` is provided, check only for timeline tombsotnes with same or higher generation. /// If `generation` is `None`, check for any timeline tombstone. /// Tenant tombstones are checked regardless of the generation. fn has_tombstone( &self, ttid: &TenantTimelineId, generation: Option<SafekeeperGeneration>, ) -> bool { self.has_timeline_tombstone(ttid, generation) || self.has_tenant_tombstone(&ttid.tenant_id) } /// Removes timeline tombstone for the given timeline ID. /// Returns `true` if there have been actual changes. fn remove_timeline_tombstone(&mut self, ttid: &TenantTimelineId) -> bool { self.timeline_tombstones.remove(ttid).is_some() } fn delete(&mut self, ttid: TenantTimelineId, generation: Option<SafekeeperGeneration>) { self.timelines.remove(&ttid); self.timeline_tombstones .insert(ttid, TimelineTombstone::new(generation)); } fn add_tenant_tombstone(&mut self, tenant_id: TenantId) { self.tenant_tombstones.insert(tenant_id, Instant::now()); } } /// A struct used to manage access to the global timelines map. pub struct GlobalTimelines { state: Mutex<GlobalTimelinesState>, } impl GlobalTimelines { /// Create a new instance of the global timelines map. pub fn new(conf: Arc<SafeKeeperConf>, wal_backup: Arc<WalBackup>) -> Self { Self { state: Mutex::new(GlobalTimelinesState { timelines: HashMap::new(), timeline_tombstones: HashMap::new(), tenant_tombstones: HashMap::new(), conf, broker_active_set: Arc::new(TimelinesSet::default()), global_rate_limiter: RateLimiter::new(1, 1), wal_backup, }), } } /// Inject dependencies needed for the timeline constructors and load all timelines to memory. pub async fn init(&self) -> Result<()> { // clippy isn't smart enough to understand that drop(state) releases the // lock, so use explicit block let tenants_dir = { let mut state = self.state.lock().unwrap(); state.global_rate_limiter = RateLimiter::new( state.conf.partial_backup_concurrency, DEFAULT_EVICTION_CONCURRENCY, ); // Iterate through all directories and load tenants for all directories // named as a valid tenant_id. state.conf.workdir.clone() }; let mut tenant_count = 0; for tenants_dir_entry in std::fs::read_dir(&tenants_dir) .with_context(|| format!("failed to list tenants dir {tenants_dir}"))? { match &tenants_dir_entry { Ok(tenants_dir_entry) => { if let Ok(tenant_id) = TenantId::from_str(tenants_dir_entry.file_name().to_str().unwrap_or("")) { tenant_count += 1; self.load_tenant_timelines(tenant_id).await?; } } Err(e) => error!( "failed to list tenants dir entry {:?} in directory {}, reason: {:?}", tenants_dir_entry, tenants_dir, e ), } } info!( "found {} tenants directories, successfully loaded {} timelines", tenant_count, self.state.lock().unwrap().timelines.len() ); Ok(()) } /// Loads all timelines for the given tenant to memory. Returns fs::read_dir /// errors if any. /// /// It is async, but self.state lock is sync and there is no important /// reason to make it async (it is always held for a short while), so we /// just lock and unlock it for each timeline -- this function is called /// during init when nothing else is running, so this is fine. async fn load_tenant_timelines(&self, tenant_id: TenantId) -> Result<()> { let (conf, broker_active_set, partial_backup_rate_limiter, wal_backup) = { let state = self.state.lock().unwrap(); state.get_dependencies() }; let timelines_dir = get_tenant_dir(&conf, &tenant_id); for timelines_dir_entry in std::fs::read_dir(&timelines_dir) .with_context(|| format!("failed to list timelines dir {timelines_dir}"))? { match &timelines_dir_entry { Ok(timeline_dir_entry) => { if let Ok(timeline_id) = TimelineId::from_str(timeline_dir_entry.file_name().to_str().unwrap_or("")) { let ttid = TenantTimelineId::new(tenant_id, timeline_id); match Timeline::load_timeline(conf.clone(), ttid, wal_backup.clone()) { Ok(tli) => { let mut shared_state = tli.write_shared_state().await; self.state .lock() .unwrap() .timelines .insert(ttid, GlobalMapTimeline::Timeline(tli.clone())); tli.bootstrap( &mut shared_state, &conf, broker_active_set.clone(), partial_backup_rate_limiter.clone(), wal_backup.clone(), ); } // If we can't load a timeline, it's most likely because of a corrupted // directory. We will log an error and won't allow to delete/recreate // this timeline. The only way to fix this timeline is to repair manually // and restart the safekeeper. Err(e) => error!( "failed to load timeline {} for tenant {}, reason: {:?}", timeline_id, tenant_id, e ), } } } Err(e) => error!( "failed to list timelines dir entry {:?} in directory {}, reason: {:?}", timelines_dir_entry, timelines_dir, e ), } } Ok(()) } /// Get the number of timelines in the map. pub fn timelines_count(&self) -> usize { self.state.lock().unwrap().timelines.len() } /// Get the global safekeeper config. pub fn get_global_config(&self) -> Arc<SafeKeeperConf> { self.state.lock().unwrap().conf.clone() } pub fn get_global_broker_active_set(&self) -> Arc<TimelinesSet> { self.state.lock().unwrap().broker_active_set.clone() } pub fn get_wal_backup(&self) -> Arc<WalBackup> { self.state.lock().unwrap().wal_backup.clone() } /// Create a new timeline with the given id. If the timeline already exists, returns /// an existing timeline. pub(crate) async fn create( &self, ttid: TenantTimelineId, mconf: Configuration, server_info: ServerInfo, start_lsn: Lsn, commit_lsn: Lsn, ) -> Result<Arc<Timeline>> { let generation = Some(mconf.generation); let (conf, _, _, _) = { let state = self.state.lock().unwrap(); if let Ok(timeline) = state.get(&ttid) { // Timeline already exists, return it. return Ok(timeline); } if state.has_tombstone(&ttid, generation) { anyhow::bail!(TimelineError::Deleted(ttid)); } state.get_dependencies() }; info!("creating new timeline {}", ttid); // Do on disk initialization in tmp dir. let (_tmp_dir, tmp_dir_path) = create_temp_timeline_dir(&conf, ttid).await?; // TODO: currently we create only cfile. It would be reasonable to // immediately initialize first WAL segment as well. let state = TimelinePersistentState::new(&ttid, mconf, server_info, start_lsn, commit_lsn)?; control_file::FileStorage::create_new(&tmp_dir_path, state, conf.no_sync).await?; let timeline = self .load_temp_timeline(ttid, &tmp_dir_path, generation) .await?; Ok(timeline) } /// Move timeline from a temp directory to the main storage, and load it to /// the global map. Creating timeline in this way ensures atomicity: rename /// is atomic, so either move of the whole datadir succeeds or it doesn't, /// but corrupted data dir shouldn't be possible. /// /// We'd like to avoid holding map lock while doing IO, so it's a 3 step /// process: /// 1) check the global map that timeline doesn't exist and mark that we're /// creating it; /// 2) move the directory and load the timeline /// 3) take lock again and insert the timeline into the global map. pub async fn load_temp_timeline( &self, ttid: TenantTimelineId, tmp_path: &Utf8PathBuf, generation: Option<SafekeeperGeneration>, ) -> Result<Arc<Timeline>> { // Check for existence and mark that we're creating it. let (conf, broker_active_set, partial_backup_rate_limiter, wal_backup) = { let mut state = self.state.lock().unwrap(); match state.timelines.get(&ttid) { Some(GlobalMapTimeline::CreationInProgress) => { bail!(TimelineError::CreationInProgress(ttid)); } Some(GlobalMapTimeline::Timeline(_)) => { bail!(TimelineError::AlreadyExists(ttid)); } _ => {} } if state.has_tombstone(&ttid, generation) { // If the timeline is deleted, we refuse to recreate it. // This is a safeguard against accidentally overwriting a timeline that was deleted // by concurrent request. anyhow::bail!(TimelineError::Deleted(ttid)); } // We might have an outdated tombstone with the older generation. // Remove it unconditionally. state.remove_timeline_tombstone(&ttid); state .timelines .insert(ttid, GlobalMapTimeline::CreationInProgress); state.get_dependencies() }; // Do the actual move and reflect the result in the map. match GlobalTimelines::install_temp_timeline( ttid, tmp_path, conf.clone(), wal_backup.clone(), ) .await { Ok(timeline) => { let mut timeline_shared_state = timeline.write_shared_state().await; let mut state = self.state.lock().unwrap(); assert!(matches!( state.timelines.get(&ttid), Some(GlobalMapTimeline::CreationInProgress) )); state .timelines .insert(ttid, GlobalMapTimeline::Timeline(timeline.clone())); drop(state); timeline.bootstrap( &mut timeline_shared_state, &conf, broker_active_set, partial_backup_rate_limiter, wal_backup, ); drop(timeline_shared_state); Ok(timeline) } Err(e) => { // Init failed, remove the marker from the map let mut state = self.state.lock().unwrap(); assert!(matches!( state.timelines.get(&ttid), Some(GlobalMapTimeline::CreationInProgress) )); state.timelines.remove(&ttid); Err(e) } } } /// Main part of load_temp_timeline: do the move and load. async fn install_temp_timeline( ttid: TenantTimelineId, tmp_path: &Utf8PathBuf, conf: Arc<SafeKeeperConf>, wal_backup: Arc<WalBackup>, ) -> Result<Arc<Timeline>> { let tenant_path = get_tenant_dir(conf.as_ref(), &ttid.tenant_id); let timeline_path = get_timeline_dir(conf.as_ref(), &ttid); // We must have already checked that timeline doesn't exist in the map, // but there might be existing datadir: if timeline is corrupted it is // not loaded. We don't want to overwrite such a dir, so check for its // existence. match fs::metadata(&timeline_path).await { Ok(_) => { // Timeline directory exists on disk, we should leave state unchanged // and return error. bail!(TimelineError::Invalid(ttid)); } Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => { return Err(e.into()); } } info!( "moving timeline {} from {} to {}", ttid, tmp_path, timeline_path ); // Now it is safe to move the timeline directory to the correct // location. First, create tenant directory. Ignore error if it already // exists. if let Err(e) = tokio::fs::create_dir(&tenant_path).await { if e.kind() != std::io::ErrorKind::AlreadyExists { return Err(e.into()); } } // fsync it fsync_async_opt(&tenant_path, !conf.no_sync).await?; // and its creation fsync_async_opt(&conf.workdir, !conf.no_sync).await?; // Do the move. durable_rename(tmp_path, &timeline_path, !conf.no_sync).await?; Timeline::load_timeline(conf, ttid, wal_backup) } /// Get a timeline from the global map. If it's not present, it doesn't exist on disk, /// or was corrupted and couldn't be loaded on startup. Returned timeline is always valid, /// i.e. loaded in memory and not cancelled. pub(crate) fn get(&self, ttid: TenantTimelineId) -> Result<Arc<Timeline>, TimelineError> { let tli_res = { let state = self.state.lock().unwrap(); state.get(&ttid) }; match tli_res { Ok(tli) => { if tli.is_cancelled() { return Err(TimelineError::Cancelled(ttid)); } Ok(tli) } _ => tli_res, } } /// Returns all timelines. This is used for background timeline processes. pub fn get_all(&self) -> Vec<Arc<Timeline>> { let global_lock = self.state.lock().unwrap(); global_lock .timelines .values() .filter_map(|t| match t { GlobalMapTimeline::Timeline(t) => { if t.is_cancelled() { None } else { Some(t.clone()) } } _ => None, }) .collect() } /// Returns statistics about timeline counts pub fn get_timeline_counts(&self) -> SafekeeperUtilization { let global_lock = self.state.lock().unwrap(); let timeline_count = global_lock .timelines .values() .filter(|t| match t { GlobalMapTimeline::CreationInProgress => false, GlobalMapTimeline::Timeline(t) => !t.is_cancelled(), }) .count() as u64; SafekeeperUtilization { timeline_count } } /// Returns all timelines belonging to a given tenant. Used for deleting all timelines of a tenant, /// and that's why it can return cancelled timelines, to retry deleting them. fn get_all_for_tenant(&self, tenant_id: TenantId) -> Vec<Arc<Timeline>> { let global_lock = self.state.lock().unwrap(); global_lock .timelines .values() .filter_map(|t| match t { GlobalMapTimeline::Timeline(t) => Some(t.clone()), _ => None, }) .filter(|t| t.ttid.tenant_id == tenant_id) .collect() } /// Delete timeline, only locally on this node or globally (also cleaning /// remote storage WAL), depending on `action` value. pub(crate) async fn delete_or_exclude( &self, ttid: &TenantTimelineId, action: DeleteOrExclude, ) -> Result<TimelineDeleteResult, DeleteOrExcludeError> { let generation = match &action { DeleteOrExclude::Delete | DeleteOrExclude::DeleteLocal => None, DeleteOrExclude::Exclude(mconf) => Some(mconf.generation), }; let tli_res = { let state = self.state.lock().unwrap(); // Do NOT check tenant tombstones here: those were set earlier if state.has_timeline_tombstone(ttid, generation) { // Presence of a tombstone guarantees that a previous deletion has completed and there is no work to do. info!("Timeline {ttid} was already deleted"); return Ok(TimelineDeleteResult { dir_existed: false }); } state.get(ttid) }; let result = match tli_res { Ok(timeline) => { info!("deleting timeline {}, action={:?}", ttid, action); // If node is getting excluded, check the generation first. // Then, while holding the lock cancel the timeline; it will be // unusable after this point, and if node is added back first // deletion must be completed and node seeded anew. // // We would like to avoid holding the lock while waiting for the // gate to finish as this is deadlock prone, so for actual // deletion will take it second time. // // Canceling the timeline will block membership switch requests, // ensuring that the timeline generation will not increase // after this point, and we will not remove a timeline with a generation // higher than the requested one. if let DeleteOrExclude::Exclude(ref mconf) = action { let shared_state = timeline.read_shared_state().await; if shared_state.sk.state().mconf.generation > mconf.generation { return Err(DeleteOrExcludeError::Conflict { requested: mconf.clone(), current: shared_state.sk.state().mconf.clone(), }); } timeline.cancel(); } else { timeline.cancel(); } timeline.close().await; info!("timeline {ttid} shut down for deletion"); // Take a lock and finish the deletion holding this mutex. let mut shared_state = timeline.write_shared_state().await; let only_local = !matches!(action, DeleteOrExclude::Delete); let dir_existed = timeline.delete(&mut shared_state, only_local).await?; Ok(TimelineDeleteResult { dir_existed }) } Err(_) => { // Timeline is not memory, but it may still exist on disk in broken state. let dir_path = get_timeline_dir(self.state.lock().unwrap().conf.as_ref(), ttid); let dir_existed = delete_dir(&dir_path).await?; Ok(TimelineDeleteResult { dir_existed }) } }; // Finalize deletion, by dropping Timeline objects and storing smaller tombstones. The tombstones // are used to prevent still-running computes from re-creating the same timeline when they send data, // and to speed up repeated deletion calls by avoiding re-listing objects. self.state.lock().unwrap().delete(*ttid, generation); result } /// Deactivates and deletes all timelines for the tenant. Returns map of all timelines which /// the tenant had, `true` if a timeline was active. There may be a race if new timelines are /// created simultaneously. In that case the function will return error and the caller should /// retry tenant deletion again later. /// /// If only_local, doesn't remove WAL segments in remote storage. pub async fn delete_all_for_tenant( &self, tenant_id: &TenantId, action: DeleteOrExclude, ) -> Result<HashMap<TenantTimelineId, TimelineDeleteResult>> { info!("deleting all timelines for tenant {}", tenant_id); // Adding a tombstone before getting the timelines to prevent new timeline additions self.state.lock().unwrap().add_tenant_tombstone(*tenant_id); let to_delete = self.get_all_for_tenant(*tenant_id); let mut err = None; let mut deleted = HashMap::new(); for tli in &to_delete { match self.delete_or_exclude(&tli.ttid, action.clone()).await { Ok(result) => { deleted.insert(tli.ttid, result); } Err(e) => { error!("failed to delete timeline {}: {}", tli.ttid, e); // Save error to return later. err = Some(e); } } } // If there was an error, return it. if let Some(e) = err { return Err(anyhow::Error::from(e)); } // There may be broken timelines on disk, so delete the whole tenant dir as well. // Note that we could concurrently create new timelines while we were deleting them, // so the directory may be not empty. In this case timelines will have bad state // and timeline background jobs can panic. let tenant_dir = get_tenant_dir(self.state.lock().unwrap().conf.as_ref(), tenant_id); delete_dir(&tenant_dir).await?; Ok(deleted) } pub fn housekeeping(&self, tombstone_ttl: &Duration) { let mut state = self.state.lock().unwrap(); // We keep tombstones long enough to have a good chance of preventing rogue computes from re-creating deleted // timelines. If a compute kept running for longer than this TTL (or across a safekeeper restart) then they // may recreate a deleted timeline. let now = Instant::now(); state .timeline_tombstones .retain(|_, v| now.duration_since(v.timestamp) < *tombstone_ttl); state .tenant_tombstones .retain(|_, v| now.duration_since(*v) < *tombstone_ttl); } pub fn get_sk_id(&self) -> NodeId { self.state.lock().unwrap().conf.my_id } } /// Action for delete_or_exclude. #[derive(Clone, Debug)] pub enum DeleteOrExclude { /// Delete timeline globally. Delete, /// Legacy mode until we fully migrate to generations: like exclude deletes /// timeline only locally, but ignores generation number. DeleteLocal, /// This node is getting excluded, delete timeline locally. Exclude(membership::Configuration), } /// Create temp directory for a new timeline. It needs to be located on the same /// filesystem as the rest of the timelines. It will be automatically deleted when /// Utf8TempDir goes out of scope. pub async fn create_temp_timeline_dir( conf: &SafeKeeperConf, ttid: TenantTimelineId, ) -> Result<(Utf8TempDir, Utf8PathBuf)> { let temp_base = conf.workdir.join("tmp"); tokio::fs::create_dir_all(&temp_base).await?; let tli_dir = camino_tempfile::Builder::new() .suffix("_temptli") .prefix(&format!("{}_{}_", ttid.tenant_id, ttid.timeline_id)) .tempdir_in(temp_base)?; let tli_dir_path = tli_dir.path().to_path_buf(); Ok((tli_dir, tli_dir_path)) } /// Do basic validation of a temp timeline, before moving it to the global map. pub async fn validate_temp_timeline( conf: &SafeKeeperConf, ttid: TenantTimelineId, path: &Utf8PathBuf, generation: Option<SafekeeperGeneration>, ) -> Result<(Lsn, Lsn)> { let control_path = path.join("safekeeper.control"); let control_store = control_file::FileStorage::load_control_file(control_path)?; if control_store.server.wal_seg_size == 0 { bail!("wal_seg_size is not set"); } if let Some(generation) = generation { if control_store.mconf.generation > generation { bail!( "tmp timeline generation {} is higher than expected {generation}", control_store.mconf.generation ); } } let wal_store = wal_storage::PhysicalStorage::new(&ttid, path, &control_store, conf.no_sync)?; let commit_lsn = control_store.commit_lsn; let flush_lsn = wal_store.flush_lsn(); Ok((commit_lsn, flush_lsn)) } /// A tombstone for a deleted timeline. /// The generation is passed with "exclude" request and stored in the tombstone. /// We ignore the tombstone if the request generation is higher than /// the tombstone generation. /// If the tombstone doesn't have a generation, it's considered permanent, /// e.g. after "delete" request. struct TimelineTombstone { timestamp: Instant, generation: Option<SafekeeperGeneration>, } impl TimelineTombstone { fn new(generation: Option<SafekeeperGeneration>) -> Self { TimelineTombstone { timestamp: Instant::now(), generation, } } /// Check if the timeline is still valid for the given generation. fn is_valid(&self, generation: SafekeeperGeneration) -> bool { self.generation.is_none_or(|g| g >= generation) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/lib.rs
safekeeper/src/lib.rs
#![deny(clippy::undocumented_unsafe_blocks)] extern crate hyper0 as hyper; use std::time::Duration; use camino::Utf8PathBuf; use once_cell::sync::Lazy; use pem::Pem; use remote_storage::RemoteStorageConfig; use storage_broker::Uri; use tokio::runtime::Runtime; use url::Url; use utils::auth::SwappableJwtAuth; use utils::id::NodeId; use utils::logging::SecretString; mod auth; pub mod broker; pub mod control_file; pub mod control_file_upgrade; pub mod copy_timeline; pub mod debug_dump; pub mod hadron; pub mod handler; pub mod http; pub mod metrics; pub mod patch_control_file; pub mod pull_timeline; pub mod rate_limit; pub mod receive_wal; pub mod recovery; pub mod remove_wal; pub mod safekeeper; pub mod send_interpreted_wal; pub mod send_wal; pub mod state; pub mod timeline; pub mod timeline_eviction; pub mod timeline_guard; pub mod timeline_manager; pub mod timelines_set; pub mod wal_backup; pub mod wal_backup_partial; pub mod wal_reader_stream; pub mod wal_service; pub mod wal_storage; #[cfg(any(test, feature = "benchmarking"))] pub mod test_utils; mod timelines_global_map; use std::sync::Arc; pub use timelines_global_map::GlobalTimelines; use utils::auth::JwtAuth; pub mod defaults { pub use safekeeper_api::{ DEFAULT_HTTP_LISTEN_ADDR, DEFAULT_HTTP_LISTEN_PORT, DEFAULT_PG_LISTEN_ADDR, DEFAULT_PG_LISTEN_PORT, }; pub const DEFAULT_HEARTBEAT_TIMEOUT: &str = "5000ms"; pub const DEFAULT_MAX_OFFLOADER_LAG_BYTES: u64 = 128 * (1 << 20); /* BEGIN_HADRON */ // Default leader re-elect is 0(disabled). SK will re-elect leader if the current leader is lagging this many bytes. pub const DEFAULT_MAX_REELECT_OFFLOADER_LAG_BYTES: u64 = 0; // Default disk usage limit is 0 (disabled). It means each timeline by default can use up to this many WAL // disk space on this SK until SK begins to reject WALs. pub const DEFAULT_MAX_TIMELINE_DISK_USAGE_BYTES: u64 = 0; /* END_HADRON */ pub const DEFAULT_PARTIAL_BACKUP_TIMEOUT: &str = "15m"; pub const DEFAULT_CONTROL_FILE_SAVE_INTERVAL: &str = "300s"; pub const DEFAULT_PARTIAL_BACKUP_CONCURRENCY: &str = "5"; pub const DEFAULT_EVICTION_CONCURRENCY: usize = 2; // By default, our required residency before eviction is the same as the period that passes // before uploading a partial segment, so that in normal operation the eviction can happen // as soon as we have done the partial segment upload. pub const DEFAULT_EVICTION_MIN_RESIDENT: &str = DEFAULT_PARTIAL_BACKUP_TIMEOUT; pub const DEFAULT_SSL_KEY_FILE: &str = "server.key"; pub const DEFAULT_SSL_CERT_FILE: &str = "server.crt"; pub const DEFAULT_SSL_CERT_RELOAD_PERIOD: &str = "60s"; // Global disk watcher defaults pub const DEFAULT_GLOBAL_DISK_CHECK_INTERVAL: &str = "60s"; pub const DEFAULT_MAX_GLOBAL_DISK_USAGE_RATIO: f64 = 0.0; } #[derive(Debug, Clone)] pub struct SafeKeeperConf { // Repository directory, relative to current working directory. // Normally, the safekeeper changes the current working directory // to the repository, and 'workdir' is always '.'. But we don't do // that during unit testing, because the current directory is global // to the process but different unit tests work on different // data directories to avoid clashing with each other. pub workdir: Utf8PathBuf, pub my_id: NodeId, pub listen_pg_addr: String, pub listen_pg_addr_tenant_only: Option<String>, pub listen_http_addr: String, pub listen_https_addr: Option<String>, pub advertise_pg_addr: Option<String>, pub availability_zone: Option<String>, pub no_sync: bool, /* BEGIN_HADRON */ pub advertise_pg_addr_tenant_only: Option<String>, pub enable_pull_timeline_on_startup: bool, pub hcc_base_url: Option<Url>, /* END_HADRON */ pub broker_endpoint: Uri, pub broker_keepalive_interval: Duration, pub heartbeat_timeout: Duration, pub peer_recovery_enabled: bool, pub remote_storage: Option<RemoteStorageConfig>, pub max_offloader_lag_bytes: u64, /* BEGIN_HADRON */ pub max_reelect_offloader_lag_bytes: u64, pub max_timeline_disk_usage_bytes: u64, /// How often to check the working directory's filesystem for total disk usage. pub global_disk_check_interval: Duration, /// The portion of the filesystem capacity that can be used by all timelines. pub max_global_disk_usage_ratio: f64, /* END_HADRON */ pub backup_parallel_jobs: usize, pub wal_backup_enabled: bool, pub pg_auth: Option<Arc<JwtAuth>>, pub pg_tenant_only_auth: Option<Arc<JwtAuth>>, pub http_auth: Option<Arc<SwappableJwtAuth>>, /// JWT token to connect to other safekeepers with. pub sk_auth_token: Option<SecretString>, pub current_thread_runtime: bool, pub walsenders_keep_horizon: bool, pub partial_backup_timeout: Duration, pub disable_periodic_broker_push: bool, pub enable_offload: bool, pub delete_offloaded_wal: bool, pub control_file_save_interval: Duration, pub partial_backup_concurrency: usize, pub eviction_min_resident: Duration, pub wal_reader_fanout: bool, pub max_delta_for_fanout: Option<u64>, pub ssl_key_file: Utf8PathBuf, pub ssl_cert_file: Utf8PathBuf, pub ssl_cert_reload_period: Duration, pub ssl_ca_certs: Vec<Pem>, pub use_https_safekeeper_api: bool, pub enable_tls_wal_service_api: bool, pub force_metric_collection_on_scrape: bool, } impl SafeKeeperConf { pub fn dummy() -> Self { SafeKeeperConf { workdir: Utf8PathBuf::from("./"), no_sync: false, listen_pg_addr: defaults::DEFAULT_PG_LISTEN_ADDR.to_string(), listen_pg_addr_tenant_only: None, listen_http_addr: defaults::DEFAULT_HTTP_LISTEN_ADDR.to_string(), listen_https_addr: None, advertise_pg_addr: None, availability_zone: None, remote_storage: None, my_id: NodeId(0), broker_endpoint: storage_broker::DEFAULT_ENDPOINT .parse() .expect("failed to parse default broker endpoint"), broker_keepalive_interval: Duration::from_secs(5), peer_recovery_enabled: true, wal_backup_enabled: true, backup_parallel_jobs: 1, pg_auth: None, pg_tenant_only_auth: None, http_auth: None, sk_auth_token: None, heartbeat_timeout: Duration::new(5, 0), max_offloader_lag_bytes: defaults::DEFAULT_MAX_OFFLOADER_LAG_BYTES, /* BEGIN_HADRON */ max_reelect_offloader_lag_bytes: defaults::DEFAULT_MAX_REELECT_OFFLOADER_LAG_BYTES, max_timeline_disk_usage_bytes: defaults::DEFAULT_MAX_TIMELINE_DISK_USAGE_BYTES, global_disk_check_interval: Duration::from_secs(60), max_global_disk_usage_ratio: defaults::DEFAULT_MAX_GLOBAL_DISK_USAGE_RATIO, /* END_HADRON */ current_thread_runtime: false, walsenders_keep_horizon: false, partial_backup_timeout: Duration::from_secs(0), disable_periodic_broker_push: false, enable_offload: false, delete_offloaded_wal: false, control_file_save_interval: Duration::from_secs(1), partial_backup_concurrency: 1, eviction_min_resident: Duration::ZERO, wal_reader_fanout: false, max_delta_for_fanout: None, ssl_key_file: Utf8PathBuf::from(defaults::DEFAULT_SSL_KEY_FILE), ssl_cert_file: Utf8PathBuf::from(defaults::DEFAULT_SSL_CERT_FILE), ssl_cert_reload_period: Duration::from_secs(60), ssl_ca_certs: Vec::new(), use_https_safekeeper_api: false, enable_tls_wal_service_api: false, force_metric_collection_on_scrape: true, /* BEGIN_HADRON */ advertise_pg_addr_tenant_only: None, enable_pull_timeline_on_startup: false, hcc_base_url: None, /* END_HADRON */ } } } // Tokio runtimes. pub static WAL_SERVICE_RUNTIME: Lazy<Runtime> = Lazy::new(|| { tokio::runtime::Builder::new_multi_thread() .thread_name("WAL service worker") .enable_all() .build() .expect("Failed to create WAL service runtime") }); pub static HTTP_RUNTIME: Lazy<Runtime> = Lazy::new(|| { tokio::runtime::Builder::new_multi_thread() .thread_name("HTTP worker") .enable_all() .build() .expect("Failed to create HTTP runtime") }); pub static BROKER_RUNTIME: Lazy<Runtime> = Lazy::new(|| { tokio::runtime::Builder::new_multi_thread() .thread_name("broker worker") .worker_threads(2) // there are only 2 tasks, having more threads doesn't make sense .enable_all() .build() .expect("Failed to create broker runtime") }); pub static WAL_BACKUP_RUNTIME: Lazy<Runtime> = Lazy::new(|| { tokio::runtime::Builder::new_multi_thread() .thread_name("WAL backup worker") .enable_all() .build() .expect("Failed to create WAL backup runtime") }); /// Hadron: Dedicated runtime for infrequent background tasks. pub static BACKGROUND_RUNTIME: Lazy<Runtime> = Lazy::new(|| { tokio::runtime::Builder::new_multi_thread() .thread_name("Hadron background worker") // One worker thread is enough, as most of the actual tasks run on blocking threads // which has it own thread pool. .worker_threads(1) .enable_all() .build() .expect("Failed to create background runtime") });
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/wal_service.rs
safekeeper/src/wal_service.rs
//! //! WAL service listens for client connections and //! receive WAL from wal_proposer and send it to WAL receivers //! use std::os::fd::AsRawFd; use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result}; use postgres_backend::{AuthType, PostgresBackend, QueryError}; use safekeeper_api::models::ConnectionId; use tokio::net::TcpStream; use tokio_io_timeout::TimeoutReader; use tokio_util::sync::CancellationToken; use tracing::*; use utils::auth::Scope; use utils::measured_stream::MeasuredStream; use crate::handler::SafekeeperPostgresHandler; use crate::metrics::TrafficMetrics; use crate::{GlobalTimelines, SafeKeeperConf}; /// Accept incoming TCP connections and spawn them into a background thread. /// /// allowed_auth_scope is either SafekeeperData (wide JWT tokens giving access /// to any tenant are allowed) or Tenant (only tokens giving access to specific /// tenant are allowed). Doesn't matter if auth is disabled in conf. pub async fn task_main( conf: Arc<SafeKeeperConf>, pg_listener: std::net::TcpListener, allowed_auth_scope: Scope, tls_config: Option<Arc<rustls::ServerConfig>>, global_timelines: Arc<GlobalTimelines>, ) -> anyhow::Result<()> { // Tokio's from_std won't do this for us, per its comment. pg_listener.set_nonblocking(true)?; let listener = tokio::net::TcpListener::from_std(pg_listener)?; let mut connection_count: ConnectionCount = 0; loop { let (socket, peer_addr) = listener.accept().await.context("accept")?; debug!("accepted connection from {}", peer_addr); let conf = conf.clone(); let conn_id = issue_connection_id(&mut connection_count); let global_timelines = global_timelines.clone(); let tls_config = tls_config.clone(); tokio::spawn( async move { if let Err(err) = handle_socket(socket, conf, conn_id, allowed_auth_scope, tls_config, global_timelines).await { error!("connection handler exited: {}", err); } } .instrument(info_span!("", cid = %conn_id, ttid = field::Empty, application_name = field::Empty, shard = field::Empty)), ); } } /// This is run by `task_main` above, inside a background thread. /// async fn handle_socket( socket: TcpStream, conf: Arc<SafeKeeperConf>, conn_id: ConnectionId, allowed_auth_scope: Scope, tls_config: Option<Arc<rustls::ServerConfig>>, global_timelines: Arc<GlobalTimelines>, ) -> Result<(), QueryError> { socket.set_nodelay(true)?; let socket_fd = socket.as_raw_fd(); let peer_addr = socket.peer_addr()?; // Set timeout on reading from the socket. It prevents hanged up connection // if client suddenly disappears. Note that TCP_KEEPALIVE is not enabled by // default, and tokio doesn't provide ability to set it out of the box. let mut socket = TimeoutReader::new(socket); let wal_service_timeout = Duration::from_secs(60 * 10); socket.set_timeout(Some(wal_service_timeout)); // pin! is here because TimeoutReader (due to storing sleep future inside) // is not Unpin, and all pgbackend/framed/tokio dependencies require stream // to be Unpin. Which is reasonable, as indeed something like TimeoutReader // shouldn't be moved. let socket = std::pin::pin!(socket); let traffic_metrics = TrafficMetrics::new(); if let Some(current_az) = conf.availability_zone.as_deref() { traffic_metrics.set_sk_az(current_az); } let socket = MeasuredStream::new( socket, |cnt| { traffic_metrics.observe_read(cnt); }, |cnt| { traffic_metrics.observe_write(cnt); }, ); let auth_key = match allowed_auth_scope { Scope::Tenant => conf.pg_tenant_only_auth.clone(), _ => conf.pg_auth.clone(), }; let auth_type = match auth_key { None => AuthType::Trust, Some(_) => AuthType::NeonJWT, }; let auth_pair = auth_key.map(|key| (allowed_auth_scope, key)); let mut conn_handler = SafekeeperPostgresHandler::new( conf, conn_id, Some(traffic_metrics.clone()), auth_pair, global_timelines, ); let pgbackend = PostgresBackend::new_from_io(socket_fd, socket, peer_addr, auth_type, tls_config)?; // libpq protocol between safekeeper and walproposer / pageserver // We don't use shutdown. pgbackend .run(&mut conn_handler, &CancellationToken::new()) .await } pub type ConnectionCount = u32; pub fn issue_connection_id(count: &mut ConnectionCount) -> ConnectionId { *count = count.wrapping_add(1); *count }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/debug_dump.rs
safekeeper/src/debug_dump.rs
//! Utils for dumping full state of the safekeeper. use std::fs; use std::fs::DirEntry; use std::io::{BufReader, Read}; use std::path::PathBuf; use std::sync::Arc; use anyhow::{Result, bail}; use camino::{Utf8Path, Utf8PathBuf}; use chrono::{DateTime, Utc}; use postgres_ffi::v14::xlog_utils::{IsPartialXLogFileName, IsXLogFileName}; use postgres_ffi::{MAX_SEND_SIZE, XLogSegNo}; use safekeeper_api::models::WalSenderState; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId}; use utils::lsn::Lsn; use crate::safekeeper::TermHistory; use crate::state::{TimelineMemState, TimelinePersistentState}; use crate::timeline::{WalResidentTimeline, get_timeline_dir}; use crate::{GlobalTimelines, SafeKeeperConf, timeline_manager}; /// Various filters that influence the resulting JSON output. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Args { /// Dump all available safekeeper state. False by default. pub dump_all: bool, /// Dump control_file content. Uses value of `dump_all` by default. pub dump_control_file: bool, /// Dump in-memory state. Uses value of `dump_all` by default. pub dump_memory: bool, /// Dump all disk files in a timeline directory. Uses value of `dump_all` by default. pub dump_disk_content: bool, /// Dump full term history. True by default. pub dump_term_history: bool, /// Dump last modified time of WAL segments. Uses value of `dump_all` by default. pub dump_wal_last_modified: bool, /// Filter timelines by tenant_id. pub tenant_id: Option<TenantId>, /// Filter timelines by timeline_id. pub timeline_id: Option<TimelineId>, } /// Response for debug dump request. #[derive(Debug, Serialize)] pub struct Response { pub start_time: DateTime<Utc>, pub finish_time: DateTime<Utc>, pub timelines: Vec<TimelineDumpSer>, pub timelines_count: usize, pub config: Config, } pub struct TimelineDumpSer { pub tli: Arc<crate::timeline::Timeline>, pub args: Args, pub timeline_dir: Utf8PathBuf, pub runtime: Arc<tokio::runtime::Runtime>, } impl std::fmt::Debug for TimelineDumpSer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TimelineDumpSer") .field("tli", &self.tli.ttid) .field("args", &self.args) .finish() } } impl Serialize for TimelineDumpSer { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::Serializer, { let dump = self.runtime.block_on(build_from_tli_dump( &self.tli, &self.args, &self.timeline_dir, )); dump.serialize(serializer) } } async fn build_from_tli_dump( timeline: &Arc<crate::timeline::Timeline>, args: &Args, timeline_dir: &Utf8Path, ) -> Timeline { let control_file = if args.dump_control_file { let mut state = timeline.get_state().await.1; if !args.dump_term_history { state.acceptor_state.term_history = TermHistory(vec![]); } Some(state) } else { None }; let memory = if args.dump_memory { Some(timeline.memory_dump().await) } else { None }; let disk_content = if args.dump_disk_content { // build_disk_content can fail, but we don't want to fail the whole // request because of that. // Note: timeline can be in offloaded state, this is not a problem. build_disk_content(timeline_dir).ok() } else { None }; let wal_last_modified = if args.dump_wal_last_modified { get_wal_last_modified(timeline_dir).ok().flatten() } else { None }; Timeline { tenant_id: timeline.ttid.tenant_id, timeline_id: timeline.ttid.timeline_id, control_file, memory, disk_content, wal_last_modified, } } /// Safekeeper configuration. #[derive(Debug, Serialize, Deserialize)] pub struct Config { pub id: NodeId, pub workdir: PathBuf, pub listen_pg_addr: String, pub listen_http_addr: String, pub no_sync: bool, pub max_offloader_lag_bytes: u64, pub wal_backup_enabled: bool, } #[derive(Debug, Serialize, Deserialize)] pub struct Timeline { pub tenant_id: TenantId, pub timeline_id: TimelineId, pub control_file: Option<TimelinePersistentState>, pub memory: Option<Memory>, pub disk_content: Option<DiskContent>, pub wal_last_modified: Option<DateTime<Utc>>, } #[derive(Debug, Serialize, Deserialize)] pub struct Memory { pub is_cancelled: bool, pub peers_info_len: usize, pub walsenders: Vec<WalSenderState>, pub wal_backup_active: bool, pub active: bool, pub num_computes: u32, pub last_removed_segno: XLogSegNo, pub epoch_start_lsn: Lsn, pub mem_state: TimelineMemState, pub mgr_status: timeline_manager::Status, // PhysicalStorage state. pub write_lsn: Lsn, pub write_record_lsn: Lsn, pub flush_lsn: Lsn, pub file_open: bool, } #[derive(Debug, Serialize, Deserialize)] pub struct DiskContent { pub files: Vec<FileInfo>, } #[derive(Debug, Serialize, Deserialize)] pub struct FileInfo { pub name: String, pub size: u64, pub created: DateTime<Utc>, pub modified: DateTime<Utc>, pub start_zeroes: u64, pub end_zeroes: u64, // TODO: add sha256 checksum } /// Build debug dump response, using the provided [`Args`] filters. pub async fn build(args: Args, global_timelines: Arc<GlobalTimelines>) -> Result<Response> { let start_time = Utc::now(); let timelines_count = global_timelines.timelines_count(); let config = global_timelines.get_global_config(); let ptrs_snapshot = if args.tenant_id.is_some() && args.timeline_id.is_some() { // If both tenant_id and timeline_id are specified, we can just get the // timeline directly, without taking a snapshot of the whole list. let ttid = TenantTimelineId::new(args.tenant_id.unwrap(), args.timeline_id.unwrap()); if let Ok(tli) = global_timelines.get(ttid) { vec![tli] } else { vec![] } } else { // Otherwise, take a snapshot of the whole list. global_timelines.get_all() }; let mut timelines = Vec::new(); let runtime = Arc::new( tokio::runtime::Builder::new_current_thread() .build() .unwrap(), ); for tli in ptrs_snapshot { let ttid = tli.ttid; if let Some(tenant_id) = args.tenant_id { if tenant_id != ttid.tenant_id { continue; } } if let Some(timeline_id) = args.timeline_id { if timeline_id != ttid.timeline_id { continue; } } timelines.push(TimelineDumpSer { tli, args: args.clone(), timeline_dir: get_timeline_dir(&config, &ttid), runtime: runtime.clone(), }); } // Tokio forbids to drop runtime in async context, so this is a stupid way // to drop it in non async context. tokio::task::spawn_blocking(move || { let _r = runtime; }) .await?; Ok(Response { start_time, finish_time: Utc::now(), timelines, timelines_count, config: build_config(config), }) } /// Builds DiskContent from a directory path. It can fail if the directory /// is deleted between the time we get the path and the time we try to open it. fn build_disk_content(path: &Utf8Path) -> Result<DiskContent> { let mut files = Vec::new(); for entry in fs::read_dir(path)? { if entry.is_err() { continue; } let file = build_file_info(entry?); if file.is_err() { continue; } files.push(file?); } Ok(DiskContent { files }) } /// Builds FileInfo from DirEntry. Sometimes it can return an error /// if the file is deleted between the time we get the DirEntry /// and the time we try to open it. fn build_file_info(entry: DirEntry) -> Result<FileInfo> { let metadata = entry.metadata()?; let path = entry.path(); let name = path .file_name() .and_then(|x| x.to_str()) .unwrap_or("") .to_owned(); let mut file = fs::File::open(path)?; let mut reader = BufReader::new(&mut file).bytes().filter_map(|x| x.ok()); let start_zeroes = reader.by_ref().take_while(|&x| x == 0).count() as u64; let mut end_zeroes = 0; for b in reader { if b == 0 { end_zeroes += 1; } else { end_zeroes = 0; } } Ok(FileInfo { name, size: metadata.len(), created: DateTime::from(metadata.created()?), modified: DateTime::from(metadata.modified()?), start_zeroes, end_zeroes, }) } /// Get highest modified time of WAL segments in the directory. fn get_wal_last_modified(path: &Utf8Path) -> Result<Option<DateTime<Utc>>> { let mut res = None; for entry in fs::read_dir(path)? { if entry.is_err() { continue; } let entry = entry?; /* Ignore files that are not XLOG segments */ let fname = entry.file_name(); if !IsXLogFileName(&fname) && !IsPartialXLogFileName(&fname) { continue; } let metadata = entry.metadata()?; let modified: DateTime<Utc> = DateTime::from(metadata.modified()?); res = std::cmp::max(res, Some(modified)); } Ok(res) } /// Converts SafeKeeperConf to Config, filtering out the fields that are not /// supposed to be exposed. fn build_config(config: Arc<SafeKeeperConf>) -> Config { Config { id: config.my_id, workdir: config.workdir.clone().into(), listen_pg_addr: config.listen_pg_addr.clone(), listen_http_addr: config.listen_http_addr.clone(), no_sync: config.no_sync, max_offloader_lag_bytes: config.max_offloader_lag_bytes, wal_backup_enabled: config.wal_backup_enabled, } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct TimelineDigestRequest { pub from_lsn: Lsn, pub until_lsn: Lsn, } #[derive(Debug, Serialize, Deserialize)] pub struct TimelineDigest { pub sha256: String, } pub async fn calculate_digest( tli: &WalResidentTimeline, request: TimelineDigestRequest, ) -> Result<TimelineDigest> { if request.from_lsn > request.until_lsn { bail!("from_lsn is greater than until_lsn"); } let (_, persisted_state) = tli.get_state().await; if persisted_state.timeline_start_lsn > request.from_lsn { bail!("requested LSN is before the start of the timeline"); } let mut wal_reader = tli.get_walreader(request.from_lsn).await?; let mut hasher = Sha256::new(); let mut buf = vec![0u8; MAX_SEND_SIZE]; let mut bytes_left = (request.until_lsn.0 - request.from_lsn.0) as usize; while bytes_left > 0 { let bytes_to_read = std::cmp::min(buf.len(), bytes_left); let bytes_read = wal_reader.read(&mut buf[..bytes_to_read]).await?; if bytes_read == 0 { bail!("wal_reader.read returned 0 bytes"); } hasher.update(&buf[..bytes_read]); bytes_left -= bytes_read; } let digest = hasher.finalize(); let digest = hex::encode(digest); Ok(TimelineDigest { sha256: digest }) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/state.rs
safekeeper/src/state.rs
//! Defines per timeline data stored persistently (SafeKeeperPersistentState) //! and its wrapper with in memory layer (SafekeeperState). use std::cmp::max; use std::ops::Deref; use std::time::SystemTime; use anyhow::{Result, bail}; use postgres_ffi::WAL_SEGMENT_SIZE; use postgres_versioninfo::{PgMajorVersion, PgVersionId}; use safekeeper_api::membership::Configuration; use safekeeper_api::models::TimelineTermBumpResponse; use safekeeper_api::{INITIAL_TERM, ServerInfo, Term}; use serde::{Deserialize, Serialize}; use tracing::info; use utils::id::{TenantId, TenantTimelineId, TimelineId}; use utils::lsn::Lsn; use crate::control_file; use crate::safekeeper::{AcceptorState, PgUuid, TermHistory, TermLsn, UNKNOWN_SERVER_VERSION}; use crate::timeline::TimelineError; use crate::wal_backup_partial::{self}; /// Persistent information stored on safekeeper node about timeline. /// On disk data is prefixed by magic and format version and followed by checksum. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TimelinePersistentState { #[serde(with = "hex")] pub tenant_id: TenantId, #[serde(with = "hex")] pub timeline_id: TimelineId, /// Membership configuration. pub mconf: Configuration, /// persistent acceptor state pub acceptor_state: AcceptorState, /// information about server pub server: ServerInfo, /// Unique id of the last *elected* proposer we dealt with. Not needed /// for correctness, exists for monitoring purposes. #[serde(with = "hex")] pub proposer_uuid: PgUuid, /// Since which LSN this timeline generally starts. Safekeeper might have /// joined later. pub timeline_start_lsn: Lsn, /// Since which LSN safekeeper has (had) WAL for this timeline. /// All WAL segments next to one containing local_start_lsn are /// filled with data from the beginning. pub local_start_lsn: Lsn, /// Part of WAL acknowledged by quorum *and available locally*. Always points /// to record boundary. pub commit_lsn: Lsn, /// LSN that points to the end of the last backed up segment. Useful to /// persist to avoid finding out offloading progress on boot. pub backup_lsn: Lsn, /// Minimal LSN which may be needed for recovery of some safekeeper (end_lsn /// of last record streamed to everyone). Persisting it helps skipping /// recovery in walproposer, generally we compute it from peers. In /// walproposer proto called 'truncate_lsn'. Updates are currently drived /// only by walproposer. pub peer_horizon_lsn: Lsn, /// LSN of the oldest known checkpoint made by pageserver and successfully /// pushed to s3. We don't remove WAL beyond it. Persisted only for /// informational purposes, we receive it from pageserver (or broker). pub remote_consistent_lsn: Lsn, /// Holds names of partial segments uploaded to remote storage. Used to /// clean up old objects without leaving garbage in remote storage. pub partial_backup: wal_backup_partial::State, /// Eviction state of the timeline. If it's Offloaded, we should download /// WAL files from remote storage to serve the timeline. pub eviction_state: EvictionState, pub creation_ts: SystemTime, } /// State of the local WAL files. Used to track current timeline state, /// that can be either WAL files are present on disk or last partial segment /// is offloaded to remote storage. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] pub enum EvictionState { /// WAL files are present on disk. Present, /// Last partial segment is offloaded to remote storage. /// Contains flush_lsn of the last offloaded segment. Offloaded(Lsn), } pub struct MembershipSwitchResult { pub previous_conf: Configuration, pub current_conf: Configuration, } impl TimelinePersistentState { /// commit_lsn is the same as start_lsn in the normal creaiton; see /// `TimelineCreateRequest` comments.` pub fn new( ttid: &TenantTimelineId, mconf: Configuration, server_info: ServerInfo, start_lsn: Lsn, commit_lsn: Lsn, ) -> anyhow::Result<TimelinePersistentState> { if server_info.wal_seg_size == 0 { bail!(TimelineError::UninitializedWalSegSize(*ttid)); } if server_info.pg_version == UNKNOWN_SERVER_VERSION { bail!(TimelineError::UninitialinzedPgVersion(*ttid)); } if commit_lsn < start_lsn { bail!( "commit_lsn {} is smaller than start_lsn {}", commit_lsn, start_lsn ); } // If we are given with init LSN, initialize term history with it. It // ensures that walproposer always must be able to find a common point // in histories; if it can't something is corrupted. Not having LSN here // is so far left for legacy case where timeline is created by compute // and LSN during creation is not known yet. let term_history = if commit_lsn != Lsn::INVALID { TermHistory(vec![TermLsn { term: INITIAL_TERM, lsn: start_lsn, }]) } else { TermHistory::empty() }; Ok(TimelinePersistentState { tenant_id: ttid.tenant_id, timeline_id: ttid.timeline_id, mconf, acceptor_state: AcceptorState { term: INITIAL_TERM, term_history, }, server: server_info, proposer_uuid: [0; 16], timeline_start_lsn: start_lsn, local_start_lsn: start_lsn, commit_lsn, backup_lsn: start_lsn, peer_horizon_lsn: start_lsn, remote_consistent_lsn: Lsn(0), partial_backup: wal_backup_partial::State::default(), eviction_state: EvictionState::Present, creation_ts: SystemTime::now(), }) } pub fn empty() -> Self { TimelinePersistentState::new( &TenantTimelineId::empty(), Configuration::empty(), ServerInfo { pg_version: PgVersionId::from(PgMajorVersion::PG17), system_id: 0, /* Postgres system identifier */ wal_seg_size: WAL_SEGMENT_SIZE as u32, }, Lsn::INVALID, Lsn::INVALID, ) .unwrap() } } #[derive(Debug, Clone, Serialize, Deserialize)] // In memory safekeeper state. Fields mirror ones in `SafeKeeperPersistentState`; values // are not flushed yet. pub struct TimelineMemState { pub commit_lsn: Lsn, pub backup_lsn: Lsn, pub peer_horizon_lsn: Lsn, pub remote_consistent_lsn: Lsn, #[serde(with = "hex")] pub proposer_uuid: PgUuid, } /// Safekeeper persistent state plus in memory layer. /// /// Allows us to avoid frequent fsyncs when we update fields like commit_lsn /// which don't need immediate persistence. Provides transactional like API /// to atomically update the state. /// /// Implements Deref into *persistent* part. pub struct TimelineState<CTRL: control_file::Storage> { pub inmem: TimelineMemState, pub pers: CTRL, // persistent } impl<CTRL> TimelineState<CTRL> where CTRL: control_file::Storage, { pub fn new(state: CTRL) -> Self { TimelineState { inmem: TimelineMemState { commit_lsn: state.commit_lsn, backup_lsn: state.backup_lsn, peer_horizon_lsn: state.peer_horizon_lsn, remote_consistent_lsn: state.remote_consistent_lsn, proposer_uuid: state.proposer_uuid, }, pers: state, } } /// Start atomic change. Returns SafeKeeperPersistentState with in memory /// values applied; the protocol is to 1) change returned struct as desired /// 2) atomically persist it with finish_change. pub fn start_change(&self) -> TimelinePersistentState { let mut s = self.pers.clone(); s.commit_lsn = self.inmem.commit_lsn; s.backup_lsn = self.inmem.backup_lsn; s.peer_horizon_lsn = self.inmem.peer_horizon_lsn; s.remote_consistent_lsn = self.inmem.remote_consistent_lsn; s.proposer_uuid = self.inmem.proposer_uuid; s } /// Persist given state. c.f. start_change. pub async fn finish_change(&mut self, s: &TimelinePersistentState) -> Result<()> { if s.eq(&*self.pers) { // nothing to do if state didn't change } else { self.pers.persist(s).await?; } // keep in memory values up to date self.inmem.commit_lsn = s.commit_lsn; self.inmem.backup_lsn = s.backup_lsn; self.inmem.peer_horizon_lsn = s.peer_horizon_lsn; self.inmem.remote_consistent_lsn = s.remote_consistent_lsn; self.inmem.proposer_uuid = s.proposer_uuid; Ok(()) } /// Flush in memory values. pub async fn flush(&mut self) -> Result<()> { let s = self.start_change(); self.finish_change(&s).await } /// Make term at least as `to`. If `to` is None, increment current one. This /// is not in safekeeper.rs because we want to be able to do it even if /// timeline is offloaded. pub async fn term_bump(&mut self, to: Option<Term>) -> Result<TimelineTermBumpResponse> { let before = self.acceptor_state.term; let mut state = self.start_change(); let new = match to { Some(to) => max(state.acceptor_state.term, to), None => state.acceptor_state.term + 1, }; if new > state.acceptor_state.term { state.acceptor_state.term = new; self.finish_change(&state).await?; } let after = self.acceptor_state.term; Ok(TimelineTermBumpResponse { previous_term: before, current_term: after, }) } /// Switch into membership configuration `to` if it is higher than the /// current one. pub async fn membership_switch(&mut self, to: Configuration) -> Result<MembershipSwitchResult> { let before = self.mconf.clone(); // Is switch allowed? if to.generation <= self.mconf.generation { info!( "ignoring request to switch membership conf to {}, current conf {}", to, self.mconf ); } else { let mut state = self.start_change(); state.mconf = to.clone(); self.finish_change(&state).await?; info!("switched membership conf to {} from {}", to, before); } Ok(MembershipSwitchResult { previous_conf: before, current_conf: self.mconf.clone(), }) } } impl<CTRL> Deref for TimelineState<CTRL> where CTRL: control_file::Storage, { type Target = TimelinePersistentState; fn deref(&self) -> &Self::Target { &self.pers } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/safekeeper.rs
safekeeper/src/safekeeper.rs
//! Acceptor part of proposer-acceptor consensus algorithm. use std::cmp::{max, min}; use std::fmt; use std::io::Read; use std::str::FromStr; use anyhow::{Context, Result, bail}; use byteorder::{LittleEndian, ReadBytesExt}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use postgres_ffi::{MAX_SEND_SIZE, TimeLineID}; use postgres_versioninfo::{PgMajorVersion, PgVersionId}; use pq_proto::SystemId; use safekeeper_api::membership::{ INVALID_GENERATION, MemberSet, SafekeeperGeneration as Generation, SafekeeperId, }; use safekeeper_api::models::HotStandbyFeedback; use safekeeper_api::{Term, membership}; use serde::{Deserialize, Serialize}; use storage_broker::proto::SafekeeperTimelineInfo; use tracing::*; use utils::bin_ser::LeSer; use utils::id::{NodeId, TenantId, TimelineId}; use utils::lsn::Lsn; use utils::pageserver_feedback::PageserverFeedback; use crate::metrics::{MISC_OPERATION_SECONDS, PROPOSER_ACCEPTOR_MESSAGES_TOTAL}; use crate::state::TimelineState; use crate::{control_file, wal_storage}; pub const SK_PROTO_VERSION_2: u32 = 2; pub const SK_PROTO_VERSION_3: u32 = 3; pub const UNKNOWN_SERVER_VERSION: PgVersionId = PgVersionId::UNKNOWN; #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub struct TermLsn { pub term: Term, pub lsn: Lsn, } // Creation from tuple provides less typing (e.g. for unit tests). impl From<(Term, Lsn)> for TermLsn { fn from(pair: (Term, Lsn)) -> TermLsn { TermLsn { term: pair.0, lsn: pair.1, } } } #[derive(Clone, Serialize, Deserialize, PartialEq)] pub struct TermHistory(pub Vec<TermLsn>); impl TermHistory { pub fn empty() -> TermHistory { TermHistory(Vec::new()) } // Parse TermHistory as n_entries followed by TermLsn pairs in network order. pub fn from_bytes(bytes: &mut Bytes) -> Result<TermHistory> { let n_entries = bytes .get_u32_f() .with_context(|| "TermHistory misses len")?; let mut res = Vec::with_capacity(n_entries as usize); for i in 0..n_entries { let term = bytes .get_u64_f() .with_context(|| format!("TermHistory pos {i} misses term"))?; let lsn = bytes .get_u64_f() .with_context(|| format!("TermHistory pos {i} misses lsn"))? .into(); res.push(TermLsn { term, lsn }) } Ok(TermHistory(res)) } // Parse TermHistory as n_entries followed by TermLsn pairs in LE order. // TODO remove once v2 protocol is fully dropped. pub fn from_bytes_le(bytes: &mut Bytes) -> Result<TermHistory> { if bytes.remaining() < 4 { bail!("TermHistory misses len"); } let n_entries = bytes.get_u32_le(); let mut res = Vec::with_capacity(n_entries as usize); for _ in 0..n_entries { if bytes.remaining() < 16 { bail!("TermHistory is incomplete"); } res.push(TermLsn { term: bytes.get_u64_le(), lsn: bytes.get_u64_le().into(), }) } Ok(TermHistory(res)) } /// Return copy of self with switches happening strictly after up_to /// truncated. pub fn up_to(&self, up_to: Lsn) -> TermHistory { let mut res = Vec::with_capacity(self.0.len()); for e in &self.0 { if e.lsn > up_to { break; } res.push(*e); } TermHistory(res) } /// Find point of divergence between leader (walproposer) term history and /// safekeeper. Arguments are not symmetric as proposer history ends at /// +infinity while safekeeper at flush_lsn. /// C version is at walproposer SendProposerElected. pub fn find_highest_common_point( prop_th: &TermHistory, sk_th: &TermHistory, sk_wal_end: Lsn, ) -> Option<TermLsn> { let (prop_th, sk_th) = (&prop_th.0, &sk_th.0); // avoid .0 below if let Some(sk_th_last) = sk_th.last() { assert!( sk_th_last.lsn <= sk_wal_end, "safekeeper term history end {sk_th_last:?} LSN is higher than WAL end {sk_wal_end:?}" ); } // find last common term, if any... let mut last_common_idx = None; for i in 0..min(sk_th.len(), prop_th.len()) { if prop_th[i].term != sk_th[i].term { break; } // If term is the same, LSN must be equal as well. assert!( prop_th[i].lsn == sk_th[i].lsn, "same term {} has different start LSNs: prop {}, sk {}", prop_th[i].term, prop_th[i].lsn, sk_th[i].lsn ); last_common_idx = Some(i); } let last_common_idx = last_common_idx?; // Now find where it ends at both prop and sk and take min. End of // (common) term is the start of the next except it is the last one; // there it is flush_lsn in case of safekeeper or, in case of proposer // +infinity, so we just take flush_lsn then. if last_common_idx == prop_th.len() - 1 { Some(TermLsn { term: prop_th[last_common_idx].term, lsn: sk_wal_end, }) } else { let prop_common_term_end = prop_th[last_common_idx + 1].lsn; let sk_common_term_end = if last_common_idx + 1 < sk_th.len() { sk_th[last_common_idx + 1].lsn } else { sk_wal_end }; Some(TermLsn { term: prop_th[last_common_idx].term, lsn: min(prop_common_term_end, sk_common_term_end), }) } } } /// Display only latest entries for Debug. impl fmt::Debug for TermHistory { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let n_printed = 20; write!( fmt, "{}{:?}", if self.0.len() > n_printed { "... " } else { "" }, self.0 .iter() .rev() .take(n_printed) .map(|&e| (e.term, e.lsn)) // omit TermSwitchEntry .collect::<Vec<_>>() ) } } /// Unique id of proposer. Not needed for correctness, used for monitoring. pub type PgUuid = [u8; 16]; /// Persistent consensus state of the acceptor. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AcceptorState { /// acceptor's last term it voted for (advanced in 1 phase) pub term: Term, /// History of term switches for safekeeper's WAL. /// Actually it often goes *beyond* WAL contents as we adopt term history /// from the proposer before recovery. pub term_history: TermHistory, } impl AcceptorState { /// acceptor's last_log_term is the term of the highest entry in the log pub fn get_last_log_term(&self, flush_lsn: Lsn) -> Term { let th = self.term_history.up_to(flush_lsn); match th.0.last() { Some(e) => e.term, None => 0, } } } // protocol messages /// Initial Proposer -> Acceptor message #[derive(Debug, Deserialize)] pub struct ProposerGreeting { pub tenant_id: TenantId, pub timeline_id: TimelineId, pub mconf: membership::Configuration, /// Postgres server version pub pg_version: PgVersionId, pub system_id: SystemId, pub wal_seg_size: u32, } /// V2 of the message; exists as a struct because we (de)serialized it as is. #[derive(Debug, Deserialize)] pub struct ProposerGreetingV2 { /// proposer-acceptor protocol version pub protocol_version: u32, /// Postgres server version pub pg_version: PgVersionId, pub proposer_id: PgUuid, pub system_id: SystemId, pub timeline_id: TimelineId, pub tenant_id: TenantId, pub tli: TimeLineID, pub wal_seg_size: u32, } /// Acceptor -> Proposer initial response: the highest term known to me /// (acceptor voted for). #[derive(Debug, Serialize)] pub struct AcceptorGreeting { node_id: NodeId, mconf: membership::Configuration, term: u64, } /// Vote request sent from proposer to safekeepers #[derive(Debug)] pub struct VoteRequest { pub generation: Generation, pub term: Term, } /// V2 of the message; exists as a struct because we (de)serialized it as is. #[derive(Debug, Deserialize)] pub struct VoteRequestV2 { pub term: Term, } /// Vote itself, sent from safekeeper to proposer #[derive(Debug, Serialize)] pub struct VoteResponse { generation: Generation, // membership conf generation pub term: Term, // safekeeper's current term; if it is higher than proposer's, the compute is out of date. vote_given: bool, // Safekeeper flush_lsn (end of WAL) + history of term switches allow // proposer to choose the most advanced one. pub flush_lsn: Lsn, truncate_lsn: Lsn, pub term_history: TermHistory, } /* * Proposer -> Acceptor message announcing proposer is elected and communicating * term history to it. */ #[derive(Debug, Clone)] pub struct ProposerElected { pub generation: Generation, // membership conf generation pub term: Term, pub start_streaming_at: Lsn, pub term_history: TermHistory, } /// Request with WAL message sent from proposer to safekeeper. Along the way it /// communicates commit_lsn. #[derive(Debug)] pub struct AppendRequest { pub h: AppendRequestHeader, pub wal_data: Bytes, } #[derive(Debug, Clone, Deserialize)] pub struct AppendRequestHeader { pub generation: Generation, // membership conf generation // safekeeper's current term; if it is higher than proposer's, the compute is out of date. pub term: Term, /// start position of message in WAL pub begin_lsn: Lsn, /// end position of message in WAL pub end_lsn: Lsn, /// LSN committed by quorum of safekeepers pub commit_lsn: Lsn, /// minimal LSN which may be needed by proposer to perform recovery of some safekeeper pub truncate_lsn: Lsn, } /// V2 of the message; exists as a struct because we (de)serialized it as is. #[derive(Debug, Clone, Deserialize)] pub struct AppendRequestHeaderV2 { // safekeeper's current term; if it is higher than proposer's, the compute is out of date. pub term: Term, // TODO: remove this field from the protocol, it in unused -- LSN of term // switch can be taken from ProposerElected (as well as from term history). pub term_start_lsn: Lsn, /// start position of message in WAL pub begin_lsn: Lsn, /// end position of message in WAL pub end_lsn: Lsn, /// LSN committed by quorum of safekeepers pub commit_lsn: Lsn, /// minimal LSN which may be needed by proposer to perform recovery of some safekeeper pub truncate_lsn: Lsn, // only for logging/debugging pub proposer_uuid: PgUuid, } /// Report safekeeper state to proposer #[derive(Debug, Serialize, Clone)] pub struct AppendResponse { // Membership conf generation. Not strictly required because on mismatch // connection is reset, but let's sanity check it. generation: Generation, // Current term of the safekeeper; if it is higher than proposer's, the // compute is out of date. pub term: Term, // Flushed end of wal on safekeeper; one should be always mindful from what // term history this value comes, either checking history directly or // observing term being set to one for which WAL truncation is known to have // happened. pub flush_lsn: Lsn, // We report back our awareness about which WAL is committed, as this is // a criterion for walproposer --sync mode exit pub commit_lsn: Lsn, pub hs_feedback: HotStandbyFeedback, pub pageserver_feedback: Option<PageserverFeedback>, } impl AppendResponse { fn term_only(generation: Generation, term: Term) -> AppendResponse { AppendResponse { generation, term, flush_lsn: Lsn(0), commit_lsn: Lsn(0), hs_feedback: HotStandbyFeedback::empty(), pageserver_feedback: None, } } } /// Proposer -> Acceptor messages #[derive(Debug)] pub enum ProposerAcceptorMessage { Greeting(ProposerGreeting), VoteRequest(VoteRequest), Elected(ProposerElected), AppendRequest(AppendRequest), NoFlushAppendRequest(AppendRequest), FlushWAL, } /// Augment Bytes with fallible get_uN where N is number of bytes methods. /// All reads are in network (big endian) order. trait BytesF { fn get_u8_f(&mut self) -> Result<u8>; fn get_u16_f(&mut self) -> Result<u16>; fn get_u32_f(&mut self) -> Result<u32>; fn get_u64_f(&mut self) -> Result<u64>; } impl BytesF for Bytes { fn get_u8_f(&mut self) -> Result<u8> { if self.is_empty() { bail!("no bytes left, expected 1"); } Ok(self.get_u8()) } fn get_u16_f(&mut self) -> Result<u16> { if self.remaining() < 2 { bail!("no bytes left, expected 2"); } Ok(self.get_u16()) } fn get_u32_f(&mut self) -> Result<u32> { if self.remaining() < 4 { bail!("only {} bytes left, expected 4", self.remaining()); } Ok(self.get_u32()) } fn get_u64_f(&mut self) -> Result<u64> { if self.remaining() < 8 { bail!("only {} bytes left, expected 8", self.remaining()); } Ok(self.get_u64()) } } impl ProposerAcceptorMessage { /// Read cstring from Bytes. fn get_cstr(buf: &mut Bytes) -> Result<String> { let pos = buf .iter() .position(|x| *x == 0) .ok_or_else(|| anyhow::anyhow!("missing cstring terminator"))?; let result = buf.split_to(pos); buf.advance(1); // drop the null terminator match std::str::from_utf8(&result) { Ok(s) => Ok(s.to_string()), Err(e) => bail!("invalid utf8 in cstring: {}", e), } } /// Read membership::Configuration from Bytes. fn get_mconf(buf: &mut Bytes) -> Result<membership::Configuration> { let generation = Generation::new(buf.get_u32_f().with_context(|| "reading generation")?); let members_len = buf.get_u32_f().with_context(|| "reading members_len")?; // Main member set must have at least someone in valid configuration. // Empty conf is allowed until we fully migrate. if generation != INVALID_GENERATION && members_len == 0 { bail!("empty members_len"); } let mut members = MemberSet::empty(); for i in 0..members_len { let id = buf .get_u64_f() .with_context(|| format!("reading member {i} node_id"))?; let host = Self::get_cstr(buf).with_context(|| format!("reading member {i} host"))?; let pg_port = buf .get_u16_f() .with_context(|| format!("reading member {i} port"))?; let sk = SafekeeperId { id: NodeId(id), host, pg_port, }; members.add(sk)?; } let new_members_len = buf.get_u32_f().with_context(|| "reading new_members_len")?; // Non joint conf. if new_members_len == 0 { Ok(membership::Configuration { generation, members, new_members: None, }) } else { let mut new_members = MemberSet::empty(); for i in 0..new_members_len { let id = buf .get_u64_f() .with_context(|| format!("reading new member {i} node_id"))?; let host = Self::get_cstr(buf).with_context(|| format!("reading new member {i} host"))?; let pg_port = buf .get_u16_f() .with_context(|| format!("reading new member {i} port"))?; let sk = SafekeeperId { id: NodeId(id), host, pg_port, }; new_members.add(sk)?; } Ok(membership::Configuration { generation, members, new_members: Some(new_members), }) } } /// Parse proposer message. pub fn parse(mut msg_bytes: Bytes, proto_version: u32) -> Result<ProposerAcceptorMessage> { if proto_version == SK_PROTO_VERSION_3 { if msg_bytes.is_empty() { bail!("ProposerAcceptorMessage is not complete: missing tag"); } let tag = msg_bytes.get_u8_f().with_context(|| { "ProposerAcceptorMessage is not complete: missing tag".to_string() })? as char; match tag { 'g' => { let tenant_id_str = Self::get_cstr(&mut msg_bytes).with_context(|| "reading tenant_id")?; let tenant_id = TenantId::from_str(&tenant_id_str)?; let timeline_id_str = Self::get_cstr(&mut msg_bytes).with_context(|| "reading timeline_id")?; let timeline_id = TimelineId::from_str(&timeline_id_str)?; let mconf = Self::get_mconf(&mut msg_bytes)?; let pg_version = msg_bytes .get_u32_f() .with_context(|| "reading pg_version")?; let system_id = msg_bytes.get_u64_f().with_context(|| "reading system_id")?; let wal_seg_size = msg_bytes .get_u32_f() .with_context(|| "reading wal_seg_size")?; let g = ProposerGreeting { tenant_id, timeline_id, mconf, pg_version: PgVersionId::from_full_pg_version(pg_version), system_id, wal_seg_size, }; Ok(ProposerAcceptorMessage::Greeting(g)) } 'v' => { let generation = Generation::new( msg_bytes .get_u32_f() .with_context(|| "reading generation")?, ); let term = msg_bytes.get_u64_f().with_context(|| "reading term")?; let v = VoteRequest { generation, term }; Ok(ProposerAcceptorMessage::VoteRequest(v)) } 'e' => { let generation = Generation::new( msg_bytes .get_u32_f() .with_context(|| "reading generation")?, ); let term = msg_bytes.get_u64_f().with_context(|| "reading term")?; let start_streaming_at: Lsn = msg_bytes .get_u64_f() .with_context(|| "reading start_streaming_at")? .into(); let term_history = TermHistory::from_bytes(&mut msg_bytes)?; let msg = ProposerElected { generation, term, start_streaming_at, term_history, }; Ok(ProposerAcceptorMessage::Elected(msg)) } 'a' => { let generation = Generation::new( msg_bytes .get_u32_f() .with_context(|| "reading generation")?, ); let term = msg_bytes.get_u64_f().with_context(|| "reading term")?; let begin_lsn: Lsn = msg_bytes .get_u64_f() .with_context(|| "reading begin_lsn")? .into(); let end_lsn: Lsn = msg_bytes .get_u64_f() .with_context(|| "reading end_lsn")? .into(); let commit_lsn: Lsn = msg_bytes .get_u64_f() .with_context(|| "reading commit_lsn")? .into(); let truncate_lsn: Lsn = msg_bytes .get_u64_f() .with_context(|| "reading truncate_lsn")? .into(); let hdr = AppendRequestHeader { generation, term, begin_lsn, end_lsn, commit_lsn, truncate_lsn, }; let rec_size = hdr .end_lsn .checked_sub(hdr.begin_lsn) .context("begin_lsn > end_lsn in AppendRequest")? .0 as usize; if rec_size > MAX_SEND_SIZE { bail!( "AppendRequest is longer than MAX_SEND_SIZE ({})", MAX_SEND_SIZE ); } if msg_bytes.remaining() < rec_size { bail!( "reading WAL: only {} bytes left, wanted {}", msg_bytes.remaining(), rec_size ); } let wal_data = msg_bytes.copy_to_bytes(rec_size); let msg = AppendRequest { h: hdr, wal_data }; Ok(ProposerAcceptorMessage::AppendRequest(msg)) } _ => bail!("unknown proposer-acceptor message tag: {}", tag), } } else if proto_version == SK_PROTO_VERSION_2 { // xxx using Reader is inefficient but easy to work with bincode let mut stream = msg_bytes.reader(); // u64 is here to avoid padding; it will be removed once we stop packing C structs into the wire as is let tag = stream.read_u64::<LittleEndian>()? as u8 as char; match tag { 'g' => { let msgv2 = ProposerGreetingV2::des_from(&mut stream)?; let g = ProposerGreeting { tenant_id: msgv2.tenant_id, timeline_id: msgv2.timeline_id, mconf: membership::Configuration { generation: INVALID_GENERATION, members: MemberSet::empty(), new_members: None, }, pg_version: msgv2.pg_version, system_id: msgv2.system_id, wal_seg_size: msgv2.wal_seg_size, }; Ok(ProposerAcceptorMessage::Greeting(g)) } 'v' => { let msg = VoteRequestV2::des_from(&mut stream)?; let v = VoteRequest { generation: INVALID_GENERATION, term: msg.term, }; Ok(ProposerAcceptorMessage::VoteRequest(v)) } 'e' => { let mut msg_bytes = stream.into_inner(); if msg_bytes.remaining() < 16 { bail!("ProposerElected message is not complete"); } let term = msg_bytes.get_u64_le(); let start_streaming_at = msg_bytes.get_u64_le().into(); let term_history = TermHistory::from_bytes_le(&mut msg_bytes)?; if msg_bytes.remaining() < 8 { bail!("ProposerElected message is not complete"); } let _timeline_start_lsn = msg_bytes.get_u64_le(); let msg = ProposerElected { generation: INVALID_GENERATION, term, start_streaming_at, term_history, }; Ok(ProposerAcceptorMessage::Elected(msg)) } 'a' => { // read header followed by wal data let hdrv2 = AppendRequestHeaderV2::des_from(&mut stream)?; let hdr = AppendRequestHeader { generation: INVALID_GENERATION, term: hdrv2.term, begin_lsn: hdrv2.begin_lsn, end_lsn: hdrv2.end_lsn, commit_lsn: hdrv2.commit_lsn, truncate_lsn: hdrv2.truncate_lsn, }; let rec_size = hdr .end_lsn .checked_sub(hdr.begin_lsn) .context("begin_lsn > end_lsn in AppendRequest")? .0 as usize; if rec_size > MAX_SEND_SIZE { bail!( "AppendRequest is longer than MAX_SEND_SIZE ({})", MAX_SEND_SIZE ); } let mut wal_data_vec: Vec<u8> = vec![0; rec_size]; stream.read_exact(&mut wal_data_vec)?; let wal_data = Bytes::from(wal_data_vec); let msg = AppendRequest { h: hdr, wal_data }; Ok(ProposerAcceptorMessage::AppendRequest(msg)) } _ => bail!("unknown proposer-acceptor message tag: {}", tag), } } else { bail!("unsupported protocol version {}", proto_version); } } /// The memory size of the message, including byte slices. pub fn size(&self) -> usize { const BASE_SIZE: usize = std::mem::size_of::<ProposerAcceptorMessage>(); // For most types, the size is just the base enum size including the nested structs. Some // types also contain byte slices; add them. // // We explicitly list all fields, to draw attention here when new fields are added. let mut size = BASE_SIZE; size += match self { Self::Greeting(_) => 0, Self::VoteRequest(_) => 0, Self::Elected(_) => 0, Self::AppendRequest(AppendRequest { h: AppendRequestHeader { generation: _, term: _, begin_lsn: _, end_lsn: _, commit_lsn: _, truncate_lsn: _, }, wal_data, }) => wal_data.len(), Self::NoFlushAppendRequest(AppendRequest { h: AppendRequestHeader { generation: _, term: _, begin_lsn: _, end_lsn: _, commit_lsn: _, truncate_lsn: _, }, wal_data, }) => wal_data.len(), Self::FlushWAL => 0, }; size } } /// Acceptor -> Proposer messages #[derive(Debug)] pub enum AcceptorProposerMessage { Greeting(AcceptorGreeting), VoteResponse(VoteResponse), AppendResponse(AppendResponse), } impl AcceptorProposerMessage { fn put_cstr(buf: &mut BytesMut, s: &str) { buf.put_slice(s.as_bytes()); buf.put_u8(0); // null terminator } /// Serialize membership::Configuration into buf. fn serialize_mconf(buf: &mut BytesMut, mconf: &membership::Configuration) { buf.put_u32(mconf.generation.into_inner()); buf.put_u32(mconf.members.m.len() as u32); for sk in &mconf.members.m { buf.put_u64(sk.id.0); Self::put_cstr(buf, &sk.host); buf.put_u16(sk.pg_port); } if let Some(ref new_members) = mconf.new_members { buf.put_u32(new_members.m.len() as u32); for sk in &new_members.m { buf.put_u64(sk.id.0); Self::put_cstr(buf, &sk.host); buf.put_u16(sk.pg_port); } } else { buf.put_u32(0); } } /// Serialize acceptor -> proposer message. pub fn serialize(&self, buf: &mut BytesMut, proto_version: u32) -> Result<()> { if proto_version == SK_PROTO_VERSION_3 { match self { AcceptorProposerMessage::Greeting(msg) => { buf.put_u8(b'g'); buf.put_u64(msg.node_id.0); Self::serialize_mconf(buf, &msg.mconf); buf.put_u64(msg.term) } AcceptorProposerMessage::VoteResponse(msg) => { buf.put_u8(b'v'); buf.put_u32(msg.generation.into_inner()); buf.put_u64(msg.term); buf.put_u8(msg.vote_given as u8); buf.put_u64(msg.flush_lsn.into()); buf.put_u64(msg.truncate_lsn.into()); buf.put_u32(msg.term_history.0.len() as u32); for e in &msg.term_history.0 { buf.put_u64(e.term); buf.put_u64(e.lsn.into()); } } AcceptorProposerMessage::AppendResponse(msg) => { buf.put_u8(b'a'); buf.put_u32(msg.generation.into_inner()); buf.put_u64(msg.term); buf.put_u64(msg.flush_lsn.into()); buf.put_u64(msg.commit_lsn.into()); buf.put_i64(msg.hs_feedback.ts); buf.put_u64(msg.hs_feedback.xmin); buf.put_u64(msg.hs_feedback.catalog_xmin); // AsyncReadMessage in walproposer.c will not try to decode pageserver_feedback // if it is not present. if let Some(ref msg) = msg.pageserver_feedback { msg.serialize(buf); } } } Ok(()) // TODO remove 3 after converting all msgs } else if proto_version == SK_PROTO_VERSION_2 { match self { AcceptorProposerMessage::Greeting(msg) => { buf.put_u64_le('g' as u64); // v2 didn't have mconf and fields were reordered buf.put_u64_le(msg.term); buf.put_u64_le(msg.node_id.0); } AcceptorProposerMessage::VoteResponse(msg) => { // v2 didn't have generation, had u64 vote_given and timeline_start_lsn buf.put_u64_le('v' as u64); buf.put_u64_le(msg.term); buf.put_u64_le(msg.vote_given as u64); buf.put_u64_le(msg.flush_lsn.into()); buf.put_u64_le(msg.truncate_lsn.into()); buf.put_u32_le(msg.term_history.0.len() as u32); for e in &msg.term_history.0 { buf.put_u64_le(e.term); buf.put_u64_le(e.lsn.into()); } // removed timeline_start_lsn buf.put_u64_le(0); } AcceptorProposerMessage::AppendResponse(msg) => { // v2 didn't have generation buf.put_u64_le('a' as u64); buf.put_u64_le(msg.term); buf.put_u64_le(msg.flush_lsn.into()); buf.put_u64_le(msg.commit_lsn.into()); buf.put_i64_le(msg.hs_feedback.ts); buf.put_u64_le(msg.hs_feedback.xmin); buf.put_u64_le(msg.hs_feedback.catalog_xmin); // AsyncReadMessage in walproposer.c will not try to decode pageserver_feedback // if it is not present. if let Some(ref msg) = msg.pageserver_feedback { msg.serialize(buf); } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/test_utils.rs
safekeeper/src/test_utils.rs
use std::ffi::CStr; use std::sync::Arc; use camino_tempfile::Utf8TempDir; use postgres_ffi::v17::wal_generator::{LogicalMessageGenerator, WalGenerator}; use safekeeper_api::membership::SafekeeperGeneration as Generation; use tokio::fs::create_dir_all; use utils::id::{NodeId, TenantTimelineId}; use utils::lsn::Lsn; use crate::rate_limit::RateLimiter; use crate::receive_wal::WalAcceptor; use crate::safekeeper::{ AcceptorProposerMessage, AppendRequest, AppendRequestHeader, ProposerAcceptorMessage, ProposerElected, SafeKeeper, TermHistory, }; use crate::send_wal::EndWatch; use crate::state::{TimelinePersistentState, TimelineState}; use crate::timeline::{SharedState, StateSK, Timeline, get_timeline_dir}; use crate::timelines_set::TimelinesSet; use crate::wal_backup::{WalBackup, remote_timeline_path}; use crate::{SafeKeeperConf, control_file, receive_wal, wal_storage}; /// A Safekeeper testing or benchmarking environment. Uses a tempdir for storage, removed on drop. pub struct Env { /// Whether to enable fsync. pub fsync: bool, /// Benchmark directory. Deleted when dropped. pub tempdir: Utf8TempDir, } impl Env { /// Creates a new test or benchmarking environment in a temporary directory. fsync controls whether to /// enable fsyncing. pub fn new(fsync: bool) -> anyhow::Result<Self> { let tempdir = camino_tempfile::tempdir()?; Ok(Self { fsync, tempdir }) } /// Constructs a Safekeeper config for the given node ID. fn make_conf(&self, node_id: NodeId) -> SafeKeeperConf { let mut conf = SafeKeeperConf::dummy(); conf.my_id = node_id; conf.no_sync = !self.fsync; conf.workdir = self.tempdir.path().join(format!("safekeeper-{node_id}")); conf } /// Constructs a Safekeeper with the given node and tenant/timeline ID. /// /// TODO: we should support using in-memory storage, to measure non-IO costs. This would be /// easier if SafeKeeper used trait objects for storage rather than generics. It's also not /// currently possible to construct a timeline using non-file storage since StateSK only accepts /// SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>. pub async fn make_safekeeper( &self, node_id: NodeId, ttid: TenantTimelineId, start_lsn: Lsn, ) -> anyhow::Result<SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>> { let conf = self.make_conf(node_id); let timeline_dir = get_timeline_dir(&conf, &ttid); create_dir_all(&timeline_dir).await?; let mut pstate = TimelinePersistentState::empty(); pstate.tenant_id = ttid.tenant_id; pstate.timeline_id = ttid.timeline_id; let wal = wal_storage::PhysicalStorage::new(&ttid, &timeline_dir, &pstate, conf.no_sync)?; let ctrl = control_file::FileStorage::create_new(&timeline_dir, pstate, conf.no_sync).await?; let state = TimelineState::new(ctrl); let mut safekeeper = SafeKeeper::new(state, wal, conf.my_id)?; // Emulate an initial election. safekeeper .process_msg(&ProposerAcceptorMessage::Elected(ProposerElected { generation: Generation::new(0), term: 1, start_streaming_at: start_lsn, term_history: TermHistory(vec![(1, start_lsn).into()]), })) .await?; Ok(safekeeper) } /// Constructs a timeline, including a new Safekeeper with the given node ID, and spawns its /// manager task. pub async fn make_timeline( &self, node_id: NodeId, ttid: TenantTimelineId, start_lsn: Lsn, ) -> anyhow::Result<Arc<Timeline>> { let conf = Arc::new(self.make_conf(node_id)); let timeline_dir = get_timeline_dir(&conf, &ttid); let remote_path = remote_timeline_path(&ttid)?; let safekeeper = self.make_safekeeper(node_id, ttid, start_lsn).await?; let shared_state = SharedState::new(StateSK::Loaded(safekeeper)); let wal_backup = Arc::new(WalBackup::new(&conf).await?); let timeline = Timeline::new( ttid, &timeline_dir, &remote_path, shared_state, conf.clone(), wal_backup.clone(), ); timeline.bootstrap( &mut timeline.write_shared_state().await, &conf, Arc::new(TimelinesSet::default()), // ignored for now RateLimiter::new(0, 0), wal_backup, ); Ok(timeline) } // This will be dead code when building a non-benchmark target with the // benchmarking feature enabled. #[allow(dead_code)] pub(crate) async fn write_wal( tli: Arc<Timeline>, start_lsn: Lsn, msg_size: usize, msg_count: usize, prefix: &CStr, mut next_record_lsns: Option<&mut Vec<Lsn>>, ) -> anyhow::Result<EndWatch> { let (msg_tx, msg_rx) = tokio::sync::mpsc::channel(receive_wal::MSG_QUEUE_SIZE); let (reply_tx, mut reply_rx) = tokio::sync::mpsc::channel(receive_wal::REPLY_QUEUE_SIZE); let end_watch = EndWatch::Commit(tli.get_commit_lsn_watch_rx()); WalAcceptor::spawn(tli.wal_residence_guard().await?, msg_rx, reply_tx, Some(0)); let prefixlen = prefix.to_bytes_with_nul().len(); assert!(msg_size >= prefixlen); let message = vec![0; msg_size - prefixlen]; let walgen = &mut WalGenerator::new(LogicalMessageGenerator::new(prefix, &message), start_lsn); for _ in 0..msg_count { let (lsn, record) = walgen.next().unwrap(); if let Some(ref mut lsns) = next_record_lsns { lsns.push(lsn); } let req = AppendRequest { h: AppendRequestHeader { generation: Generation::new(0), term: 1, begin_lsn: lsn, end_lsn: lsn + record.len() as u64, commit_lsn: lsn, truncate_lsn: Lsn(0), }, wal_data: record, }; let end_lsn = req.h.end_lsn; let msg = ProposerAcceptorMessage::AppendRequest(req); msg_tx.send(msg).await?; while let Some(reply) = reply_rx.recv().await { if let AcceptorProposerMessage::AppendResponse(resp) = reply { if resp.flush_lsn >= end_lsn { break; } } } } Ok(end_watch) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/remove_wal.rs
safekeeper/src/remove_wal.rs
use utils::lsn::Lsn; use crate::timeline_manager::StateSnapshot; /// Get oldest LSN we still need to keep. /// /// We hold WAL till it is consumed by /// 1) pageserver (remote_consistent_lsn) /// 2) s3 offloading. /// 3) Additionally we must store WAL since last local commit_lsn because /// that's where we start looking for last WAL record on start. /// /// If some peer safekeeper misses data it will fetch it from the remote /// storage. While it is safe to use inmem values for determining horizon, we /// use persistent to make possible normal states less surprising. All segments /// covering LSNs before horizon_lsn can be removed. pub(crate) fn calc_horizon_lsn(state: &StateSnapshot, extra_horizon_lsn: Option<Lsn>) -> Lsn { use std::cmp::min; let mut horizon_lsn = state.cfile_remote_consistent_lsn; // we don't want to remove WAL that is not yet offloaded to s3 horizon_lsn = min(horizon_lsn, state.cfile_backup_lsn); // Min by local commit_lsn to be able to begin reading WAL from somewhere on // sk start. Technically we don't allow local commit_lsn to be higher than // flush_lsn, but let's be double safe by including it as well. horizon_lsn = min(horizon_lsn, state.cfile_commit_lsn); horizon_lsn = min(horizon_lsn, state.flush_lsn); if let Some(extra_horizon_lsn) = extra_horizon_lsn { horizon_lsn = min(horizon_lsn, extra_horizon_lsn); } horizon_lsn }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/timeline_eviction.rs
safekeeper/src/timeline_eviction.rs
//! Code related to evicting WAL files to remote storage. //! //! The actual upload is done by the partial WAL backup code. This file has //! code to delete and re-download WAL files, cross-validate with partial WAL //! backup if local file is still present. use anyhow::Context; use camino::Utf8PathBuf; use remote_storage::{GenericRemoteStorage, RemotePath}; use tokio::fs::File; use tokio::io::{AsyncRead, AsyncWriteExt}; use tracing::{debug, info, instrument, warn}; use utils::crashsafe::durable_rename; use crate::metrics::{ EVICTION_EVENTS_COMPLETED, EVICTION_EVENTS_STARTED, EvictionEvent, NUM_EVICTED_TIMELINES, }; use crate::rate_limit::rand_duration; use crate::timeline_manager::{Manager, StateSnapshot}; use crate::wal_backup; use crate::wal_backup_partial::{self, PartialRemoteSegment}; use crate::wal_storage::wal_file_paths; impl Manager { /// Returns true if the timeline is ready for eviction. /// Current criteria: /// - no active tasks /// - control file is flushed (no next event scheduled) /// - no WAL residence guards /// - no pushes to the broker /// - last partial WAL segment is uploaded /// - all local segments before the uploaded partial are committed and uploaded pub(crate) fn ready_for_eviction( &self, next_event: &Option<tokio::time::Instant>, state: &StateSnapshot, ) -> bool { self.backup_task.is_none() && self.recovery_task.is_none() && self.wal_removal_task.is_none() && self.partial_backup_task.is_none() && next_event.is_none() && self.access_service.is_empty() && !self.tli_broker_active.get() // Partial segment of current flush_lsn is uploaded up to this flush_lsn. && !wal_backup_partial::needs_uploading(state, &self.partial_backup_uploaded) // And it is the next one after the last removed. Given that local // WAL is removed only after it is uploaded to s3 (and pageserver // advancing remote_consistent_lsn) which happens only after WAL is // committed, true means all this is done. // // This also works for the first segment despite last_removed_segno // being 0 on init because this 0 triggers run of wal_removal_task // on success of which manager updates the horizon. // // **Note** pull_timeline functionality assumes that evicted timelines always have // a partial segment: if we ever change this condition, must also update that code. && self .partial_backup_uploaded .as_ref() .unwrap() .flush_lsn .segment_number(self.wal_seg_size) == self.last_removed_segno + 1 } /// Evict the timeline to remote storage. Returns whether the eviction was successful. #[instrument(name = "evict_timeline", skip_all)] pub(crate) async fn evict_timeline(&mut self) -> bool { assert!(!self.is_offloaded); let Some(storage) = self.wal_backup.get_storage() else { warn!("no remote storage configured, skipping uneviction"); return false; }; let partial_backup_uploaded = match &self.partial_backup_uploaded { Some(p) => p.clone(), None => { warn!("no partial backup uploaded, skipping eviction"); return false; } }; info!("starting eviction, using {:?}", partial_backup_uploaded); EVICTION_EVENTS_STARTED .with_label_values(&[EvictionEvent::Evict.into()]) .inc(); let _guard = scopeguard::guard((), |_| { EVICTION_EVENTS_COMPLETED .with_label_values(&[EvictionEvent::Evict.into()]) .inc(); }); if let Err(e) = do_eviction(self, &partial_backup_uploaded, &storage).await { warn!("failed to evict timeline: {:?}", e); return false; } info!("successfully evicted timeline"); NUM_EVICTED_TIMELINES.inc(); true } /// Attempt to restore evicted timeline from remote storage; it must be /// offloaded. #[instrument(name = "unevict_timeline", skip_all)] pub(crate) async fn unevict_timeline(&mut self) { assert!(self.is_offloaded); let Some(storage) = self.wal_backup.get_storage() else { warn!("no remote storage configured, skipping uneviction"); return; }; let partial_backup_uploaded = match &self.partial_backup_uploaded { Some(p) => p.clone(), None => { warn!("no partial backup uploaded, cannot unevict"); return; } }; info!("starting uneviction, using {:?}", partial_backup_uploaded); EVICTION_EVENTS_STARTED .with_label_values(&[EvictionEvent::Restore.into()]) .inc(); let _guard = scopeguard::guard((), |_| { EVICTION_EVENTS_COMPLETED .with_label_values(&[EvictionEvent::Restore.into()]) .inc(); }); if let Err(e) = do_uneviction(self, &partial_backup_uploaded, &storage).await { warn!("failed to unevict timeline: {:?}", e); return; } self.evict_not_before = tokio::time::Instant::now() + rand_duration(&self.conf.eviction_min_resident); info!("successfully restored evicted timeline"); NUM_EVICTED_TIMELINES.dec(); } } /// Ensure that content matches the remote partial backup, if local segment exists. /// Then change state in control file and in-memory. If `delete_offloaded_wal` is set, /// delete the local segment. async fn do_eviction( mgr: &mut Manager, partial: &PartialRemoteSegment, storage: &GenericRemoteStorage, ) -> anyhow::Result<()> { compare_local_segment_with_remote(mgr, partial, storage).await?; mgr.tli.switch_to_offloaded(partial).await?; // switch manager state as soon as possible mgr.is_offloaded = true; if mgr.conf.delete_offloaded_wal { delete_local_segment(mgr, partial).await?; } Ok(()) } /// Ensure that content matches the remote partial backup, if local segment exists. /// Then download segment to local disk and change state in control file and in-memory. async fn do_uneviction( mgr: &mut Manager, partial: &PartialRemoteSegment, storage: &GenericRemoteStorage, ) -> anyhow::Result<()> { // if the local segment is present, validate it compare_local_segment_with_remote(mgr, partial, storage).await?; // atomically download the partial segment redownload_partial_segment(mgr, partial, storage).await?; mgr.tli.switch_to_present().await?; // switch manager state as soon as possible mgr.is_offloaded = false; Ok(()) } /// Delete local WAL segment. async fn delete_local_segment(mgr: &Manager, partial: &PartialRemoteSegment) -> anyhow::Result<()> { let local_path = local_segment_path(mgr, partial); info!("deleting WAL file to evict: {}", local_path); tokio::fs::remove_file(&local_path).await?; Ok(()) } /// Redownload partial segment from remote storage. /// The segment is downloaded to a temporary file and then renamed to the final path. async fn redownload_partial_segment( mgr: &Manager, partial: &PartialRemoteSegment, storage: &GenericRemoteStorage, ) -> anyhow::Result<()> { let tmp_file = mgr.tli.timeline_dir().join("remote_partial.tmp"); let remote_segfile = remote_segment_path(mgr, partial); debug!( "redownloading partial segment: {} -> {}", remote_segfile, tmp_file ); let mut reader = wal_backup::read_object(storage, &remote_segfile, 0).await?; let mut file = File::create(&tmp_file).await?; let actual_len = tokio::io::copy(&mut reader, &mut file).await?; let expected_len = partial.flush_lsn.segment_offset(mgr.wal_seg_size); if actual_len != expected_len as u64 { anyhow::bail!( "partial downloaded {} bytes, expected {}", actual_len, expected_len ); } if actual_len > mgr.wal_seg_size as u64 { anyhow::bail!( "remote segment is too long: {} bytes, expected {}", actual_len, mgr.wal_seg_size ); } file.set_len(mgr.wal_seg_size as u64).await?; file.flush().await?; let final_path = local_segment_path(mgr, partial); info!("downloaded {actual_len} bytes, renaming to {final_path}"); if let Err(e) = durable_rename(&tmp_file, &final_path, !mgr.conf.no_sync).await { // Probably rename succeeded, but fsync of it failed. Remove // the file then to avoid using it. tokio::fs::remove_file(tmp_file) .await .or_else(utils::fs_ext::ignore_not_found)?; return Err(e.into()); } Ok(()) } /// Compare local WAL segment with partial WAL backup in remote storage. /// If the local segment is not present, the function does nothing. /// If the local segment is present, it compares the local segment with the remote one. async fn compare_local_segment_with_remote( mgr: &Manager, partial: &PartialRemoteSegment, storage: &GenericRemoteStorage, ) -> anyhow::Result<()> { let local_path = local_segment_path(mgr, partial); match File::open(&local_path).await { Ok(mut local_file) => { do_validation(mgr, &mut local_file, mgr.wal_seg_size, partial, storage) .await .context("validation failed") } Err(_) => { info!( "local WAL file {} is not present, skipping validation", local_path ); Ok(()) } } } /// Compare opened local WAL segment with partial WAL backup in remote storage. /// Validate full content of both files. async fn do_validation( mgr: &Manager, file: &mut File, wal_seg_size: usize, partial: &PartialRemoteSegment, storage: &GenericRemoteStorage, ) -> anyhow::Result<()> { let local_size = file.metadata().await?.len() as usize; if local_size != wal_seg_size { anyhow::bail!( "local segment size is invalid: found {}, expected {}", local_size, wal_seg_size ); } let remote_segfile = remote_segment_path(mgr, partial); let mut remote_reader: std::pin::Pin<Box<dyn AsyncRead + Send + Sync>> = wal_backup::read_object(storage, &remote_segfile, 0).await?; // remote segment should have bytes excatly up to `flush_lsn` let expected_remote_size = partial.flush_lsn.segment_offset(mgr.wal_seg_size); // let's compare the first `expected_remote_size` bytes compare_n_bytes(&mut remote_reader, file, expected_remote_size).await?; // and check that the remote segment ends here check_end(&mut remote_reader).await?; // if local segment is longer, the rest should be zeroes read_n_zeroes(file, mgr.wal_seg_size - expected_remote_size).await?; // and check that the local segment ends here check_end(file).await?; Ok(()) } fn local_segment_path(mgr: &Manager, partial: &PartialRemoteSegment) -> Utf8PathBuf { let flush_lsn = partial.flush_lsn; let segno = flush_lsn.segment_number(mgr.wal_seg_size); let (_, local_partial_segfile) = wal_file_paths(mgr.tli.timeline_dir(), segno, mgr.wal_seg_size); local_partial_segfile } fn remote_segment_path(mgr: &Manager, partial: &PartialRemoteSegment) -> RemotePath { partial.remote_path(&mgr.tli.remote_path) } /// Compare first `n` bytes of two readers. If the bytes differ, return an error. /// If the readers are shorter than `n`, return an error. async fn compare_n_bytes<R1, R2>(reader1: &mut R1, reader2: &mut R2, n: usize) -> anyhow::Result<()> where R1: AsyncRead + Unpin, R2: AsyncRead + Unpin, { use tokio::io::AsyncReadExt; const BUF_SIZE: usize = 32 * 1024; let mut buffer1 = vec![0u8; BUF_SIZE]; let mut buffer2 = vec![0u8; BUF_SIZE]; let mut offset = 0; while offset < n { let bytes_to_read = std::cmp::min(BUF_SIZE, n - offset); let bytes_read1 = reader1 .read(&mut buffer1[..bytes_to_read]) .await .with_context(|| format!("failed to read from reader1 at offset {offset}"))?; if bytes_read1 == 0 { anyhow::bail!("unexpected EOF from reader1 at offset {}", offset); } let bytes_read2 = reader2 .read_exact(&mut buffer2[..bytes_read1]) .await .with_context(|| { format!("failed to read {bytes_read1} bytes from reader2 at offset {offset}") })?; assert!(bytes_read2 == bytes_read1); if buffer1[..bytes_read1] != buffer2[..bytes_read2] { let diff_offset = buffer1[..bytes_read1] .iter() .zip(buffer2[..bytes_read2].iter()) .position(|(a, b)| a != b) .expect("mismatched buffers, but no difference found"); anyhow::bail!("mismatch at offset {}", offset + diff_offset); } offset += bytes_read1; } Ok(()) } async fn check_end<R>(mut reader: R) -> anyhow::Result<()> where R: AsyncRead + Unpin, { use tokio::io::AsyncReadExt; let mut buffer = [0u8; 1]; let bytes_read = reader.read(&mut buffer).await?; if bytes_read != 0 { anyhow::bail!("expected EOF, found bytes"); } Ok(()) } async fn read_n_zeroes<R>(reader: &mut R, n: usize) -> anyhow::Result<()> where R: AsyncRead + Unpin, { use tokio::io::AsyncReadExt; const BUF_SIZE: usize = 32 * 1024; let mut buffer = vec![0u8; BUF_SIZE]; let mut offset = 0; while offset < n { let bytes_to_read = std::cmp::min(BUF_SIZE, n - offset); let bytes_read = reader .read(&mut buffer[..bytes_to_read]) .await .context("expected zeroes, got read error")?; if bytes_read == 0 { anyhow::bail!("expected zeroes, got EOF"); } if buffer[..bytes_read].iter().all(|&b| b == 0) { offset += bytes_read; } else { anyhow::bail!("non-zero byte found"); } } Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/timelines_set.rs
safekeeper/src/timelines_set.rs
use std::collections::HashMap; use std::sync::Arc; use utils::id::TenantTimelineId; use crate::timeline::Timeline; /// Set of timelines, supports operations: /// - add timeline /// - remove timeline /// - clone the set /// /// Usually used for keeping subset of timelines. For example active timelines that require broker push. pub struct TimelinesSet { timelines: std::sync::Mutex<HashMap<TenantTimelineId, Arc<Timeline>>>, } impl Default for TimelinesSet { fn default() -> Self { Self { timelines: std::sync::Mutex::new(HashMap::new()), } } } impl TimelinesSet { pub fn insert(&self, tli: Arc<Timeline>) { self.timelines.lock().unwrap().insert(tli.ttid, tli); } pub fn delete(&self, ttid: &TenantTimelineId) { self.timelines.lock().unwrap().remove(ttid); } /// If present is true, adds timeline to the set, otherwise removes it. pub fn set_present(&self, tli: Arc<Timeline>, present: bool) { if present { self.insert(tli); } else { self.delete(&tli.ttid); } } pub fn is_present(&self, ttid: &TenantTimelineId) -> bool { self.timelines.lock().unwrap().contains_key(ttid) } /// Returns all timelines in the set. pub fn get_all(&self) -> Vec<Arc<Timeline>> { self.timelines.lock().unwrap().values().cloned().collect() } /// Returns a timeline guard for easy presence control. pub fn guard(self: &Arc<Self>, tli: Arc<Timeline>) -> TimelineSetGuard { let is_present = self.is_present(&tli.ttid); TimelineSetGuard { timelines_set: self.clone(), tli, is_present, } } } /// Guard is used to add or remove timelines from the set. /// /// If the timeline present in set, it will be removed from it on drop. /// Note: do not use more than one guard for the same timeline, it caches the presence state. /// It is designed to be used in the manager task only. pub struct TimelineSetGuard { timelines_set: Arc<TimelinesSet>, tli: Arc<Timeline>, is_present: bool, } impl TimelineSetGuard { /// Returns true if the state was changed. pub fn set(&mut self, present: bool) -> bool { if present == self.is_present { return false; } self.is_present = present; self.timelines_set.set_present(self.tli.clone(), present); true } pub fn get(&self) -> bool { self.is_present } } impl Drop for TimelineSetGuard { fn drop(&mut self) { // remove timeline from the map on drop self.timelines_set.delete(&self.tli.ttid); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/copy_timeline.rs
safekeeper/src/copy_timeline.rs
use std::sync::Arc; use anyhow::{Result, bail}; use camino::Utf8PathBuf; use postgres_ffi::{MAX_SEND_SIZE, WAL_SEGMENT_SIZE}; use remote_storage::GenericRemoteStorage; use safekeeper_api::membership::Configuration; use tokio::fs::OpenOptions; use tokio::io::{AsyncSeekExt, AsyncWriteExt}; use tracing::{info, warn}; use utils::id::TenantTimelineId; use utils::lsn::Lsn; use crate::GlobalTimelines; use crate::control_file::FileStorage; use crate::state::TimelinePersistentState; use crate::timeline::{TimelineError, WalResidentTimeline}; use crate::timelines_global_map::{create_temp_timeline_dir, validate_temp_timeline}; use crate::wal_backup::copy_s3_segments; use crate::wal_storage::{WalReader, wal_file_paths}; // we don't want to have more than 10 segments on disk after copy, because they take space const MAX_BACKUP_LAG: u64 = 10 * WAL_SEGMENT_SIZE as u64; pub struct Request { pub source_ttid: TenantTimelineId, pub until_lsn: Lsn, pub destination_ttid: TenantTimelineId, } pub async fn handle_request( request: Request, global_timelines: Arc<GlobalTimelines>, storage: Arc<GenericRemoteStorage>, ) -> Result<()> { // TODO: request.until_lsn MUST be a valid LSN, and we cannot check it :( // if LSN will point to the middle of a WAL record, timeline will be in "broken" state match global_timelines.get(request.destination_ttid) { // timeline already exists. would be good to check that this timeline is the copy // of the source timeline, but it isn't obvious how to do that Ok(_) => return Ok(()), // timeline not found, we are going to create it Err(TimelineError::NotFound(_)) => {} // error, probably timeline was deleted res => { res?; } } let source = global_timelines.get(request.source_ttid)?; let source_tli = source.wal_residence_guard().await?; let conf = &global_timelines.get_global_config(); let ttid = request.destination_ttid; let (_tmp_dir, tli_dir_path) = create_temp_timeline_dir(conf, ttid).await?; let (mem_state, state) = source_tli.get_state().await; let start_lsn = state.timeline_start_lsn; if start_lsn == Lsn::INVALID { bail!("timeline is not initialized"); } let backup_lsn = mem_state.backup_lsn; { let commit_lsn = mem_state.commit_lsn; let flush_lsn = source_tli.get_flush_lsn().await; info!( "collected info about source timeline: start_lsn={}, backup_lsn={}, commit_lsn={}, flush_lsn={}", start_lsn, backup_lsn, commit_lsn, flush_lsn ); assert!(backup_lsn >= start_lsn); assert!(commit_lsn >= start_lsn); assert!(flush_lsn >= start_lsn); if request.until_lsn > flush_lsn { bail!(format!( "requested LSN {} is beyond the end of the timeline {}", request.until_lsn, flush_lsn )); } if request.until_lsn < start_lsn { bail!(format!( "requested LSN {} is before the start of the timeline {}", request.until_lsn, start_lsn )); } if request.until_lsn > commit_lsn { warn!("copy_timeline WAL is not fully committed"); } if backup_lsn < request.until_lsn && request.until_lsn.0 - backup_lsn.0 > MAX_BACKUP_LAG { // we have a lot of segments that are not backed up. we can try to wait here until // segments will be backed up to remote storage, but it's not clear how long to wait bail!("too many segments are not backed up"); } } let wal_seg_size = state.server.wal_seg_size as usize; if wal_seg_size == 0 { bail!("wal_seg_size is not set"); } let first_segment = start_lsn.segment_number(wal_seg_size); let last_segment = request.until_lsn.segment_number(wal_seg_size); let new_backup_lsn = { // we can't have new backup_lsn greater than existing backup_lsn or start of the last segment let max_backup_lsn = backup_lsn.min(Lsn(last_segment * wal_seg_size as u64)); if max_backup_lsn <= start_lsn { // probably we are starting from the first segment, which was not backed up yet. // note that start_lsn can be in the middle of the segment start_lsn } else { // we have some segments backed up, so we will assume all WAL below max_backup_lsn is backed up assert!(max_backup_lsn.segment_offset(wal_seg_size) == 0); max_backup_lsn } }; // all previous segments will be copied inside S3 let first_ondisk_segment = new_backup_lsn.segment_number(wal_seg_size); assert!(first_ondisk_segment <= last_segment); assert!(first_ondisk_segment >= first_segment); copy_s3_segments( &storage, wal_seg_size, &request.source_ttid, &request.destination_ttid, first_segment, first_ondisk_segment, ) .await?; copy_disk_segments( &source_tli, wal_seg_size, new_backup_lsn, request.until_lsn, &tli_dir_path, ) .await?; let mut new_state = TimelinePersistentState::new( &request.destination_ttid, Configuration::empty(), state.server.clone(), start_lsn, request.until_lsn, )?; new_state.timeline_start_lsn = start_lsn; new_state.peer_horizon_lsn = request.until_lsn; new_state.backup_lsn = new_backup_lsn; FileStorage::create_new(&tli_dir_path, new_state.clone(), conf.no_sync).await?; // now we have a ready timeline in a temp directory validate_temp_timeline(conf, request.destination_ttid, &tli_dir_path, None).await?; global_timelines .load_temp_timeline(request.destination_ttid, &tli_dir_path, None) .await?; Ok(()) } async fn copy_disk_segments( tli: &WalResidentTimeline, wal_seg_size: usize, start_lsn: Lsn, end_lsn: Lsn, tli_dir_path: &Utf8PathBuf, ) -> Result<()> { let mut wal_reader = tli.get_walreader(start_lsn).await?; let mut buf = vec![0u8; MAX_SEND_SIZE]; let first_segment = start_lsn.segment_number(wal_seg_size); let last_segment = end_lsn.segment_number(wal_seg_size); for segment in first_segment..=last_segment { let segment_start = segment * wal_seg_size as u64; let segment_end = segment_start + wal_seg_size as u64; let copy_start = segment_start.max(start_lsn.0); let copy_end = segment_end.min(end_lsn.0); let copy_start = copy_start - segment_start; let copy_end = copy_end - segment_start; let wal_file_path = { let (normal, partial) = wal_file_paths(tli_dir_path, segment, wal_seg_size); if segment == last_segment { partial } else { normal } }; write_segment( &mut buf, &wal_file_path, wal_seg_size as u64, copy_start, copy_end, &mut wal_reader, ) .await?; } Ok(()) } async fn write_segment( buf: &mut [u8], file_path: &Utf8PathBuf, wal_seg_size: u64, from: u64, to: u64, reader: &mut WalReader, ) -> Result<()> { assert!(from <= to); assert!(to <= wal_seg_size); #[allow(clippy::suspicious_open_options)] let mut file = OpenOptions::new() .create(true) .write(true) .open(&file_path) .await?; // maybe fill with zeros, as in wal_storage.rs? file.set_len(wal_seg_size).await?; file.seek(std::io::SeekFrom::Start(from)).await?; let mut bytes_left = to - from; while bytes_left > 0 { let len = bytes_left as usize; let len = len.min(buf.len()); let len = reader.read(&mut buf[..len]).await?; file.write_all(&buf[..len]).await?; bytes_left -= len as u64; } file.flush().await?; file.sync_all().await?; Ok(()) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/control_file.rs
safekeeper/src/control_file.rs
//! Control file serialization, deserialization and persistence. use std::future::Future; use std::io::Read; use std::ops::Deref; use std::path::Path; use std::time::Instant; use anyhow::{Context, Result, bail, ensure}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use camino::{Utf8Path, Utf8PathBuf}; use safekeeper_api::membership::INVALID_GENERATION; use tokio::fs::File; use tokio::io::AsyncWriteExt; use utils::bin_ser::LeSer; use utils::crashsafe::durable_rename; use crate::control_file_upgrade::{downgrade_v10_to_v9, upgrade_control_file}; use crate::metrics::PERSIST_CONTROL_FILE_SECONDS; use crate::metrics::WAL_DISK_IO_ERRORS; use crate::state::{EvictionState, TimelinePersistentState}; pub const SK_MAGIC: u32 = 0xcafeceefu32; pub const SK_FORMAT_VERSION: u32 = 10; // contains persistent metadata for safekeeper pub const CONTROL_FILE_NAME: &str = "safekeeper.control"; // needed to atomically update the state using `rename` const CONTROL_FILE_NAME_PARTIAL: &str = "safekeeper.control.partial"; pub const CHECKSUM_SIZE: usize = size_of::<u32>(); /// Storage should keep actual state inside of it. It should implement Deref /// trait to access state fields and have persist method for updating that state. pub trait Storage: Deref<Target = TimelinePersistentState> { /// Persist safekeeper state on disk and update internal state. fn persist(&mut self, s: &TimelinePersistentState) -> impl Future<Output = Result<()>> + Send; /// Timestamp of last persist. fn last_persist_at(&self) -> Instant; } #[derive(Debug)] pub struct FileStorage { // save timeline dir to avoid reconstructing it every time timeline_dir: Utf8PathBuf, no_sync: bool, /// Last state persisted to disk. state: TimelinePersistentState, /// Not preserved across restarts. last_persist_at: Instant, } impl FileStorage { /// Initialize storage by loading state from disk. pub fn restore_new(timeline_dir: &Utf8Path, no_sync: bool) -> Result<FileStorage> { let state = Self::load_control_file_from_dir(timeline_dir)?; Ok(FileStorage { timeline_dir: timeline_dir.to_path_buf(), no_sync, state, last_persist_at: Instant::now(), }) } /// Create and reliably persist new control file at given location. /// /// Note: we normally call this in temp directory for atomic init, so /// interested in FileStorage as a result only in tests. pub async fn create_new( timeline_dir: &Utf8Path, state: TimelinePersistentState, no_sync: bool, ) -> Result<FileStorage> { // we don't support creating new timelines in offloaded state assert!(matches!(state.eviction_state, EvictionState::Present)); let mut store = FileStorage { timeline_dir: timeline_dir.to_path_buf(), no_sync, state: state.clone(), last_persist_at: Instant::now(), }; store.persist(&state).await?; Ok(store) } /// Check the magic/version in the on-disk data and deserialize it, if possible. fn deser_sk_state(buf: &mut &[u8]) -> Result<TimelinePersistentState> { // Read the version independent part let magic = ReadBytesExt::read_u32::<LittleEndian>(buf)?; if magic != SK_MAGIC { bail!( "bad control file magic: {:X}, expected {:X}", magic, SK_MAGIC ); } let version = ReadBytesExt::read_u32::<LittleEndian>(buf)?; if version == SK_FORMAT_VERSION { let res = TimelinePersistentState::des(buf)?; return Ok(res); } // try to upgrade upgrade_control_file(buf, version) } /// Load control file from given directory. fn load_control_file_from_dir(timeline_dir: &Utf8Path) -> Result<TimelinePersistentState> { let path = timeline_dir.join(CONTROL_FILE_NAME); Self::load_control_file(path) } /// Read in the control file. pub fn load_control_file<P: AsRef<Path>>( control_file_path: P, ) -> Result<TimelinePersistentState> { let mut control_file = std::fs::OpenOptions::new() .read(true) .write(true) .open(&control_file_path) .with_context(|| { format!( "failed to open control file at {}", control_file_path.as_ref().display(), ) })?; let mut buf = Vec::new(); control_file .read_to_end(&mut buf) .context("failed to read control file")?; let calculated_checksum = crc32c::crc32c(&buf[..buf.len() - CHECKSUM_SIZE]); let expected_checksum_bytes: &[u8; CHECKSUM_SIZE] = buf[buf.len() - CHECKSUM_SIZE..].try_into()?; let expected_checksum = u32::from_le_bytes(*expected_checksum_bytes); ensure!( calculated_checksum == expected_checksum, format!( "safekeeper control file checksum mismatch: expected {} got {}", expected_checksum, calculated_checksum ) ); let state = FileStorage::deser_sk_state(&mut &buf[..buf.len() - CHECKSUM_SIZE]) .with_context(|| { format!( "while reading control file {}", control_file_path.as_ref().display(), ) })?; Ok(state) } } impl Deref for FileStorage { type Target = TimelinePersistentState; fn deref(&self) -> &Self::Target { &self.state } } impl TimelinePersistentState { pub(crate) fn write_to_buf(&self) -> Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(); WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_MAGIC)?; if self.mconf.generation == INVALID_GENERATION { // Temp hack for forward compatibility test: in case of none // configuration save cfile in previous v9 format. const PREV_FORMAT_VERSION: u32 = 9; let prev = downgrade_v10_to_v9(self); WriteBytesExt::write_u32::<LittleEndian>(&mut buf, PREV_FORMAT_VERSION)?; prev.ser_into(&mut buf)?; } else { // otherwise, we write the current format version WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_FORMAT_VERSION)?; self.ser_into(&mut buf)?; } // calculate checksum before resize let checksum = crc32c::crc32c(&buf); buf.extend_from_slice(&checksum.to_le_bytes()); Ok(buf) } } impl Storage for FileStorage { /// Persists state durably to the underlying storage. async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> { // start timer for metrics let _timer = PERSIST_CONTROL_FILE_SECONDS.start_timer(); // write data to safekeeper.control.partial let control_partial_path = self.timeline_dir.join(CONTROL_FILE_NAME_PARTIAL); let mut control_partial = File::create(&control_partial_path).await.with_context(|| { /* BEGIN_HADRON */ WAL_DISK_IO_ERRORS.inc(); /*END_HADRON */ format!( "failed to create partial control file at: {}", &control_partial_path ) })?; let buf: Vec<u8> = s.write_to_buf()?; control_partial.write_all(&buf).await.with_context(|| { /* BEGIN_HADRON */ WAL_DISK_IO_ERRORS.inc(); /*END_HADRON */ format!("failed to write safekeeper state into control file at: {control_partial_path}") })?; control_partial.flush().await.with_context(|| { /* BEGIN_HADRON */ WAL_DISK_IO_ERRORS.inc(); /*END_HADRON */ format!("failed to flush safekeeper state into control file at: {control_partial_path}") })?; let control_path = self.timeline_dir.join(CONTROL_FILE_NAME); durable_rename(&control_partial_path, &control_path, !self.no_sync) .await /* BEGIN_HADRON */ .inspect_err(|_| WAL_DISK_IO_ERRORS.inc())?; /* END_HADRON */ // update internal state self.state = s.clone(); Ok(()) } fn last_persist_at(&self) -> Instant { self.last_persist_at } } #[cfg(test)] mod test { use safekeeper_api::membership::{Configuration, MemberSet, SafekeeperGeneration}; use tokio::fs; use utils::lsn::Lsn; use super::*; const NO_SYNC: bool = true; #[tokio::test] async fn test_read_write_safekeeper_state() -> anyhow::Result<()> { let tempdir = camino_tempfile::tempdir()?; let mut state = TimelinePersistentState::empty(); state.mconf = Configuration { generation: SafekeeperGeneration::new(42), members: MemberSet::empty(), new_members: None, }; let mut storage = FileStorage::create_new(tempdir.path(), state.clone(), NO_SYNC).await?; // Make a change. state.commit_lsn = Lsn(42); storage.persist(&state).await?; // Reload the state. It should match the previously persisted state. let loaded_state = FileStorage::load_control_file_from_dir(tempdir.path())?; assert_eq!(loaded_state, state); Ok(()) } #[tokio::test] async fn test_safekeeper_state_checksum_mismatch() -> anyhow::Result<()> { let tempdir = camino_tempfile::tempdir()?; let mut state = TimelinePersistentState::empty(); let mut storage = FileStorage::create_new(tempdir.path(), state.clone(), NO_SYNC).await?; // Make a change. state.commit_lsn = Lsn(42); storage.persist(&state).await?; // Change the first byte to fail checksum validation. let ctrl_path = tempdir.path().join(CONTROL_FILE_NAME); let mut data = fs::read(&ctrl_path).await?; data[0] += 1; fs::write(&ctrl_path, &data).await?; // Loading the file should fail checksum validation. if let Err(err) = FileStorage::load_control_file_from_dir(tempdir.path()) { assert!(err.to_string().contains("control file checksum mismatch")) } else { panic!("expected checksum error") } Ok(()) } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/wal_backup.rs
safekeeper/src/wal_backup.rs
use std::cmp::min; use std::collections::HashSet; use std::num::NonZeroU32; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result}; use camino::{Utf8Path, Utf8PathBuf}; use futures::StreamExt; use futures::stream::{self, FuturesOrdered}; use postgres_ffi::v14::xlog_utils::XLogSegNoOffsetToRecPtr; use postgres_ffi::{PG_TLI, XLogFileName, XLogSegNo}; use remote_storage::{ DownloadError, DownloadOpts, GenericRemoteStorage, ListingMode, RemotePath, StorageMetadata, }; use safekeeper_api::models::PeerInfo; use tokio::fs::File; use tokio::select; use tokio::sync::mpsc::{self, Receiver, Sender}; use tokio::sync::watch; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use tracing::*; use utils::id::{NodeId, TenantTimelineId}; use utils::lsn::Lsn; use utils::{backoff, pausable_failpoint}; use crate::metrics::{ BACKED_UP_SEGMENTS, BACKUP_ERRORS, BACKUP_REELECT_LEADER_COUNT, WAL_BACKUP_TASKS, }; use crate::timeline::WalResidentTimeline; use crate::timeline_manager::{Manager, StateSnapshot}; use crate::{SafeKeeperConf, WAL_BACKUP_RUNTIME}; const UPLOAD_FAILURE_RETRY_MIN_MS: u64 = 10; const UPLOAD_FAILURE_RETRY_MAX_MS: u64 = 5000; /// Default buffer size when interfacing with [`tokio::fs::File`]. const BUFFER_SIZE: usize = 32 * 1024; pub struct WalBackupTaskHandle { shutdown_tx: Sender<()>, handle: JoinHandle<()>, } impl WalBackupTaskHandle { pub(crate) async fn join(self) { if let Err(e) = self.handle.await { error!("WAL backup task panicked: {}", e); } } } /// Do we have anything to upload to S3, i.e. should safekeepers run backup activity? pub(crate) fn is_wal_backup_required( wal_seg_size: usize, num_computes: usize, state: &StateSnapshot, ) -> bool { num_computes > 0 || // Currently only the whole segment is offloaded, so compare segment numbers. (state.commit_lsn.segment_number(wal_seg_size) > state.backup_lsn.segment_number(wal_seg_size)) } /// Based on peer information determine which safekeeper should offload; if it /// is me, run (per timeline) task, if not yet. OTOH, if it is not me and task /// is running, kill it. pub(crate) async fn update_task( mgr: &mut Manager, storage: Arc<GenericRemoteStorage>, need_backup: bool, state: &StateSnapshot, ) { /* BEGIN_HADRON */ let (offloader, election_dbg_str) = hadron_determine_offloader(mgr, state); /* END_HADRON */ let elected_me = Some(mgr.conf.my_id) == offloader; let should_task_run = need_backup && elected_me; // start or stop the task if should_task_run != (mgr.backup_task.is_some()) { if should_task_run { info!("elected for backup: {}", election_dbg_str); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); let Ok(resident) = mgr.wal_resident_timeline() else { info!("Timeline shut down"); return; }; let async_task = backup_task_main( resident, storage, mgr.conf.backup_parallel_jobs, shutdown_rx, ); let handle = if mgr.conf.current_thread_runtime { tokio::spawn(async_task) } else { WAL_BACKUP_RUNTIME.spawn(async_task) }; mgr.backup_task = Some(WalBackupTaskHandle { shutdown_tx, handle, }); } else { if !need_backup { // don't need backup at all info!("stepping down from backup, need_backup={}", need_backup); } else { // someone else has been elected info!("stepping down from backup: {}", election_dbg_str); } shut_down_task(&mut mgr.backup_task).await; } } } async fn shut_down_task(entry: &mut Option<WalBackupTaskHandle>) { if let Some(wb_handle) = entry.take() { // Tell the task to shutdown. Error means task exited earlier, that's ok. let _ = wb_handle.shutdown_tx.send(()).await; // Await the task itself. TODO: restart panicked tasks earlier. wb_handle.join().await; } } /* BEGIN_HADRON */ // On top of the neon determine_offloader, we also check if the current offloader is lagging behind too much. // If it is, we re-elect a new offloader. This mitigates the below issue. It also helps distribute the load across SKs. // // We observe that the offloader fails to upload a segment due to race conditions on XLOG SWITCH and PG start streaming WALs. // wal_backup task continously failing to upload a full segment while the segment remains partial on the disk. // The consequence is that commit_lsn for all SKs move forward but backup_lsn stays the same. Then, all SKs run out of disk space. // See go/sk-ood-xlog-switch for more details. // // To mitigate this issue, we will re-elect a new offloader if the current offloader is lagging behind too much. // Each SK makes the decision locally but they are aware of each other's commit and backup lsns. // // determine_offloader will pick a SK. say SK-1. // Each SK checks // -- if commit_lsn - back_lsn > threshold, // -- -- remove SK-1 from the candidate and call determine_offloader again. // SK-1 will step down and all SKs will elect the same leader again. // After the backup is caught up, the leader will become SK-1 again. fn hadron_determine_offloader(mgr: &Manager, state: &StateSnapshot) -> (Option<NodeId>, String) { let mut offloader: Option<NodeId>; let mut election_dbg_str: String; let caughtup_peers_count: usize; (offloader, election_dbg_str, caughtup_peers_count) = determine_offloader(&state.peers, state.backup_lsn, mgr.tli.ttid, &mgr.conf); if offloader.is_none() || caughtup_peers_count <= 1 || mgr.conf.max_reelect_offloader_lag_bytes == 0 { return (offloader, election_dbg_str); } let offloader_sk_id = offloader.unwrap(); let backup_lag = state.commit_lsn.checked_sub(state.backup_lsn); if backup_lag.is_none() { debug!("Backup lag is None. Skipping re-election."); return (offloader, election_dbg_str); } let backup_lag = backup_lag.unwrap().0; if backup_lag < mgr.conf.max_reelect_offloader_lag_bytes { return (offloader, election_dbg_str); } info!( "Electing a new leader: Backup lag is too high backup lsn lag {} threshold {}: {}", backup_lag, mgr.conf.max_reelect_offloader_lag_bytes, election_dbg_str ); BACKUP_REELECT_LEADER_COUNT.inc(); // Remove the current offloader if lag is too high. let new_peers: Vec<_> = state .peers .iter() .filter(|p| p.sk_id != offloader_sk_id) .cloned() .collect(); (offloader, election_dbg_str, _) = determine_offloader(&new_peers, state.backup_lsn, mgr.tli.ttid, &mgr.conf); (offloader, election_dbg_str) } /* END_HADRON */ /// The goal is to ensure that normally only one safekeepers offloads. However, /// it is fine (and inevitable, as s3 doesn't provide CAS) that for some short /// time we have several ones as they PUT the same files. Also, /// - frequently changing the offloader would be bad; /// - electing seriously lagging safekeeper is undesirable; /// /// So we deterministically choose among the reasonably caught up candidates. /// TODO: take into account failed attempts to deal with hypothetical situation /// where s3 is unreachable only for some sks. fn determine_offloader( alive_peers: &[PeerInfo], wal_backup_lsn: Lsn, ttid: TenantTimelineId, conf: &SafeKeeperConf, ) -> (Option<NodeId>, String, usize) { // TODO: remove this once we fill newly joined safekeepers since backup_lsn. let capable_peers = alive_peers .iter() .filter(|p| p.local_start_lsn <= wal_backup_lsn); match capable_peers.clone().map(|p| p.commit_lsn).max() { None => (None, "no connected peers to elect from".to_string(), 0), Some(max_commit_lsn) => { let threshold = max_commit_lsn .checked_sub(conf.max_offloader_lag_bytes) .unwrap_or(Lsn(0)); let mut caughtup_peers = capable_peers .clone() .filter(|p| p.commit_lsn >= threshold) .collect::<Vec<_>>(); caughtup_peers.sort_by(|p1, p2| p1.sk_id.cmp(&p2.sk_id)); // To distribute the load, shift by timeline_id. let offloader = caughtup_peers [(u128::from(ttid.timeline_id) % caughtup_peers.len() as u128) as usize] .sk_id; let mut capable_peers_dbg = capable_peers .map(|p| (p.sk_id, p.commit_lsn)) .collect::<Vec<_>>(); capable_peers_dbg.sort_by(|p1, p2| p1.0.cmp(&p2.0)); ( Some(offloader), format!( "elected {} among {:?} peers, with {} of them being caughtup", offloader, capable_peers_dbg, caughtup_peers.len() ), caughtup_peers.len(), ) } } } pub struct WalBackup { storage: Option<Arc<GenericRemoteStorage>>, } impl WalBackup { /// Create a new WalBackup instance. pub async fn new(conf: &SafeKeeperConf) -> Result<Self> { if !conf.wal_backup_enabled { return Ok(Self { storage: None }); } match conf.remote_storage.as_ref() { Some(config) => { let storage = GenericRemoteStorage::from_config(config).await?; Ok(Self { storage: Some(Arc::new(storage)), }) } None => Ok(Self { storage: None }), } } pub fn get_storage(&self) -> Option<Arc<GenericRemoteStorage>> { self.storage.clone() } } struct WalBackupTask { timeline: WalResidentTimeline, timeline_dir: Utf8PathBuf, wal_seg_size: usize, parallel_jobs: usize, commit_lsn_watch_rx: watch::Receiver<Lsn>, storage: Arc<GenericRemoteStorage>, } /// Offload single timeline. #[instrument(name = "wal_backup", skip_all, fields(ttid = %tli.ttid))] async fn backup_task_main( tli: WalResidentTimeline, storage: Arc<GenericRemoteStorage>, parallel_jobs: usize, mut shutdown_rx: Receiver<()>, ) { let _guard = WAL_BACKUP_TASKS.guard(); info!("started"); let cancel = tli.tli.cancel.clone(); let mut wb = WalBackupTask { wal_seg_size: tli.get_wal_seg_size().await, commit_lsn_watch_rx: tli.get_commit_lsn_watch_rx(), timeline_dir: tli.get_timeline_dir(), timeline: tli, parallel_jobs, storage, }; // task is spinned up only when wal_seg_size already initialized assert!(wb.wal_seg_size > 0); let mut canceled = false; select! { _ = wb.run() => {} _ = shutdown_rx.recv() => { canceled = true; }, _ = cancel.cancelled() => { canceled = true; } } info!("task {}", if canceled { "canceled" } else { "terminated" }); } impl WalBackupTask { /// This function must be called from a select! that also respects self.timeline's /// cancellation token. This is done in [`backup_task_main`]. /// /// The future returned by this function is safe to drop at any time because it /// does not write to local disk. async fn run(&mut self) { let mut backup_lsn = Lsn(0); let mut retry_attempt = 0u32; // offload loop while !self.timeline.cancel.is_cancelled() { if retry_attempt == 0 { // wait for new WAL to arrive if let Err(e) = self.commit_lsn_watch_rx.changed().await { // should never happen, as we hold Arc to timeline and transmitter's lifetime // is within Timeline's error!("commit_lsn watch shut down: {:?}", e); return; }; } else { // or just sleep if we errored previously let mut retry_delay = UPLOAD_FAILURE_RETRY_MAX_MS; if let Some(backoff_delay) = UPLOAD_FAILURE_RETRY_MIN_MS.checked_shl(retry_attempt) { retry_delay = min(retry_delay, backoff_delay); } tokio::time::sleep(Duration::from_millis(retry_delay)).await; } let commit_lsn = *self.commit_lsn_watch_rx.borrow(); // Note that backup_lsn can be higher than commit_lsn if we // don't have much local WAL and others already uploaded // segments we don't even have. if backup_lsn.segment_number(self.wal_seg_size) >= commit_lsn.segment_number(self.wal_seg_size) { retry_attempt = 0; continue; /* nothing to do, common case as we wake up on every commit_lsn bump */ } // Perhaps peers advanced the position, check shmem value. backup_lsn = self.timeline.get_wal_backup_lsn().await; if backup_lsn.segment_number(self.wal_seg_size) >= commit_lsn.segment_number(self.wal_seg_size) { retry_attempt = 0; continue; } match backup_lsn_range( &self.timeline, self.storage.clone(), &mut backup_lsn, commit_lsn, self.wal_seg_size, &self.timeline_dir, self.parallel_jobs, ) .await { Ok(()) => { retry_attempt = 0; } Err(e) => { // We might have managed to upload some segment even though // some later in the range failed, so log backup_lsn // separately. error!( "failed while offloading range {}-{}, backup_lsn {}: {:?}", backup_lsn, commit_lsn, backup_lsn, e ); retry_attempt = retry_attempt.saturating_add(1); } } } } } async fn backup_lsn_range( timeline: &WalResidentTimeline, storage: Arc<GenericRemoteStorage>, backup_lsn: &mut Lsn, end_lsn: Lsn, wal_seg_size: usize, timeline_dir: &Utf8Path, parallel_jobs: usize, ) -> Result<()> { if parallel_jobs < 1 { anyhow::bail!("parallel_jobs must be >= 1"); } pausable_failpoint!("backup-lsn-range-pausable"); let remote_timeline_path = &timeline.remote_path; let start_lsn = *backup_lsn; let segments = get_segments(start_lsn, end_lsn, wal_seg_size); info!( "offloading segnos {:?} of range [{}-{})", segments.iter().map(|&s| s.seg_no).collect::<Vec<_>>(), start_lsn, end_lsn, ); // Pool of concurrent upload tasks. We use `FuturesOrdered` to // preserve order of uploads, and update `backup_lsn` only after // all previous uploads are finished. let mut uploads = FuturesOrdered::new(); let mut iter = segments.iter(); loop { let added_task = match iter.next() { Some(s) => { uploads.push_back(backup_single_segment( &storage, s, timeline_dir, remote_timeline_path, )); true } None => false, }; // Wait for the next segment to upload if we don't have any more segments, // or if we have too many concurrent uploads. if !added_task || uploads.len() >= parallel_jobs { let next = uploads.next().await; if let Some(res) = next { // next segment uploaded let segment = res?; let new_backup_lsn = segment.end_lsn; timeline .set_wal_backup_lsn(new_backup_lsn) .await .context("setting wal_backup_lsn")?; *backup_lsn = new_backup_lsn; } else { // no more segments to upload break; } } } info!( "offloaded segnos {:?} of range [{}-{})", segments.iter().map(|&s| s.seg_no).collect::<Vec<_>>(), start_lsn, end_lsn, ); Ok(()) } async fn backup_single_segment( storage: &GenericRemoteStorage, seg: &Segment, timeline_dir: &Utf8Path, remote_timeline_path: &RemotePath, ) -> Result<Segment> { let segment_file_path = seg.file_path(timeline_dir)?; let remote_segment_path = seg.remote_path(remote_timeline_path); let res = backup_object( storage, &segment_file_path, &remote_segment_path, seg.size(), ) .await; if res.is_ok() { BACKED_UP_SEGMENTS.inc(); } else { BACKUP_ERRORS.inc(); } res?; debug!("Backup of {} done", segment_file_path); Ok(*seg) } #[derive(Debug, Copy, Clone)] pub struct Segment { seg_no: XLogSegNo, start_lsn: Lsn, end_lsn: Lsn, } impl Segment { pub fn new(seg_no: u64, start_lsn: Lsn, end_lsn: Lsn) -> Self { Self { seg_no, start_lsn, end_lsn, } } pub fn object_name(self) -> String { XLogFileName(PG_TLI, self.seg_no, self.size()) } pub fn file_path(self, timeline_dir: &Utf8Path) -> Result<Utf8PathBuf> { Ok(timeline_dir.join(self.object_name())) } pub fn remote_path(self, remote_timeline_path: &RemotePath) -> RemotePath { remote_timeline_path.join(self.object_name()) } pub fn size(self) -> usize { (u64::from(self.end_lsn) - u64::from(self.start_lsn)) as usize } } fn get_segments(start: Lsn, end: Lsn, seg_size: usize) -> Vec<Segment> { let first_seg = start.segment_number(seg_size); let last_seg = end.segment_number(seg_size); let res: Vec<Segment> = (first_seg..last_seg) .map(|s| { let start_lsn = XLogSegNoOffsetToRecPtr(s, 0, seg_size); let end_lsn = XLogSegNoOffsetToRecPtr(s + 1, 0, seg_size); Segment::new(s, Lsn::from(start_lsn), Lsn::from(end_lsn)) }) .collect(); res } async fn backup_object( storage: &GenericRemoteStorage, source_file: &Utf8Path, target_file: &RemotePath, size: usize, ) -> Result<()> { let file = File::open(&source_file) .await .with_context(|| format!("Failed to open file {source_file:?} for wal backup"))?; let file = tokio_util::io::ReaderStream::with_capacity(file, BUFFER_SIZE); let cancel = CancellationToken::new(); storage .upload_storage_object(file, size, target_file, &cancel) .await } pub(crate) async fn backup_partial_segment( storage: &GenericRemoteStorage, source_file: &Utf8Path, target_file: &RemotePath, size: usize, ) -> Result<()> { let file = File::open(&source_file) .await .with_context(|| format!("Failed to open file {source_file:?} for wal backup"))?; // limiting the file to read only the first `size` bytes let limited_file = tokio::io::AsyncReadExt::take(file, size as u64); let file = tokio_util::io::ReaderStream::with_capacity(limited_file, BUFFER_SIZE); let cancel = CancellationToken::new(); storage .upload( file, size, target_file, Some(StorageMetadata::from([("sk_type", "partial_segment")])), &cancel, ) .await } pub(crate) async fn copy_partial_segment( storage: &GenericRemoteStorage, source: &RemotePath, destination: &RemotePath, ) -> Result<()> { let cancel = CancellationToken::new(); storage.copy_object(source, destination, &cancel).await } const WAL_READ_WARN_THRESHOLD: u32 = 2; const WAL_READ_MAX_RETRIES: u32 = 3; pub async fn read_object( storage: &GenericRemoteStorage, file_path: &RemotePath, offset: u64, ) -> anyhow::Result<Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>> { info!("segment download about to start from remote path {file_path:?} at offset {offset}"); let cancel = CancellationToken::new(); let opts = DownloadOpts { byte_start: std::ops::Bound::Included(offset), ..Default::default() }; // This retry only solves the connect errors: subsequent reads can still fail as this function returns // a stream. let download = backoff::retry( || async { storage.download(file_path, &opts, &cancel).await }, DownloadError::is_permanent, WAL_READ_WARN_THRESHOLD, WAL_READ_MAX_RETRIES, "download WAL segment", &cancel, ) .await .ok_or_else(|| DownloadError::Cancelled) .and_then(|x| x) .with_context(|| { format!("Failed to open WAL segment download stream for remote path {file_path:?}") })?; let reader = tokio_util::io::StreamReader::new(download.download_stream); let reader = tokio::io::BufReader::with_capacity(BUFFER_SIZE, reader); Ok(Box::pin(reader)) } /// Delete WAL files for the given timeline. Remote storage must be configured /// when called. pub async fn delete_timeline( storage: &GenericRemoteStorage, ttid: &TenantTimelineId, ) -> Result<()> { let remote_path = remote_timeline_path(ttid)?; // see DEFAULT_MAX_KEYS_PER_LIST_RESPONSE // const Option unwrap is not stable, otherwise it would be const. let batch_size: NonZeroU32 = NonZeroU32::new(1000).unwrap(); // A backoff::retry is used here for two reasons: // - To provide a backoff rather than busy-polling the API on errors // - To absorb transient 429/503 conditions without hitting our error // logging path for issues deleting objects. // // Note: listing segments might take a long time if there are many of them. // We don't currently have http requests timeout cancellation, but if/once // we have listing should get streaming interface to make progress. pausable_failpoint!("sk-delete-timeline-remote-pause"); fail::fail_point!("sk-delete-timeline-remote", |_| { Err(anyhow::anyhow!("failpoint: sk-delete-timeline-remote")) }); let cancel = CancellationToken::new(); // not really used backoff::retry( || async { // Do list-delete in batch_size batches to make progress even if there a lot of files. // Alternatively we could make remote storage list return iterator, but it is more complicated and // I'm not sure deleting while iterating is expected in s3. loop { let files = storage .list( Some(&remote_path), ListingMode::NoDelimiter, Some(batch_size), &cancel, ) .await? .keys .into_iter() .map(|o| o.key) .collect::<Vec<_>>(); if files.is_empty() { return Ok(()); // done } // (at least) s3 results are sorted, so can log min/max: // "List results are always returned in UTF-8 binary order." info!( "deleting batch of {} WAL segments [{}-{}]", files.len(), files.first().unwrap().object_name().unwrap_or(""), files.last().unwrap().object_name().unwrap_or("") ); storage.delete_objects(&files, &cancel).await?; } }, // consider TimeoutOrCancel::caused_by_cancel when using cancellation |_| false, 3, 10, "executing WAL segments deletion batch", &cancel, ) .await .ok_or_else(|| anyhow::anyhow!("canceled")) .and_then(|x| x)?; Ok(()) } /// Used by wal_backup_partial. pub async fn delete_objects(storage: &GenericRemoteStorage, paths: &[RemotePath]) -> Result<()> { let cancel = CancellationToken::new(); // not really used storage.delete_objects(paths, &cancel).await } /// Copy segments from one timeline to another. Used in copy_timeline. pub async fn copy_s3_segments( storage: &GenericRemoteStorage, wal_seg_size: usize, src_ttid: &TenantTimelineId, dst_ttid: &TenantTimelineId, from_segment: XLogSegNo, to_segment: XLogSegNo, ) -> Result<()> { let remote_dst_path = remote_timeline_path(dst_ttid)?; let cancel = CancellationToken::new(); let files = storage .list( Some(&remote_dst_path), ListingMode::NoDelimiter, None, &cancel, ) .await? .keys; let uploaded_segments = &files .iter() .filter_map(|o| o.key.object_name().map(ToOwned::to_owned)) .collect::<HashSet<_>>(); info!( "these segments have already been uploaded: {:?}", uploaded_segments ); /* BEGIN_HADRON */ // Copying multiple segments async. let mut copy_stream = stream::iter(from_segment..to_segment) .map(|segno| { let segment_name = XLogFileName(PG_TLI, segno, wal_seg_size); let remote_dst_path = remote_dst_path.clone(); let cancel = cancel.clone(); async move { if uploaded_segments.contains(&segment_name) { return Ok(()); } if segno % 1000 == 0 { info!("copying segment {} {}", segno, segment_name); } let from = remote_timeline_path(src_ttid)?.join(&segment_name); let to = remote_dst_path.join(&segment_name); // Retry logic: retry up to 10 times with 1 second delay let mut retry_count = 0; const MAX_RETRIES: u32 = 10; loop { match storage.copy_object(&from, &to, &cancel).await { Ok(()) => return Ok(()), Err(e) => { if cancel.is_cancelled() { // Don't retry if cancellation was requested return Err(e); } retry_count += 1; if retry_count >= MAX_RETRIES { error!( "Failed to copy segment {} after {} retries: {}", segment_name, MAX_RETRIES, e ); return Err(e); } warn!( "Failed to copy segment {} (attempt {}/{}): {}, retrying...", segment_name, retry_count, MAX_RETRIES, e ); tokio::time::sleep(Duration::from_secs(1)).await; } } } } }) .buffer_unordered(32); // Limit to 32 concurrent uploads // Process results, stopping on first error while let Some(result) = copy_stream.next().await { result?; } /* END_HADRON */ info!( "finished copying segments from {} until {}", from_segment, to_segment ); Ok(()) } /// Get S3 (remote_storage) prefix path used for timeline files. pub fn remote_timeline_path(ttid: &TenantTimelineId) -> Result<RemotePath> { RemotePath::new(&Utf8Path::new(&ttid.tenant_id.to_string()).join(ttid.timeline_id.to_string())) }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/auth.rs
safekeeper/src/auth.rs
use utils::auth::{AuthError, Claims, Scope}; use utils::id::TenantId; /// If tenant_id is provided, allow if token (claims) is for this tenant or /// whole safekeeper scope (SafekeeperData). Else, allow only if token is /// SafekeeperData. pub fn check_permission(claims: &Claims, tenant_id: Option<TenantId>) -> Result<(), AuthError> { match (&claims.scope, tenant_id) { (Scope::Tenant, None) => Err(AuthError( "Attempt to access management api with tenant scope. Permission denied".into(), )), (Scope::Tenant, Some(tenant_id)) => { if claims.tenant_id.unwrap() != tenant_id { return Err(AuthError("Tenant id mismatch. Permission denied".into())); } Ok(()) } ( Scope::Admin | Scope::PageServerApi | Scope::GenerationsApi | Scope::Infra | Scope::Scrubber | Scope::ControllerPeer | Scope::TenantEndpoint, _, ) => Err(AuthError( format!( "JWT scope '{:?}' is ineligible for Safekeeper auth", claims.scope ) .into(), )), (Scope::SafekeeperData, _) => Ok(()), } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/timeline.rs
safekeeper/src/timeline.rs
//! This module implements Timeline lifecycle management and has all necessary code //! to glue together SafeKeeper and all other background services. use std::cmp::max; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::Duration; use anyhow::{Result, anyhow, bail}; use camino::{Utf8Path, Utf8PathBuf}; use http_utils::error::ApiError; use remote_storage::RemotePath; use safekeeper_api::Term; use safekeeper_api::membership::Configuration; use safekeeper_api::models::{ PeerInfo, TimelineMembershipSwitchResponse, TimelineTermBumpResponse, }; use storage_broker::proto::{SafekeeperTimelineInfo, TenantTimelineId as ProtoTenantTimelineId}; use tokio::fs::{self}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, watch}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; use tracing::*; use utils::id::{NodeId, TenantId, TenantTimelineId}; use utils::lsn::Lsn; use utils::sync::gate::Gate; use crate::metrics::{ FullTimelineInfo, MISC_OPERATION_SECONDS, WAL_STORAGE_LIMIT_ERRORS, WalStorageMetrics, }; use crate::hadron::GLOBAL_DISK_LIMIT_EXCEEDED; use crate::rate_limit::RateLimiter; use crate::receive_wal::WalReceivers; use crate::safekeeper::{AcceptorProposerMessage, ProposerAcceptorMessage, SafeKeeper, TermLsn}; use crate::send_wal::{WalSenders, WalSendersTimelineMetricValues}; use crate::state::{EvictionState, TimelineMemState, TimelinePersistentState, TimelineState}; use crate::timeline_guard::ResidenceGuard; use crate::timeline_manager::{AtomicStatus, ManagerCtl}; use crate::timelines_set::TimelinesSet; use crate::wal_backup; use crate::wal_backup::{WalBackup, remote_timeline_path}; use crate::wal_backup_partial::PartialRemoteSegment; use crate::wal_storage::{Storage as wal_storage_iface, WalReader}; use crate::{SafeKeeperConf, control_file, debug_dump, timeline_manager, wal_storage}; fn peer_info_from_sk_info(sk_info: &SafekeeperTimelineInfo, ts: Instant) -> PeerInfo { PeerInfo { sk_id: NodeId(sk_info.safekeeper_id), term: sk_info.term, last_log_term: sk_info.last_log_term, flush_lsn: Lsn(sk_info.flush_lsn), commit_lsn: Lsn(sk_info.commit_lsn), local_start_lsn: Lsn(sk_info.local_start_lsn), pg_connstr: sk_info.safekeeper_connstr.clone(), http_connstr: sk_info.http_connstr.clone(), https_connstr: sk_info.https_connstr.clone(), ts, } } // vector-based node id -> peer state map with very limited functionality we // need. #[derive(Debug, Clone, Default)] pub struct PeersInfo(pub Vec<PeerInfo>); impl PeersInfo { fn get(&mut self, id: NodeId) -> Option<&mut PeerInfo> { self.0.iter_mut().find(|p| p.sk_id == id) } fn upsert(&mut self, p: &PeerInfo) { match self.get(p.sk_id) { Some(rp) => *rp = p.clone(), None => self.0.push(p.clone()), } } } pub type ReadGuardSharedState<'a> = RwLockReadGuard<'a, SharedState>; /// WriteGuardSharedState is a wrapper around `RwLockWriteGuard<SharedState>` that /// automatically updates `watch::Sender` channels with state on drop. pub struct WriteGuardSharedState<'a> { tli: Arc<Timeline>, guard: RwLockWriteGuard<'a, SharedState>, } impl<'a> WriteGuardSharedState<'a> { fn new(tli: Arc<Timeline>, guard: RwLockWriteGuard<'a, SharedState>) -> Self { WriteGuardSharedState { tli, guard } } } impl Deref for WriteGuardSharedState<'_> { type Target = SharedState; fn deref(&self) -> &Self::Target { &self.guard } } impl DerefMut for WriteGuardSharedState<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.guard } } impl Drop for WriteGuardSharedState<'_> { fn drop(&mut self) { let term_flush_lsn = TermLsn::from((self.guard.sk.last_log_term(), self.guard.sk.flush_lsn())); let commit_lsn = self.guard.sk.state().inmem.commit_lsn; let _ = self.tli.term_flush_lsn_watch_tx.send_if_modified(|old| { if *old != term_flush_lsn { *old = term_flush_lsn; true } else { false } }); let _ = self.tli.commit_lsn_watch_tx.send_if_modified(|old| { if *old != commit_lsn { *old = commit_lsn; true } else { false } }); // send notification about shared state update self.tli.shared_state_version_tx.send_modify(|old| { *old += 1; }); } } /// This structure is stored in shared state and represents the state of the timeline. /// /// Usually it holds SafeKeeper, but it also supports offloaded timeline state. In this /// case, SafeKeeper is not available (because WAL is not present on disk) and all /// operations can be done only with control file. #[allow(clippy::large_enum_variant, reason = "TODO")] pub enum StateSK { Loaded(SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>), Offloaded(Box<TimelineState<control_file::FileStorage>>), // Not used, required for moving between states. Empty, } impl StateSK { pub fn flush_lsn(&self) -> Lsn { match self { StateSK::Loaded(sk) => sk.wal_store.flush_lsn(), StateSK::Offloaded(state) => match state.eviction_state { EvictionState::Offloaded(flush_lsn) => flush_lsn, _ => panic!("StateSK::Offloaded mismatches with eviction_state from control_file"), }, StateSK::Empty => unreachable!(), } } /// Get a reference to the control file's timeline state. pub fn state(&self) -> &TimelineState<control_file::FileStorage> { match self { StateSK::Loaded(sk) => &sk.state, StateSK::Offloaded(s) => s, StateSK::Empty => unreachable!(), } } pub fn state_mut(&mut self) -> &mut TimelineState<control_file::FileStorage> { match self { StateSK::Loaded(sk) => &mut sk.state, StateSK::Offloaded(s) => s, StateSK::Empty => unreachable!(), } } pub fn last_log_term(&self) -> Term { self.state() .acceptor_state .get_last_log_term(self.flush_lsn()) } pub async fn term_bump(&mut self, to: Option<Term>) -> Result<TimelineTermBumpResponse> { self.state_mut().term_bump(to).await } pub async fn membership_switch( &mut self, to: Configuration, ) -> Result<TimelineMembershipSwitchResponse> { let result = self.state_mut().membership_switch(to).await?; let flush_lsn = self.flush_lsn(); let last_log_term = self.state().acceptor_state.get_last_log_term(flush_lsn); Ok(TimelineMembershipSwitchResponse { previous_conf: result.previous_conf, current_conf: result.current_conf, last_log_term, flush_lsn, }) } /// Close open WAL files to release FDs. fn close_wal_store(&mut self) { if let StateSK::Loaded(sk) = self { sk.wal_store.close(); } } /// Update timeline state with peer safekeeper data. pub async fn record_safekeeper_info(&mut self, sk_info: &SafekeeperTimelineInfo) -> Result<()> { // update commit_lsn if safekeeper is loaded match self { StateSK::Loaded(sk) => sk.record_safekeeper_info(sk_info).await?, StateSK::Offloaded(_) => {} StateSK::Empty => unreachable!(), } // update everything else, including remote_consistent_lsn and backup_lsn let mut sync_control_file = false; let state = self.state_mut(); let wal_seg_size = state.server.wal_seg_size as u64; state.inmem.backup_lsn = max(Lsn(sk_info.backup_lsn), state.inmem.backup_lsn); sync_control_file |= state.backup_lsn + wal_seg_size < state.inmem.backup_lsn; state.inmem.remote_consistent_lsn = max( Lsn(sk_info.remote_consistent_lsn), state.inmem.remote_consistent_lsn, ); sync_control_file |= state.remote_consistent_lsn + wal_seg_size < state.inmem.remote_consistent_lsn; state.inmem.peer_horizon_lsn = max(Lsn(sk_info.peer_horizon_lsn), state.inmem.peer_horizon_lsn); sync_control_file |= state.peer_horizon_lsn + wal_seg_size < state.inmem.peer_horizon_lsn; if sync_control_file { state.flush().await?; } Ok(()) } /// Previously known as epoch_start_lsn. Needed only for reference in some APIs. pub fn term_start_lsn(&self) -> Lsn { match self { StateSK::Loaded(sk) => sk.term_start_lsn, StateSK::Offloaded(_) => Lsn(0), StateSK::Empty => unreachable!(), } } /// Used for metrics only. pub fn wal_storage_metrics(&self) -> WalStorageMetrics { match self { StateSK::Loaded(sk) => sk.wal_store.get_metrics(), StateSK::Offloaded(_) => WalStorageMetrics::default(), StateSK::Empty => unreachable!(), } } /// Returns WAL storage internal LSNs for debug dump. pub fn wal_storage_internal_state(&self) -> (Lsn, Lsn, Lsn, bool) { match self { StateSK::Loaded(sk) => sk.wal_store.internal_state(), StateSK::Offloaded(_) => { let flush_lsn = self.flush_lsn(); (flush_lsn, flush_lsn, flush_lsn, false) } StateSK::Empty => unreachable!(), } } /// Access to SafeKeeper object. Panics if offloaded, should be good to use from WalResidentTimeline. pub fn safekeeper( &mut self, ) -> &mut SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage> { match self { StateSK::Loaded(sk) => sk, StateSK::Offloaded(_) => { panic!("safekeeper is offloaded, cannot be used") } StateSK::Empty => unreachable!(), } } /// Moves control file's state structure out of the enum. Used to switch states. fn take_state(self) -> TimelineState<control_file::FileStorage> { match self { StateSK::Loaded(sk) => sk.state, StateSK::Offloaded(state) => *state, StateSK::Empty => unreachable!(), } } } /// Shared state associated with database instance pub struct SharedState { /// Safekeeper object pub(crate) sk: StateSK, /// In memory list containing state of peers sent in latest messages from them. pub(crate) peers_info: PeersInfo, // True value hinders old WAL removal; this is used by snapshotting. We // could make it a counter, but there is no need to. pub(crate) wal_removal_on_hold: bool, } impl SharedState { /// Creates a new SharedState. pub fn new(sk: StateSK) -> Self { Self { sk, peers_info: PeersInfo(vec![]), wal_removal_on_hold: false, } } /// Restore SharedState from control file. If file doesn't exist, bails out. pub fn restore(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Result<Self> { let timeline_dir = get_timeline_dir(conf, ttid); let control_store = control_file::FileStorage::restore_new(&timeline_dir, conf.no_sync)?; if control_store.server.wal_seg_size == 0 { bail!(TimelineError::UninitializedWalSegSize(*ttid)); } let sk = match control_store.eviction_state { EvictionState::Present => { let wal_store = wal_storage::PhysicalStorage::new( ttid, &timeline_dir, &control_store, conf.no_sync, )?; StateSK::Loaded(SafeKeeper::new( TimelineState::new(control_store), wal_store, conf.my_id, )?) } EvictionState::Offloaded(_) => { StateSK::Offloaded(Box::new(TimelineState::new(control_store))) } }; Ok(Self::new(sk)) } pub(crate) fn get_wal_seg_size(&self) -> usize { self.sk.state().server.wal_seg_size as usize } fn get_safekeeper_info( &self, ttid: &TenantTimelineId, conf: &SafeKeeperConf, standby_apply_lsn: Lsn, ) -> SafekeeperTimelineInfo { SafekeeperTimelineInfo { safekeeper_id: conf.my_id.0, tenant_timeline_id: Some(ProtoTenantTimelineId { tenant_id: ttid.tenant_id.as_ref().to_owned(), timeline_id: ttid.timeline_id.as_ref().to_owned(), }), term: self.sk.state().acceptor_state.term, last_log_term: self.sk.last_log_term(), flush_lsn: self.sk.flush_lsn().0, // note: this value is not flushed to control file yet and can be lost commit_lsn: self.sk.state().inmem.commit_lsn.0, remote_consistent_lsn: self.sk.state().inmem.remote_consistent_lsn.0, peer_horizon_lsn: self.sk.state().inmem.peer_horizon_lsn.0, safekeeper_connstr: conf .advertise_pg_addr .to_owned() .unwrap_or(conf.listen_pg_addr.clone()), http_connstr: conf.listen_http_addr.to_owned(), https_connstr: conf.listen_https_addr.to_owned(), backup_lsn: self.sk.state().inmem.backup_lsn.0, local_start_lsn: self.sk.state().local_start_lsn.0, availability_zone: conf.availability_zone.clone(), standby_horizon: standby_apply_lsn.0, } } /// Get our latest view of alive peers status on the timeline. /// We pass our own info through the broker as well, so when we don't have connection /// to the broker returned vec is empty. pub(crate) fn get_peers(&self, heartbeat_timeout: Duration) -> Vec<PeerInfo> { let now = Instant::now(); self.peers_info .0 .iter() // Regard peer as absent if we haven't heard from it within heartbeat_timeout. .filter(|p| now.duration_since(p.ts) <= heartbeat_timeout) .cloned() .collect() } } #[derive(Debug, thiserror::Error)] pub enum TimelineError { #[error("Timeline {0} was cancelled and cannot be used anymore")] Cancelled(TenantTimelineId), #[error("Timeline {0} was not found in global map")] NotFound(TenantTimelineId), #[error("Timeline {0} has been deleted")] Deleted(TenantTimelineId), #[error("Timeline {0} creation is in progress")] CreationInProgress(TenantTimelineId), #[error("Timeline {0} exists on disk, but wasn't loaded on startup")] Invalid(TenantTimelineId), #[error("Timeline {0} is already exists")] AlreadyExists(TenantTimelineId), #[error("Timeline {0} is not initialized, wal_seg_size is zero")] UninitializedWalSegSize(TenantTimelineId), #[error("Timeline {0} is not initialized, pg_version is unknown")] UninitialinzedPgVersion(TenantTimelineId), } // Convert to HTTP API error. impl From<TimelineError> for ApiError { fn from(te: TimelineError) -> ApiError { match te { TimelineError::NotFound(ttid) => { ApiError::NotFound(anyhow!("timeline {} not found", ttid).into()) } TimelineError::Deleted(ttid) => { ApiError::NotFound(anyhow!("timeline {} deleted", ttid).into()) } _ => ApiError::InternalServerError(anyhow!("{}", te)), } } } /// We run remote deletion in a background task, this is how it sends its results back. type RemoteDeletionReceiver = tokio::sync::watch::Receiver<Option<anyhow::Result<()>>>; /// Timeline struct manages lifecycle (creation, deletion, restore) of a safekeeper timeline. /// It also holds SharedState and provides mutually exclusive access to it. pub struct Timeline { pub ttid: TenantTimelineId, pub remote_path: RemotePath, /// Used to broadcast commit_lsn updates to all background jobs. commit_lsn_watch_tx: watch::Sender<Lsn>, commit_lsn_watch_rx: watch::Receiver<Lsn>, /// Broadcasts (current term, flush_lsn) updates, walsender is interested in /// them when sending in recovery mode (to walproposer or peers). Note: this /// is just a notification, WAL reading should always done with lock held as /// term can change otherwise. term_flush_lsn_watch_tx: watch::Sender<TermLsn>, term_flush_lsn_watch_rx: watch::Receiver<TermLsn>, /// Broadcasts shared state updates. shared_state_version_tx: watch::Sender<usize>, shared_state_version_rx: watch::Receiver<usize>, /// Safekeeper and other state, that should remain consistent and /// synchronized with the disk. This is tokio mutex as we write WAL to disk /// while holding it, ensuring that consensus checks are in order. mutex: RwLock<SharedState>, walsenders: Arc<WalSenders>, walreceivers: Arc<WalReceivers>, timeline_dir: Utf8PathBuf, manager_ctl: ManagerCtl, conf: Arc<SafeKeeperConf>, pub(crate) wal_backup: Arc<WalBackup>, remote_deletion: std::sync::Mutex<Option<RemoteDeletionReceiver>>, /// Hold this gate from code that depends on the Timeline's non-shut-down state. While holding /// this gate, you must respect [`Timeline::cancel`] pub(crate) gate: Gate, /// Delete/cancel will trigger this, background tasks should drop out as soon as it fires pub(crate) cancel: CancellationToken, // timeline_manager controlled state pub(crate) broker_active: AtomicBool, pub(crate) wal_backup_active: AtomicBool, pub(crate) last_removed_segno: AtomicU64, pub(crate) mgr_status: AtomicStatus, } impl Timeline { /// Constructs a new timeline. pub fn new( ttid: TenantTimelineId, timeline_dir: &Utf8Path, remote_path: &RemotePath, shared_state: SharedState, conf: Arc<SafeKeeperConf>, wal_backup: Arc<WalBackup>, ) -> Arc<Self> { let (commit_lsn_watch_tx, commit_lsn_watch_rx) = watch::channel(shared_state.sk.state().commit_lsn); let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) = watch::channel(TermLsn::from(( shared_state.sk.last_log_term(), shared_state.sk.flush_lsn(), ))); let (shared_state_version_tx, shared_state_version_rx) = watch::channel(0); let walreceivers = WalReceivers::new(); Arc::new(Self { ttid, remote_path: remote_path.to_owned(), timeline_dir: timeline_dir.to_owned(), commit_lsn_watch_tx, commit_lsn_watch_rx, term_flush_lsn_watch_tx, term_flush_lsn_watch_rx, shared_state_version_tx, shared_state_version_rx, mutex: RwLock::new(shared_state), walsenders: WalSenders::new(walreceivers.clone()), walreceivers, gate: Default::default(), cancel: CancellationToken::default(), remote_deletion: std::sync::Mutex::new(None), manager_ctl: ManagerCtl::new(), conf, broker_active: AtomicBool::new(false), wal_backup_active: AtomicBool::new(false), last_removed_segno: AtomicU64::new(0), mgr_status: AtomicStatus::new(), wal_backup, }) } /// Load existing timeline from disk. pub fn load_timeline( conf: Arc<SafeKeeperConf>, ttid: TenantTimelineId, wal_backup: Arc<WalBackup>, ) -> Result<Arc<Timeline>> { let _enter = info_span!("load_timeline", timeline = %ttid.timeline_id).entered(); let shared_state = SharedState::restore(conf.as_ref(), &ttid)?; let timeline_dir = get_timeline_dir(conf.as_ref(), &ttid); let remote_path = remote_timeline_path(&ttid)?; Ok(Timeline::new( ttid, &timeline_dir, &remote_path, shared_state, conf, wal_backup, )) } /// Bootstrap new or existing timeline starting background tasks. pub fn bootstrap( self: &Arc<Timeline>, _shared_state: &mut WriteGuardSharedState<'_>, conf: &SafeKeeperConf, broker_active_set: Arc<TimelinesSet>, partial_backup_rate_limiter: RateLimiter, wal_backup: Arc<WalBackup>, ) { let (tx, rx) = self.manager_ctl.bootstrap_manager(); let Ok(gate_guard) = self.gate.enter() else { // Init raced with shutdown return; }; // Start manager task which will monitor timeline state and update // background tasks. tokio::spawn({ let this = self.clone(); let conf = conf.clone(); async move { let _gate_guard = gate_guard; timeline_manager::main_task( ManagerTimeline { tli: this }, conf, broker_active_set, tx, rx, partial_backup_rate_limiter, wal_backup, ) .await } }); } /// Cancel the timeline, requesting background activity to stop. Closing /// the `self.gate` waits for that. pub fn cancel(&self) { info!("timeline {} shutting down", self.ttid); self.cancel.cancel(); } /// Background timeline activities (which hold Timeline::gate) will no /// longer run once this function completes. `Self::cancel` must have been /// already called. pub async fn close(&self) { assert!(self.cancel.is_cancelled()); // Wait for any concurrent tasks to stop using this timeline, to avoid e.g. attempts // to read deleted files. self.gate.close().await; } /// Delete timeline from disk completely, by removing timeline directory. /// /// Also deletes WAL in s3. Might fail if e.g. s3 is unavailable, but /// deletion API endpoint is retriable. /// /// Timeline must be in shut-down state (i.e. call [`Self::close`] first) pub async fn delete( &self, shared_state: &mut WriteGuardSharedState<'_>, only_local: bool, ) -> Result<bool> { // Assert that [`Self::close`] was already called assert!(self.cancel.is_cancelled()); assert!(self.gate.close_complete()); info!("deleting timeline {} from disk", self.ttid); // Close associated FDs. Nobody will be able to touch timeline data once // it is cancelled, so WAL storage won't be opened again. shared_state.sk.close_wal_store(); if !only_local { self.remote_delete().await?; } let dir_existed = delete_dir(&self.timeline_dir).await?; Ok(dir_existed) } /// Delete timeline content from remote storage. If the returned future is dropped, /// deletion will continue in the background. /// /// This function ordinarily spawns a task and stashes a result receiver into [`Self::remote_deletion`]. If /// deletion is already happening, it may simply wait for an existing task's result. /// /// Note: we concurrently delete remote storage data from multiple /// safekeepers. That's ok, s3 replies 200 if object doesn't exist and we /// do some retries anyway. async fn remote_delete(&self) -> Result<()> { // We will start a background task to do the deletion, so that it proceeds even if our // API request is dropped. Future requests will see the existing deletion task and wait // for it to complete. let mut result_rx = { let mut remote_deletion_state = self.remote_deletion.lock().unwrap(); let result_rx = if let Some(result_rx) = remote_deletion_state.as_ref() { if let Some(result) = result_rx.borrow().as_ref() { if let Err(e) = result { // A previous remote deletion failed: we will start a new one tracing::error!("remote deletion failed, will retry ({e})"); None } else { // A previous remote deletion call already succeeded return Ok(()); } } else { // Remote deletion is still in flight Some(result_rx.clone()) } } else { // Remote deletion was not attempted yet, start it now. None }; match result_rx { Some(result_rx) => result_rx, None => self.start_remote_delete(&mut remote_deletion_state), } }; // Wait for a result let Ok(result) = result_rx.wait_for(|v| v.is_some()).await else { // Unexpected: sender should always send a result before dropping the channel, even if it has an error return Err(anyhow::anyhow!( "remote deletion task future was dropped without sending a result" )); }; result .as_ref() .expect("We did a wait_for on this being Some above") .as_ref() .map(|_| ()) .map_err(|e| anyhow::anyhow!("remote deletion failed: {e}")) } /// Spawn background task to do remote deletion, return a receiver for its outcome fn start_remote_delete( &self, guard: &mut std::sync::MutexGuard<Option<RemoteDeletionReceiver>>, ) -> RemoteDeletionReceiver { tracing::info!("starting remote deletion"); let storage = self.wal_backup.get_storage().clone(); let (result_tx, result_rx) = tokio::sync::watch::channel(None); let ttid = self.ttid; tokio::task::spawn( async move { let r = if let Some(storage) = storage { wal_backup::delete_timeline(&storage, &ttid).await } else { tracing::info!( "skipping remote deletion because no remote storage is configured; this effectively leaks the objects in remote storage" ); Ok(()) }; if let Err(e) = &r { // Log error here in case nobody ever listens for our result (e.g. dropped API request) tracing::error!("remote deletion failed: {e}"); } // Ignore send results: it's legal for the Timeline to give up waiting for us. let _ = result_tx.send(Some(r)); } .instrument(info_span!("remote_delete", timeline = %self.ttid)), ); **guard = Some(result_rx.clone()); result_rx } /// Returns if timeline is cancelled. pub fn is_cancelled(&self) -> bool { self.cancel.is_cancelled() } /// Take a writing mutual exclusive lock on timeline shared_state. pub async fn write_shared_state(self: &Arc<Self>) -> WriteGuardSharedState<'_> { WriteGuardSharedState::new(self.clone(), self.mutex.write().await) } pub async fn read_shared_state(&self) -> ReadGuardSharedState { self.mutex.read().await } /// Returns commit_lsn watch channel. pub fn get_commit_lsn_watch_rx(&self) -> watch::Receiver<Lsn> { self.commit_lsn_watch_rx.clone() } /// Returns term_flush_lsn watch channel. pub fn get_term_flush_lsn_watch_rx(&self) -> watch::Receiver<TermLsn> { self.term_flush_lsn_watch_rx.clone() } /// Returns watch channel for SharedState update version. pub fn get_state_version_rx(&self) -> watch::Receiver<usize> { self.shared_state_version_rx.clone() } /// Returns wal_seg_size. pub async fn get_wal_seg_size(&self) -> usize { self.read_shared_state().await.get_wal_seg_size() } /// Returns state of the timeline. pub async fn get_state(&self) -> (TimelineMemState, TimelinePersistentState) { let state = self.read_shared_state().await; ( state.sk.state().inmem.clone(), TimelinePersistentState::clone(state.sk.state()), ) } /// Returns latest backup_lsn. pub async fn get_wal_backup_lsn(&self) -> Lsn { self.read_shared_state().await.sk.state().inmem.backup_lsn } /// Sets backup_lsn to the given value. pub async fn set_wal_backup_lsn(self: &Arc<Self>, backup_lsn: Lsn) -> Result<()> { if self.is_cancelled() { bail!(TimelineError::Cancelled(self.ttid)); } let mut state = self.write_shared_state().await; state.sk.state_mut().inmem.backup_lsn = max(state.sk.state().inmem.backup_lsn, backup_lsn); // we should check whether to shut down offloader, but this will be done // soon by peer communication anyway. Ok(()) } /// Get safekeeper info for broadcasting to broker and other peers. pub async fn get_safekeeper_info(&self, conf: &SafeKeeperConf) -> SafekeeperTimelineInfo { let standby_apply_lsn = self.walsenders.get_hotstandby().reply.apply_lsn; let shared_state = self.read_shared_state().await; shared_state.get_safekeeper_info(&self.ttid, conf, standby_apply_lsn) } /// Update timeline state with peer safekeeper data. pub async fn record_safekeeper_info( self: &Arc<Self>, sk_info: SafekeeperTimelineInfo, ) -> Result<()> { { let mut shared_state = self.write_shared_state().await; shared_state.sk.record_safekeeper_info(&sk_info).await?; let peer_info = peer_info_from_sk_info(&sk_info, Instant::now()); shared_state.peers_info.upsert(&peer_info); } Ok(()) } pub async fn get_peers(&self, conf: &SafeKeeperConf) -> Vec<PeerInfo> { let shared_state = self.read_shared_state().await; shared_state.get_peers(conf.heartbeat_timeout) } pub fn get_walsenders(&self) -> &Arc<WalSenders> { &self.walsenders } pub fn get_walreceivers(&self) -> &Arc<WalReceivers> { &self.walreceivers } /// Returns flush_lsn. pub async fn get_flush_lsn(&self) -> Lsn { self.read_shared_state().await.sk.flush_lsn() } /// Gather timeline data for metrics. pub async fn info_for_metrics(&self) -> Option<FullTimelineInfo> { if self.is_cancelled() { return None; } let WalSendersTimelineMetricValues { ps_feedback_counter, ps_corruption_detected, last_ps_feedback, interpreted_wal_reader_tasks, } = self.walsenders.info_for_metrics(); let state = self.read_shared_state().await; Some(FullTimelineInfo { ttid: self.ttid, ps_feedback_count: ps_feedback_counter, ps_corruption_detected, last_ps_feedback, wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed), timeline_is_active: self.broker_active.load(Ordering::Relaxed), num_computes: self.walreceivers.get_num() as u32, last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed), interpreted_wal_reader_tasks, epoch_start_lsn: state.sk.term_start_lsn(), mem_state: state.sk.state().inmem.clone(), persisted_state: TimelinePersistentState::clone(state.sk.state()), flush_lsn: state.sk.flush_lsn(), wal_storage: state.sk.wal_storage_metrics(), }) } /// Returns in-memory timeline state to build a full debug dump. pub async fn memory_dump(&self) -> debug_dump::Memory { let state = self.read_shared_state().await; let (write_lsn, write_record_lsn, flush_lsn, file_open) = state.sk.wal_storage_internal_state(); debug_dump::Memory { is_cancelled: self.is_cancelled(), peers_info_len: state.peers_info.0.len(), walsenders: self.walsenders.get_all_public(), wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed), active: self.broker_active.load(Ordering::Relaxed), num_computes: self.walreceivers.get_num() as u32,
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/wal_reader_stream.rs
safekeeper/src/wal_reader_stream.rs
use std::pin::Pin; use std::task::{Context, Poll}; use crate::send_wal::EndWatch; use crate::timeline::WalResidentTimeline; use crate::wal_storage::WalReader; use bytes::Bytes; use futures::stream::BoxStream; use futures::{Stream, StreamExt}; use safekeeper_api::Term; use utils::id::TenantTimelineId; use utils::lsn::Lsn; #[derive(PartialEq, Eq, Debug)] pub(crate) struct WalBytes { /// Raw PG WAL pub(crate) wal: Bytes, /// Start LSN of [`Self::wal`] #[allow(dead_code)] pub(crate) wal_start_lsn: Lsn, /// End LSN of [`Self::wal`] pub(crate) wal_end_lsn: Lsn, /// End LSN of WAL available on the safekeeper. /// /// For pagservers this will be commit LSN, /// while for the compute it will be the flush LSN. pub(crate) available_wal_end_lsn: Lsn, } struct PositionedWalReader { start: Lsn, end: Lsn, reader: Option<WalReader>, } /// A streaming WAL reader wrapper which can be reset while running pub(crate) struct StreamingWalReader { stream: BoxStream<'static, WalOrReset>, start_changed_tx: tokio::sync::watch::Sender<Lsn>, // HADRON: Added TenantTimelineId for instrumentation purposes. pub(crate) ttid: TenantTimelineId, } pub(crate) enum WalOrReset { Wal(anyhow::Result<WalBytes>), Reset(Lsn), } impl WalOrReset { pub(crate) fn get_wal(self) -> Option<anyhow::Result<WalBytes>> { match self { WalOrReset::Wal(wal) => Some(wal), WalOrReset::Reset(_) => None, } } } impl StreamingWalReader { pub(crate) fn new( tli: WalResidentTimeline, term: Option<Term>, start: Lsn, end: Lsn, end_watch: EndWatch, buffer_size: usize, ) -> Self { let (start_changed_tx, start_changed_rx) = tokio::sync::watch::channel(start); let ttid = tli.ttid; let state = WalReaderStreamState { tli, wal_reader: PositionedWalReader { start, end, reader: None, }, term, end_watch, buffer: vec![0; buffer_size], buffer_size, }; // When a change notification is received while polling the internal // reader, stop polling the read future and service the change. let stream = futures::stream::unfold( (state, start_changed_rx), |(mut state, mut rx)| async move { let wal_or_reset = tokio::select! { read_res = state.read() => { WalOrReset::Wal(read_res) }, changed_res = rx.changed() => { if changed_res.is_err() { return None; } let new_start_pos = rx.borrow_and_update(); WalOrReset::Reset(*new_start_pos) } }; if let WalOrReset::Reset(lsn) = wal_or_reset { state.wal_reader.start = lsn; state.wal_reader.reader = None; } Some((wal_or_reset, (state, rx))) }, ) .boxed(); Self { stream, start_changed_tx, ttid, } } /// Reset the stream to a given position. pub(crate) async fn reset(&mut self, start: Lsn) { self.start_changed_tx.send(start).unwrap(); while let Some(wal_or_reset) = self.stream.next().await { match wal_or_reset { WalOrReset::Reset(at) => { // Stream confirmed the reset. // There may only one ongoing reset at any given time, // hence the assertion. assert_eq!(at, start); break; } WalOrReset::Wal(_) => { // Ignore wal generated before reset was handled } } } } } impl Stream for StreamingWalReader { type Item = WalOrReset; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.stream).poll_next(cx) } } struct WalReaderStreamState { tli: WalResidentTimeline, wal_reader: PositionedWalReader, term: Option<Term>, end_watch: EndWatch, buffer: Vec<u8>, buffer_size: usize, } impl WalReaderStreamState { async fn read(&mut self) -> anyhow::Result<WalBytes> { // Create reader if needed if self.wal_reader.reader.is_none() { self.wal_reader.reader = Some(self.tli.get_walreader(self.wal_reader.start).await?); } let have_something_to_send = self.wal_reader.end > self.wal_reader.start; if !have_something_to_send { tracing::debug!( "Waiting for wal: start={}, end={}", self.wal_reader.end, self.wal_reader.start ); self.wal_reader.end = self .end_watch .wait_for_lsn(self.wal_reader.start, self.term) .await?; tracing::debug!( "Done waiting for wal: start={}, end={}", self.wal_reader.end, self.wal_reader.start ); } assert!( self.wal_reader.end > self.wal_reader.start, "nothing to send after waiting for WAL" ); // Calculate chunk size let mut chunk_end_pos = self.wal_reader.start + self.buffer_size as u64; if chunk_end_pos >= self.wal_reader.end { chunk_end_pos = self.wal_reader.end; } else { chunk_end_pos = chunk_end_pos .checked_sub(chunk_end_pos.block_offset()) .unwrap(); } let send_size = (chunk_end_pos.0 - self.wal_reader.start.0) as usize; let buffer = &mut self.buffer[..send_size]; // Read WAL let send_size = { let _term_guard = if let Some(t) = self.term { Some(self.tli.acquire_term(t).await?) } else { None }; self.wal_reader .reader .as_mut() .unwrap() .read(buffer) .await? }; let wal = Bytes::copy_from_slice(&buffer[..send_size]); let result = WalBytes { wal, wal_start_lsn: self.wal_reader.start, wal_end_lsn: self.wal_reader.start + send_size as u64, available_wal_end_lsn: self.wal_reader.end, }; self.wal_reader.start += send_size as u64; Ok(result) } } #[cfg(test)] mod tests { use std::str::FromStr; use futures::StreamExt; use postgres_ffi::MAX_SEND_SIZE; use utils::id::{NodeId, TenantTimelineId}; use utils::lsn::Lsn; use crate::test_utils::Env; use crate::wal_reader_stream::StreamingWalReader; #[tokio::test] async fn test_streaming_wal_reader_reset() { let _ = env_logger::builder().is_test(true).try_init(); const SIZE: usize = 8 * 1024; const MSG_COUNT: usize = 200; let start_lsn = Lsn::from_str("0/149FD18").unwrap(); let env = Env::new(true).unwrap(); let tli = env .make_timeline(NodeId(1), TenantTimelineId::generate(), start_lsn) .await .unwrap(); let resident_tli = tli.wal_residence_guard().await.unwrap(); let end_watch = Env::write_wal(tli, start_lsn, SIZE, MSG_COUNT, c"neon-file:", None) .await .unwrap(); let end_pos = end_watch.get(); tracing::info!("Doing first round of reads ..."); let mut streaming_wal_reader = StreamingWalReader::new( resident_tli, None, start_lsn, end_pos, end_watch, MAX_SEND_SIZE, ); let mut before_reset = Vec::new(); while let Some(wor) = streaming_wal_reader.next().await { let wal = wor.get_wal().unwrap().unwrap(); let stop = wal.available_wal_end_lsn == wal.wal_end_lsn; before_reset.push(wal); if stop { break; } } tracing::info!("Resetting the WAL stream ..."); streaming_wal_reader.reset(start_lsn).await; tracing::info!("Doing second round of reads ..."); let mut after_reset = Vec::new(); while let Some(wor) = streaming_wal_reader.next().await { let wal = wor.get_wal().unwrap().unwrap(); let stop = wal.available_wal_end_lsn == wal.wal_end_lsn; after_reset.push(wal); if stop { break; } } assert_eq!(before_reset, after_reset); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/timeline_manager.rs
safekeeper/src/timeline_manager.rs
//! The timeline manager task is responsible for managing the timeline's background tasks. //! //! It is spawned alongside each timeline and exits when the timeline is deleted. //! It watches for changes in the timeline state and decides when to spawn or kill background tasks. //! It also can manage some reactive state, like should the timeline be active for broker pushes or not. //! //! Be aware that you need to be extra careful with manager code, because it is not respawned on panic. //! Also, if it will stuck in some branch, it will prevent any further progress in the timeline. use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::time::Duration; use futures::channel::oneshot; use postgres_ffi::XLogSegNo; use safekeeper_api::Term; use safekeeper_api::models::PeerInfo; use serde::{Deserialize, Serialize}; use tokio::task::{JoinError, JoinHandle}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; use tracing::{Instrument, debug, info, info_span, instrument, warn}; use utils::lsn::Lsn; use crate::SafeKeeperConf; use crate::control_file::{FileStorage, Storage}; use crate::metrics::{ MANAGER_ACTIVE_CHANGES, MANAGER_ITERATIONS_TOTAL, MISC_OPERATION_SECONDS, NUM_EVICTED_TIMELINES, }; use crate::rate_limit::{RateLimiter, rand_duration}; use crate::recovery::recovery_main; use crate::remove_wal::calc_horizon_lsn; use crate::send_wal::WalSenders; use crate::state::TimelineState; use crate::timeline::{ManagerTimeline, ReadGuardSharedState, StateSK, WalResidentTimeline}; use crate::timeline_guard::{AccessService, GuardId, ResidenceGuard}; use crate::timelines_set::{TimelineSetGuard, TimelinesSet}; use crate::wal_backup::{self, WalBackup, WalBackupTaskHandle}; use crate::wal_backup_partial::{self, PartialBackup, PartialRemoteSegment}; pub(crate) struct StateSnapshot { // inmem values pub(crate) commit_lsn: Lsn, pub(crate) backup_lsn: Lsn, pub(crate) remote_consistent_lsn: Lsn, // persistent control file values pub(crate) cfile_commit_lsn: Lsn, pub(crate) cfile_remote_consistent_lsn: Lsn, pub(crate) cfile_backup_lsn: Lsn, // latest state pub(crate) flush_lsn: Lsn, pub(crate) last_log_term: Term, // misc pub(crate) cfile_last_persist_at: std::time::Instant, pub(crate) inmem_flush_pending: bool, pub(crate) wal_removal_on_hold: bool, pub(crate) peers: Vec<PeerInfo>, } impl StateSnapshot { /// Create a new snapshot of the timeline state. fn new(read_guard: ReadGuardSharedState, heartbeat_timeout: Duration) -> Self { let state = read_guard.sk.state(); Self { commit_lsn: state.inmem.commit_lsn, backup_lsn: state.inmem.backup_lsn, remote_consistent_lsn: state.inmem.remote_consistent_lsn, cfile_commit_lsn: state.commit_lsn, cfile_remote_consistent_lsn: state.remote_consistent_lsn, cfile_backup_lsn: state.backup_lsn, flush_lsn: read_guard.sk.flush_lsn(), last_log_term: read_guard.sk.last_log_term(), cfile_last_persist_at: state.pers.last_persist_at(), inmem_flush_pending: Self::has_unflushed_inmem_state(state), wal_removal_on_hold: read_guard.wal_removal_on_hold, peers: read_guard.get_peers(heartbeat_timeout), } } fn has_unflushed_inmem_state(state: &TimelineState<FileStorage>) -> bool { state.inmem.commit_lsn > state.commit_lsn || state.inmem.backup_lsn > state.backup_lsn || state.inmem.peer_horizon_lsn > state.peer_horizon_lsn || state.inmem.remote_consistent_lsn > state.remote_consistent_lsn } } /// Control how often the manager task should wake up to check updates. /// There is no need to check for updates more often than this. const REFRESH_INTERVAL: Duration = Duration::from_millis(300); pub enum ManagerCtlMessage { /// Request to get a guard for WalResidentTimeline, with WAL files available locally. GuardRequest(tokio::sync::oneshot::Sender<anyhow::Result<ResidenceGuard>>), /// Get a guard for WalResidentTimeline if the timeline is not currently offloaded, else None TryGuardRequest(tokio::sync::oneshot::Sender<Option<ResidenceGuard>>), /// Request to drop the guard. GuardDrop(GuardId), /// Request to reset uploaded partial backup state. BackupPartialReset(oneshot::Sender<anyhow::Result<Vec<String>>>), } impl std::fmt::Debug for ManagerCtlMessage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ManagerCtlMessage::GuardRequest(_) => write!(f, "GuardRequest"), ManagerCtlMessage::TryGuardRequest(_) => write!(f, "TryGuardRequest"), ManagerCtlMessage::GuardDrop(id) => write!(f, "GuardDrop({id:?})"), ManagerCtlMessage::BackupPartialReset(_) => write!(f, "BackupPartialReset"), } } } pub struct ManagerCtl { manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>, // this is used to initialize manager, it will be moved out in bootstrap(). init_manager_rx: std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedReceiver<ManagerCtlMessage>>>, } impl Default for ManagerCtl { fn default() -> Self { Self::new() } } impl ManagerCtl { pub fn new() -> Self { let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); Self { manager_tx: tx, init_manager_rx: std::sync::Mutex::new(Some(rx)), } } /// Issue a new guard and wait for manager to prepare the timeline. /// Sends a message to the manager and waits for the response. /// Can be blocked indefinitely if the manager is stuck. pub async fn wal_residence_guard(&self) -> anyhow::Result<ResidenceGuard> { let (tx, rx) = tokio::sync::oneshot::channel(); self.manager_tx.send(ManagerCtlMessage::GuardRequest(tx))?; // wait for the manager to respond with the guard rx.await .map_err(|e| anyhow::anyhow!("response read fail: {:?}", e)) .and_then(std::convert::identity) } /// Issue a new guard if the timeline is currently not offloaded, else return None /// Sends a message to the manager and waits for the response. /// Can be blocked indefinitely if the manager is stuck. pub async fn try_wal_residence_guard(&self) -> anyhow::Result<Option<ResidenceGuard>> { let (tx, rx) = tokio::sync::oneshot::channel(); self.manager_tx .send(ManagerCtlMessage::TryGuardRequest(tx))?; // wait for the manager to respond with the guard rx.await .map_err(|e| anyhow::anyhow!("response read fail: {:?}", e)) } /// Request timeline manager to reset uploaded partial segment state and /// wait for the result. pub async fn backup_partial_reset(&self) -> anyhow::Result<Vec<String>> { let (tx, rx) = oneshot::channel(); self.manager_tx .send(ManagerCtlMessage::BackupPartialReset(tx)) .expect("manager task is not running"); match rx.await { Ok(res) => res, Err(_) => anyhow::bail!("timeline manager is gone"), } } /// Must be called exactly once to bootstrap the manager. pub fn bootstrap_manager( &self, ) -> ( tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>, tokio::sync::mpsc::UnboundedReceiver<ManagerCtlMessage>, ) { let rx = self .init_manager_rx .lock() .expect("mutex init_manager_rx poisoned") .take() .expect("manager already bootstrapped"); (self.manager_tx.clone(), rx) } } pub(crate) struct Manager { // configuration & dependencies pub(crate) tli: ManagerTimeline, pub(crate) conf: SafeKeeperConf, pub(crate) wal_seg_size: usize, pub(crate) walsenders: Arc<WalSenders>, pub(crate) wal_backup: Arc<WalBackup>, // current state pub(crate) state_version_rx: tokio::sync::watch::Receiver<usize>, pub(crate) num_computes_rx: tokio::sync::watch::Receiver<usize>, pub(crate) tli_broker_active: TimelineSetGuard, pub(crate) last_removed_segno: XLogSegNo, pub(crate) is_offloaded: bool, // background tasks pub(crate) backup_task: Option<WalBackupTaskHandle>, pub(crate) recovery_task: Option<JoinHandle<()>>, pub(crate) wal_removal_task: Option<JoinHandle<anyhow::Result<u64>>>, // partial backup pub(crate) partial_backup_task: Option<(JoinHandle<Option<PartialRemoteSegment>>, CancellationToken)>, pub(crate) partial_backup_uploaded: Option<PartialRemoteSegment>, // misc pub(crate) access_service: AccessService, pub(crate) global_rate_limiter: RateLimiter, // Anti-flapping state: we evict timelines eagerly if they are inactive, but should not // evict them if they go inactive very soon after being restored. pub(crate) evict_not_before: Instant, } /// This task gets spawned alongside each timeline and is responsible for managing the timeline's /// background tasks. /// Be careful, this task is not respawned on panic, so it should not panic. #[instrument(name = "manager", skip_all, fields(ttid = %tli.ttid))] pub async fn main_task( tli: ManagerTimeline, conf: SafeKeeperConf, broker_active_set: Arc<TimelinesSet>, manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>, mut manager_rx: tokio::sync::mpsc::UnboundedReceiver<ManagerCtlMessage>, global_rate_limiter: RateLimiter, wal_backup: Arc<WalBackup>, ) { tli.set_status(Status::Started); let defer_tli = tli.tli.clone(); scopeguard::defer! { if defer_tli.is_cancelled() { info!("manager task finished"); } else { warn!("manager task finished prematurely"); } }; let mut mgr = Manager::new( tli, conf, broker_active_set, manager_tx, global_rate_limiter, wal_backup, ) .await; // Start recovery task which always runs on the timeline. if !mgr.is_offloaded && mgr.conf.peer_recovery_enabled { // Recovery task is only spawned if we can get a residence guard (i.e. timeline is not already shutting down) if let Ok(tli) = mgr.wal_resident_timeline() { mgr.recovery_task = Some(tokio::spawn(recovery_main(tli, mgr.conf.clone()))); } } // If timeline is evicted, reflect that in the metric. if mgr.is_offloaded { NUM_EVICTED_TIMELINES.inc(); } let last_state = 'outer: loop { MANAGER_ITERATIONS_TOTAL.inc(); mgr.set_status(Status::StateSnapshot); let state_snapshot = mgr.state_snapshot().await; let mut next_event: Option<Instant> = None; if !mgr.is_offloaded { let num_computes = *mgr.num_computes_rx.borrow(); mgr.set_status(Status::UpdateBackup); let is_wal_backup_required = mgr.update_backup(num_computes, &state_snapshot).await; mgr.update_is_active(is_wal_backup_required, num_computes, &state_snapshot); mgr.set_status(Status::UpdateControlFile); mgr.update_control_file_save(&state_snapshot, &mut next_event) .await; mgr.set_status(Status::UpdateWalRemoval); mgr.update_wal_removal(&state_snapshot).await; mgr.set_status(Status::UpdatePartialBackup); mgr.update_partial_backup(&state_snapshot).await; let now = Instant::now(); if mgr.evict_not_before > now { // we should wait until evict_not_before update_next_event(&mut next_event, mgr.evict_not_before); } if mgr.conf.enable_offload && mgr.evict_not_before <= now && mgr.ready_for_eviction(&next_event, &state_snapshot) { // check rate limiter and evict timeline if possible match mgr.global_rate_limiter.try_acquire_eviction() { Some(_permit) => { mgr.set_status(Status::EvictTimeline); if !mgr.evict_timeline().await { // eviction failed, try again later mgr.evict_not_before = Instant::now() + rand_duration(&mgr.conf.eviction_min_resident); update_next_event(&mut next_event, mgr.evict_not_before); } } None => { // we can't evict timeline now, will try again later mgr.evict_not_before = Instant::now() + rand_duration(&mgr.conf.eviction_min_resident); update_next_event(&mut next_event, mgr.evict_not_before); } } } } mgr.set_status(Status::Wait); // wait until something changes. tx channels are stored under Arc, so they will not be // dropped until the manager task is finished. tokio::select! { _ = mgr.tli.cancel.cancelled() => { // timeline was deleted break 'outer state_snapshot; } _ = async { // don't wake up on every state change, but at most every REFRESH_INTERVAL tokio::time::sleep(REFRESH_INTERVAL).await; let _ = mgr.state_version_rx.changed().await; } => { // state was updated } _ = mgr.num_computes_rx.changed() => { // number of connected computes was updated } _ = sleep_until(&next_event) => { // we were waiting for some event (e.g. cfile save) } res = await_task_finish(mgr.wal_removal_task.as_mut()) => { // WAL removal task finished mgr.wal_removal_task = None; mgr.update_wal_removal_end(res); } res = await_task_finish(mgr.partial_backup_task.as_mut().map(|(handle, _)| handle)) => { // partial backup task finished mgr.partial_backup_task = None; mgr.update_partial_backup_end(res); } msg = manager_rx.recv() => { mgr.set_status(Status::HandleMessage); mgr.handle_message(msg).await; } } }; mgr.set_status(Status::Exiting); // remove timeline from the broker active set sooner, before waiting for background tasks mgr.tli_broker_active.set(false); // shutdown background tasks if let Some(storage) = mgr.wal_backup.get_storage() { if let Some(backup_task) = mgr.backup_task.take() { // If we fell through here, then the timeline is shutting down. This is important // because otherwise joining on the wal_backup handle might hang. assert!(mgr.tli.cancel.is_cancelled()); backup_task.join().await; } wal_backup::update_task(&mut mgr, storage, false, &last_state).await; } if let Some(recovery_task) = &mut mgr.recovery_task { if let Err(e) = recovery_task.await { warn!("recovery task failed: {:?}", e); } } if let Some((handle, cancel)) = &mut mgr.partial_backup_task { cancel.cancel(); if let Err(e) = handle.await { warn!("partial backup task failed: {:?}", e); } } if let Some(wal_removal_task) = &mut mgr.wal_removal_task { let res = wal_removal_task.await; mgr.update_wal_removal_end(res); } // If timeline is deleted while evicted decrement the gauge. if mgr.tli.is_cancelled() && mgr.is_offloaded { NUM_EVICTED_TIMELINES.dec(); } mgr.set_status(Status::Finished); } impl Manager { async fn new( tli: ManagerTimeline, conf: SafeKeeperConf, broker_active_set: Arc<TimelinesSet>, manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>, global_rate_limiter: RateLimiter, wal_backup: Arc<WalBackup>, ) -> Manager { let (is_offloaded, partial_backup_uploaded) = tli.bootstrap_mgr().await; Manager { wal_seg_size: tli.get_wal_seg_size().await, walsenders: tli.get_walsenders().clone(), wal_backup, state_version_rx: tli.get_state_version_rx(), num_computes_rx: tli.get_walreceivers().get_num_rx(), tli_broker_active: broker_active_set.guard(tli.clone()), last_removed_segno: 0, is_offloaded, backup_task: None, recovery_task: None, wal_removal_task: None, partial_backup_task: None, partial_backup_uploaded, access_service: AccessService::new(manager_tx), tli, global_rate_limiter, // to smooth out evictions spike after restart evict_not_before: Instant::now() + rand_duration(&conf.eviction_min_resident), conf, } } fn set_status(&self, status: Status) { self.tli.set_status(status); } /// Get a WalResidentTimeline. /// Manager code must use this function instead of one from `Timeline` /// directly, because it will deadlock. /// /// This function is fallible because the guard may not be created if the timeline is /// shutting down. pub(crate) fn wal_resident_timeline(&mut self) -> anyhow::Result<WalResidentTimeline> { assert!(!self.is_offloaded); let guard = self.access_service.create_guard( self.tli .gate .enter() .map_err(|_| anyhow::anyhow!("Timeline shutting down"))?, ); Ok(WalResidentTimeline::new(self.tli.clone(), guard)) } /// Get a snapshot of the timeline state. async fn state_snapshot(&self) -> StateSnapshot { let _timer = MISC_OPERATION_SECONDS .with_label_values(&["state_snapshot"]) .start_timer(); StateSnapshot::new( self.tli.read_shared_state().await, self.conf.heartbeat_timeout, ) } /// Spawns/kills backup task and returns true if backup is required. async fn update_backup(&mut self, num_computes: usize, state: &StateSnapshot) -> bool { let is_wal_backup_required = wal_backup::is_wal_backup_required(self.wal_seg_size, num_computes, state); if let Some(storage) = self.wal_backup.get_storage() { wal_backup::update_task(self, storage, is_wal_backup_required, state).await; } // update the state in Arc<Timeline> self.tli.wal_backup_active.store( self.backup_task.is_some(), std::sync::atomic::Ordering::Relaxed, ); is_wal_backup_required } /// Update is_active flag and returns its value. fn update_is_active( &mut self, is_wal_backup_required: bool, num_computes: usize, state: &StateSnapshot, ) { let is_active = is_wal_backup_required || num_computes > 0 || state.remote_consistent_lsn < state.commit_lsn; // update the broker timeline set if self.tli_broker_active.set(is_active) { // write log if state has changed info!( "timeline active={} now, remote_consistent_lsn={}, commit_lsn={}", is_active, state.remote_consistent_lsn, state.commit_lsn, ); MANAGER_ACTIVE_CHANGES.inc(); } // update the state in Arc<Timeline> self.tli .broker_active .store(is_active, std::sync::atomic::Ordering::Relaxed); } /// Save control file if needed. Returns Instant if we should persist the control file in the future. async fn update_control_file_save( &self, state: &StateSnapshot, next_event: &mut Option<Instant>, ) { if !state.inmem_flush_pending { return; } if state.cfile_last_persist_at.elapsed() > self.conf.control_file_save_interval // If the control file's commit_lsn lags more than one segment behind the current // commit_lsn, flush immediately to limit recovery time in case of a crash. We don't do // this on the WAL ingest hot path since it incurs fsync latency. || state.commit_lsn.saturating_sub(state.cfile_commit_lsn).0 >= self.wal_seg_size as u64 { let mut write_guard = self.tli.write_shared_state().await; // it should be done in the background because it blocks manager task, but flush() should // be fast enough not to be a problem now if let Err(e) = write_guard.sk.state_mut().flush().await { warn!("failed to save control file: {:?}", e); } } else { // we should wait until some time passed until the next save update_next_event( next_event, (state.cfile_last_persist_at + self.conf.control_file_save_interval).into(), ); } } /// Spawns WAL removal task if needed. async fn update_wal_removal(&mut self, state: &StateSnapshot) { if self.wal_removal_task.is_some() || state.wal_removal_on_hold { // WAL removal is already in progress or hold off return; } // If enabled, we use LSN of the most lagging walsender as a WAL removal horizon. // This allows to get better read speed for pageservers that are lagging behind, // at the cost of keeping more WAL on disk. let replication_horizon_lsn = if self.conf.walsenders_keep_horizon { self.walsenders.laggard_lsn() } else { None }; let removal_horizon_lsn = calc_horizon_lsn(state, replication_horizon_lsn); let removal_horizon_segno = removal_horizon_lsn .segment_number(self.wal_seg_size) .saturating_sub(1); if removal_horizon_segno > self.last_removed_segno { // we need to remove WAL let Ok(timeline_gate_guard) = self.tli.gate.enter() else { tracing::info!("Timeline shutdown, not spawning WAL removal task"); return; }; let remover = match self.tli.read_shared_state().await.sk { StateSK::Loaded(ref sk) => { crate::wal_storage::Storage::remove_up_to(&sk.wal_store, removal_horizon_segno) } StateSK::Offloaded(_) => { // we can't remove WAL if it's not loaded warn!("unexpectedly trying to run WAL removal on offloaded timeline"); return; } StateSK::Empty => unreachable!(), }; self.wal_removal_task = Some(tokio::spawn( async move { let _timeline_gate_guard = timeline_gate_guard; remover.await?; Ok(removal_horizon_segno) } .instrument(info_span!("WAL removal", ttid=%self.tli.ttid)), )); } } /// Update the state after WAL removal task finished. fn update_wal_removal_end(&mut self, res: Result<anyhow::Result<u64>, JoinError>) { let new_last_removed_segno = match res { Ok(Ok(segno)) => segno, Err(e) => { warn!("WAL removal task failed: {:?}", e); return; } Ok(Err(e)) => { warn!("WAL removal task failed: {:?}", e); return; } }; self.last_removed_segno = new_last_removed_segno; // update the state in Arc<Timeline> self.tli .last_removed_segno .store(new_last_removed_segno, std::sync::atomic::Ordering::Relaxed); } /// Spawns partial WAL backup task if needed. async fn update_partial_backup(&mut self, state: &StateSnapshot) { // check if WAL backup is enabled and should be started let Some(storage) = self.wal_backup.get_storage() else { return; }; if self.partial_backup_task.is_some() { // partial backup is already running return; } if !wal_backup_partial::needs_uploading(state, &self.partial_backup_uploaded) { // nothing to upload return; } let Ok(resident) = self.wal_resident_timeline() else { // Shutting down return; }; // Get WalResidentTimeline and start partial backup task. let cancel = CancellationToken::new(); let handle = tokio::spawn(wal_backup_partial::main_task( resident, self.conf.clone(), self.global_rate_limiter.clone(), cancel.clone(), storage, )); self.partial_backup_task = Some((handle, cancel)); } /// Update the state after partial WAL backup task finished. fn update_partial_backup_end(&mut self, res: Result<Option<PartialRemoteSegment>, JoinError>) { match res { Ok(new_upload_state) => { self.partial_backup_uploaded = new_upload_state; } Err(e) => { warn!("partial backup task panicked: {:?}", e); } } } /// Reset partial backup state and remove its remote storage data. Since it /// might concurrently uploading something, cancel the task first. async fn backup_partial_reset(&mut self) -> anyhow::Result<Vec<String>> { let Some(storage) = self.wal_backup.get_storage() else { anyhow::bail!("remote storage is not enabled"); }; info!("resetting partial backup state"); // Force unevict timeline if it is evicted before erasing partial backup // state. The intended use of this function is to drop corrupted remote // state; we haven't enabled local files deletion yet anywhere, // so direct switch is safe. if self.is_offloaded { self.tli.switch_to_present().await?; // switch manager state as soon as possible self.is_offloaded = false; } if let Some((handle, cancel)) = &mut self.partial_backup_task { cancel.cancel(); info!("cancelled partial backup task, awaiting it"); // we're going to reset .partial_backup_uploaded to None anyway, so ignore the result handle.await.ok(); self.partial_backup_task = None; } let tli = self.wal_resident_timeline()?; let mut partial_backup = PartialBackup::new(tli, self.conf.clone(), storage).await; // Reset might fail e.g. when cfile is already reset but s3 removal // failed, so set manager state to None beforehand. In any case caller // is expected to retry until success. self.partial_backup_uploaded = None; let res = partial_backup.reset().await?; info!("reset is done"); Ok(res) } /// Handle message arrived from ManagerCtl. async fn handle_message(&mut self, msg: Option<ManagerCtlMessage>) { debug!("received manager message: {:?}", msg); match msg { Some(ManagerCtlMessage::GuardRequest(tx)) => { if self.is_offloaded { // trying to unevict timeline, but without gurarantee that it will be successful self.unevict_timeline().await; } let guard = if self.is_offloaded { Err(anyhow::anyhow!("timeline is offloaded, can't get a guard")) } else { match self.tli.gate.enter() { Ok(gate_guard) => Ok(self.access_service.create_guard(gate_guard)), Err(_) => Err(anyhow::anyhow!( "timeline is shutting down, can't get a guard" )), } }; if tx.send(guard).is_err() { warn!("failed to reply with a guard, receiver dropped"); } } Some(ManagerCtlMessage::TryGuardRequest(tx)) => { let result = if self.is_offloaded { None } else { match self.tli.gate.enter() { Ok(gate_guard) => Some(self.access_service.create_guard(gate_guard)), Err(_) => None, } }; if tx.send(result).is_err() { warn!("failed to reply with a guard, receiver dropped"); } } Some(ManagerCtlMessage::GuardDrop(guard_id)) => { self.access_service.drop_guard(guard_id); } Some(ManagerCtlMessage::BackupPartialReset(tx)) => { info!("resetting uploaded partial backup state"); let res = self.backup_partial_reset().await; if let Err(ref e) = res { warn!("failed to reset partial backup state: {:?}", e); } if tx.send(res).is_err() { warn!("failed to send partial backup reset result, receiver dropped"); } } None => { // can't happen, we're holding the sender unreachable!(); } } } } // utility functions async fn sleep_until(option: &Option<tokio::time::Instant>) { if let Some(timeout) = option { tokio::time::sleep_until(*timeout).await; } else { futures::future::pending::<()>().await; } } /// Future that resolves when the task is finished or never if the task is None. /// /// Note: it accepts Option<&mut> instead of &mut Option<> because mapping the /// option to get the latter is hard. async fn await_task_finish<T>(option: Option<&mut JoinHandle<T>>) -> Result<T, JoinError> { if let Some(task) = option { task.await } else { futures::future::pending().await } } /// Update next_event if candidate is earlier. fn update_next_event(next_event: &mut Option<Instant>, candidate: Instant) { if let Some(next) = next_event { if candidate < *next { *next = candidate; } } else { *next_event = Some(candidate); } } #[repr(usize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Status { NotStarted, Started, StateSnapshot, UpdateBackup, UpdateControlFile, UpdateWalRemoval, UpdatePartialBackup, EvictTimeline, Wait, HandleMessage, Exiting, Finished, } /// AtomicStatus is a wrapper around AtomicUsize adapted for the Status enum. pub struct AtomicStatus { inner: AtomicUsize, } impl Default for AtomicStatus { fn default() -> Self { Self::new() } } impl AtomicStatus { pub fn new() -> Self { AtomicStatus { inner: AtomicUsize::new(Status::NotStarted as usize), } } pub fn load(&self, order: std::sync::atomic::Ordering) -> Status { // Safety: This line of code uses `std::mem::transmute` to reinterpret the loaded value as `Status`. // It is safe to use `transmute` in this context because `Status` is a repr(usize) enum, // which means it has the same memory layout as usize. // However, it is important to ensure that the loaded value is a valid variant of `Status`, // otherwise, the behavior will be undefined. unsafe { std::mem::transmute(self.inner.load(order)) } } pub fn get(&self) -> Status { self.load(std::sync::atomic::Ordering::Relaxed) } pub fn store(&self, val: Status, order: std::sync::atomic::Ordering) { self.inner.store(val as usize, order); } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/metrics.rs
safekeeper/src/metrics.rs
//! Global safekeeper mertics and per-timeline safekeeper metrics. use std::sync::{Arc, RwLock}; use std::time::{Instant, SystemTime}; use anyhow::Result; use futures::Future; use metrics::core::{AtomicU64, Collector, Desc, GenericCounter, GenericGaugeVec, Opts}; use metrics::proto::MetricFamily; use metrics::{ DISK_FSYNC_SECONDS_BUCKETS, Gauge, GaugeVec, Histogram, HistogramVec, IntCounter, IntCounterPair, IntCounterPairVec, IntCounterVec, IntGauge, IntGaugeVec, pow2_buckets, register_histogram, register_histogram_vec, register_int_counter, register_int_counter_pair, register_int_counter_pair_vec, register_int_counter_vec, register_int_gauge, register_int_gauge_vec, }; use once_cell::sync::Lazy; use postgres_ffi::XLogSegNo; use utils::id::TenantTimelineId; use utils::lsn::Lsn; use utils::pageserver_feedback::PageserverFeedback; use crate::GlobalTimelines; use crate::receive_wal::MSG_QUEUE_SIZE; use crate::state::{TimelineMemState, TimelinePersistentState}; // Global metrics across all timelines. pub static WRITE_WAL_BYTES: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_write_wal_bytes", "Bytes written to WAL in a single request", vec![ 1.0, 10.0, 100.0, 1024.0, 8192.0, 128.0 * 1024.0, 1024.0 * 1024.0, 10.0 * 1024.0 * 1024.0 ] ) .expect("Failed to register safekeeper_write_wal_bytes histogram") }); pub static WRITE_WAL_SECONDS: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_write_wal_seconds", "Seconds spent writing and syncing WAL to a disk in a single request", DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_write_wal_seconds histogram") }); pub static FLUSH_WAL_SECONDS: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_flush_wal_seconds", "Seconds spent syncing WAL to a disk (excluding segment initialization)", DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_flush_wal_seconds histogram") }); /* BEGIN_HADRON */ // Counter of all ProposerAcceptorMessage requests received pub static PROPOSER_ACCEPTOR_MESSAGES_TOTAL: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "safekeeper_proposer_acceptor_messages_total", "Total number of ProposerAcceptorMessage requests received by the Safekeeper.", &["outcome"] ) .expect("Failed to register safekeeper_proposer_acceptor_messages_total counter") }); pub static WAL_DISK_IO_ERRORS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_wal_disk_io_errors", "Number of disk I/O errors when creating and flushing WALs and control files" ) .expect("Failed to register safekeeper_wal_disk_io_errors counter") }); pub static WAL_STORAGE_LIMIT_ERRORS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_wal_storage_limit_errors", concat!( "Number of errors due to timeline WAL storage utilization exceeding configured limit. ", "An increase in this metric indicates issues backing up or removing WALs." ) ) .expect("Failed to register safekeeper_wal_storage_limit_errors counter") }); pub static SK_RECOVERY_PULL_TIMELINE_ERRORS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_recovery_pull_timeline_errors", concat!( "Number of errors due to pull_timeline errors during SK lost disk recovery.", "An increase in this metric indicates pull timelines runs into error." ) ) .expect("Failed to register safekeeper_recovery_pull_timeline_errors counter") }); pub static SK_RECOVERY_PULL_TIMELINE_OKS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_recovery_pull_timeline_oks", concat!( "Number of successful pull_timeline during SK lost disk recovery.", "An increase in this metric indicates pull timelines is successful." ) ) .expect("Failed to register safekeeper_recovery_pull_timeline_oks counter") }); pub static SK_RECOVERY_PULL_TIMELINES_SECONDS: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_recovery_pull_timelines_seconds", "Seconds to pull timelines", DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_recovery_pull_timelines_seconds histogram") }); pub static SK_RECOVERY_PULL_TIMELINE_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "safekeeper_recovery_pull_timeline_seconds", "Seconds to pull timeline", &["tenant_id", "timeline_id"], DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_recovery_pull_timeline_seconds histogram vec") }); /* END_HADRON */ pub static PERSIST_CONTROL_FILE_SECONDS: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_persist_control_file_seconds", "Seconds to persist and sync control file", DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_persist_control_file_seconds histogram vec") }); pub static WAL_STORAGE_OPERATION_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "safekeeper_wal_storage_operation_seconds", "Seconds spent on WAL storage operations", &["operation"], DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_wal_storage_operation_seconds histogram vec") }); pub static MISC_OPERATION_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "safekeeper_misc_operation_seconds", "Seconds spent on miscellaneous operations", &["operation"], DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_misc_operation_seconds histogram vec") }); pub static PG_IO_BYTES: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "safekeeper_pg_io_bytes_total", "Bytes read from or written to any PostgreSQL connection", &["client_az", "sk_az", "app_name", "dir", "same_az"] ) .expect("Failed to register safekeeper_pg_io_bytes gauge") }); pub static BROKER_PUSHED_UPDATES: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_broker_pushed_updates_total", "Number of timeline updates pushed to the broker" ) .expect("Failed to register safekeeper_broker_pushed_updates_total counter") }); pub static BROKER_PULLED_UPDATES: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "safekeeper_broker_pulled_updates_total", "Number of timeline updates pulled and processed from the broker", &["result"] ) .expect("Failed to register safekeeper_broker_pulled_updates_total counter") }); pub static PG_QUERIES_GAUGE: Lazy<IntCounterPairVec> = Lazy::new(|| { register_int_counter_pair_vec!( "safekeeper_pg_queries_received_total", "Number of queries received through pg protocol", "safekeeper_pg_queries_finished_total", "Number of queries finished through pg protocol", &["query"] ) .expect("Failed to register safekeeper_pg_queries_finished_total counter") }); pub static REMOVED_WAL_SEGMENTS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_removed_wal_segments_total", "Number of WAL segments removed from the disk" ) .expect("Failed to register safekeeper_removed_wal_segments_total counter") }); pub static BACKED_UP_SEGMENTS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_backed_up_segments_total", "Number of WAL segments backed up to the S3" ) .expect("Failed to register safekeeper_backed_up_segments_total counter") }); pub static BACKUP_ERRORS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_backup_errors_total", "Number of errors during backup" ) .expect("Failed to register safekeeper_backup_errors_total counter") }); /* BEGIN_HADRON */ pub static BACKUP_REELECT_LEADER_COUNT: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_backup_reelect_leader_total", "Number of times the backup leader was reelected" ) .expect("Failed to register safekeeper_backup_reelect_leader_total counter") }); /* END_HADRON */ pub static BROKER_PUSH_ALL_UPDATES_SECONDS: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_broker_push_update_seconds", "Seconds to push all timeline updates to the broker", DISK_FSYNC_SECONDS_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_broker_push_update_seconds histogram vec") }); pub const TIMELINES_COUNT_BUCKETS: &[f64] = &[ 1.0, 10.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0, 20000.0, 50000.0, ]; pub static BROKER_ITERATION_TIMELINES: Lazy<Histogram> = Lazy::new(|| { register_histogram!( "safekeeper_broker_iteration_timelines", "Count of timelines pushed to the broker in a single iteration", TIMELINES_COUNT_BUCKETS.to_vec() ) .expect("Failed to register safekeeper_broker_iteration_timelines histogram vec") }); pub static RECEIVED_PS_FEEDBACKS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_received_ps_feedbacks_total", "Number of pageserver feedbacks received" ) .expect("Failed to register safekeeper_received_ps_feedbacks_total counter") }); pub static PARTIAL_BACKUP_UPLOADS: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "safekeeper_partial_backup_uploads_total", "Number of partial backup uploads to the S3", &["result"] ) .expect("Failed to register safekeeper_partial_backup_uploads_total counter") }); pub static PARTIAL_BACKUP_UPLOADED_BYTES: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_partial_backup_uploaded_bytes_total", "Number of bytes uploaded to the S3 during partial backup" ) .expect("Failed to register safekeeper_partial_backup_uploaded_bytes_total counter") }); pub static MANAGER_ITERATIONS_TOTAL: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_manager_iterations_total", "Number of iterations of the timeline manager task" ) .expect("Failed to register safekeeper_manager_iterations_total counter") }); pub static MANAGER_ACTIVE_CHANGES: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "safekeeper_manager_active_changes_total", "Number of timeline active status changes in the timeline manager task" ) .expect("Failed to register safekeeper_manager_active_changes_total counter") }); pub static WAL_BACKUP_TASKS: Lazy<IntCounterPair> = Lazy::new(|| { register_int_counter_pair!( "safekeeper_wal_backup_tasks_started_total", "Number of active WAL backup tasks", "safekeeper_wal_backup_tasks_finished_total", "Number of finished WAL backup tasks", ) .expect("Failed to register safekeeper_wal_backup_tasks_finished_total counter") }); pub static WAL_RECEIVERS: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "safekeeper_wal_receivers", "Number of currently connected WAL receivers (i.e. connected computes)" ) .expect("Failed to register safekeeper_wal_receivers") }); pub static WAL_READERS: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "safekeeper_wal_readers", "Number of active WAL readers (may serve pageservers or other safekeepers)", &["kind", "target"] ) .expect("Failed to register safekeeper_wal_receivers") }); pub static WAL_RECEIVER_QUEUE_DEPTH: Lazy<Histogram> = Lazy::new(|| { // Use powers of two buckets, but add a bucket at 0 and the max queue size to track empty and // full queues respectively. let mut buckets = pow2_buckets(1, MSG_QUEUE_SIZE); buckets.insert(0, 0.0); buckets.insert(buckets.len() - 1, (MSG_QUEUE_SIZE - 1) as f64); assert!(buckets.len() <= 12, "too many histogram buckets"); register_histogram!( "safekeeper_wal_receiver_queue_depth", "Number of queued messages per WAL receiver (sampled every 5 seconds)", buckets ) .expect("Failed to register safekeeper_wal_receiver_queue_depth histogram") }); pub static WAL_RECEIVER_QUEUE_DEPTH_TOTAL: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "safekeeper_wal_receiver_queue_depth_total", "Total number of queued messages across all WAL receivers", ) .expect("Failed to register safekeeper_wal_receiver_queue_depth_total gauge") }); // TODO: consider adding a per-receiver queue_size histogram. This will require wrapping the Tokio // MPSC channel to update counters on send, receive, and drop, while forwarding all other methods. pub static WAL_RECEIVER_QUEUE_SIZE_TOTAL: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "safekeeper_wal_receiver_queue_size_total", "Total memory byte size of queued messages across all WAL receivers", ) .expect("Failed to register safekeeper_wal_receiver_queue_size_total gauge") }); // Metrics collected on operations on the storage repository. #[derive(strum_macros::EnumString, strum_macros::Display, strum_macros::IntoStaticStr)] #[strum(serialize_all = "kebab_case")] pub(crate) enum EvictionEvent { Evict, Restore, } pub(crate) static EVICTION_EVENTS_STARTED: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "safekeeper_eviction_events_started_total", "Number of eviction state changes, incremented when they start", &["kind"] ) .expect("Failed to register metric") }); pub(crate) static EVICTION_EVENTS_COMPLETED: Lazy<IntCounterVec> = Lazy::new(|| { register_int_counter_vec!( "safekeeper_eviction_events_completed_total", "Number of eviction state changes, incremented when they complete", &["kind"] ) .expect("Failed to register metric") }); pub static NUM_EVICTED_TIMELINES: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "safekeeper_evicted_timelines", "Number of currently evicted timelines" ) .expect("Failed to register metric") }); pub const LABEL_UNKNOWN: &str = "unknown"; /// Labels for traffic metrics. #[derive(Clone)] struct ConnectionLabels { /// Availability zone of the connection origin. client_az: String, /// Availability zone of the current safekeeper. sk_az: String, /// Client application name. app_name: String, } impl ConnectionLabels { fn new() -> Self { Self { client_az: LABEL_UNKNOWN.to_string(), sk_az: LABEL_UNKNOWN.to_string(), app_name: LABEL_UNKNOWN.to_string(), } } fn build_metrics( &self, ) -> ( GenericCounter<metrics::core::AtomicU64>, GenericCounter<metrics::core::AtomicU64>, ) { let same_az = match (self.client_az.as_str(), self.sk_az.as_str()) { (LABEL_UNKNOWN, _) | (_, LABEL_UNKNOWN) => LABEL_UNKNOWN, (client_az, sk_az) => { if client_az == sk_az { "true" } else { "false" } } }; let read = PG_IO_BYTES.with_label_values(&[ &self.client_az, &self.sk_az, &self.app_name, "read", same_az, ]); let write = PG_IO_BYTES.with_label_values(&[ &self.client_az, &self.sk_az, &self.app_name, "write", same_az, ]); (read, write) } } struct TrafficMetricsState { /// Labels for traffic metrics. labels: ConnectionLabels, /// Total bytes read from this connection. read: GenericCounter<metrics::core::AtomicU64>, /// Total bytes written to this connection. write: GenericCounter<metrics::core::AtomicU64>, } /// Metrics for measuring traffic (r/w bytes) in a single PostgreSQL connection. #[derive(Clone)] pub struct TrafficMetrics { state: Arc<RwLock<TrafficMetricsState>>, } impl Default for TrafficMetrics { fn default() -> Self { Self::new() } } impl TrafficMetrics { pub fn new() -> Self { let labels = ConnectionLabels::new(); let (read, write) = labels.build_metrics(); let state = TrafficMetricsState { labels, read, write, }; Self { state: Arc::new(RwLock::new(state)), } } pub fn set_client_az(&self, value: &str) { let mut state = self.state.write().unwrap(); state.labels.client_az = value.to_string(); (state.read, state.write) = state.labels.build_metrics(); } pub fn set_sk_az(&self, value: &str) { let mut state = self.state.write().unwrap(); state.labels.sk_az = value.to_string(); (state.read, state.write) = state.labels.build_metrics(); } pub fn set_app_name(&self, value: &str) { let mut state = self.state.write().unwrap(); state.labels.app_name = value.to_string(); (state.read, state.write) = state.labels.build_metrics(); } pub fn observe_read(&self, cnt: usize) { self.state.read().unwrap().read.inc_by(cnt as u64) } pub fn observe_write(&self, cnt: usize) { self.state.read().unwrap().write.inc_by(cnt as u64) } } /// Metrics for WalStorage in a single timeline. #[derive(Clone, Default)] pub struct WalStorageMetrics { /// How much bytes were written in total. write_wal_bytes: u64, /// How much time spent writing WAL to disk, waiting for write(2). write_wal_seconds: f64, /// How much time spent syncing WAL to disk, waiting for fsync(2). flush_wal_seconds: f64, } impl WalStorageMetrics { pub fn observe_write_bytes(&mut self, bytes: usize) { self.write_wal_bytes += bytes as u64; WRITE_WAL_BYTES.observe(bytes as f64); } pub fn observe_write_seconds(&mut self, seconds: f64) { self.write_wal_seconds += seconds; WRITE_WAL_SECONDS.observe(seconds); } pub fn observe_flush_seconds(&mut self, seconds: f64) { self.flush_wal_seconds += seconds; FLUSH_WAL_SECONDS.observe(seconds); } } /// Accepts async function that returns empty anyhow result, and returns the duration of its execution. pub async fn time_io_closure<E: Into<anyhow::Error>>( closure: impl Future<Output = Result<(), E>>, ) -> Result<f64> { let start = std::time::Instant::now(); closure.await.map_err(|e| e.into())?; Ok(start.elapsed().as_secs_f64()) } /// Metrics for a single timeline. #[derive(Clone)] pub struct FullTimelineInfo { pub ttid: TenantTimelineId, pub ps_feedback_count: u64, pub ps_corruption_detected: bool, pub last_ps_feedback: PageserverFeedback, pub wal_backup_active: bool, pub timeline_is_active: bool, pub num_computes: u32, pub last_removed_segno: XLogSegNo, pub interpreted_wal_reader_tasks: usize, pub epoch_start_lsn: Lsn, pub mem_state: TimelineMemState, pub persisted_state: TimelinePersistentState, pub flush_lsn: Lsn, pub wal_storage: WalStorageMetrics, } /// Collects metrics for all active timelines. pub struct TimelineCollector { global_timelines: Arc<GlobalTimelines>, descs: Vec<Desc>, commit_lsn: GenericGaugeVec<AtomicU64>, backup_lsn: GenericGaugeVec<AtomicU64>, flush_lsn: GenericGaugeVec<AtomicU64>, epoch_start_lsn: GenericGaugeVec<AtomicU64>, peer_horizon_lsn: GenericGaugeVec<AtomicU64>, remote_consistent_lsn: GenericGaugeVec<AtomicU64>, ps_last_received_lsn: GenericGaugeVec<AtomicU64>, feedback_last_time_seconds: GenericGaugeVec<AtomicU64>, ps_feedback_count: GenericGaugeVec<AtomicU64>, ps_corruption_detected: IntGaugeVec, timeline_active: GenericGaugeVec<AtomicU64>, wal_backup_active: GenericGaugeVec<AtomicU64>, connected_computes: IntGaugeVec, disk_usage: GenericGaugeVec<AtomicU64>, acceptor_term: GenericGaugeVec<AtomicU64>, written_wal_bytes: GenericGaugeVec<AtomicU64>, interpreted_wal_reader_tasks: GenericGaugeVec<AtomicU64>, written_wal_seconds: GaugeVec, flushed_wal_seconds: GaugeVec, collect_timeline_metrics: Gauge, timelines_count: IntGauge, active_timelines_count: IntGauge, } impl TimelineCollector { pub fn new(global_timelines: Arc<GlobalTimelines>) -> TimelineCollector { let mut descs = Vec::new(); let commit_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_commit_lsn", "Current commit_lsn (not necessarily persisted to disk), grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(commit_lsn.desc().into_iter().cloned()); let backup_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_backup_lsn", "Current backup_lsn, up to which WAL is backed up, grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(backup_lsn.desc().into_iter().cloned()); let flush_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_flush_lsn", "Current flush_lsn, grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(flush_lsn.desc().into_iter().cloned()); let epoch_start_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_epoch_start_lsn", "Point since which compute generates new WAL in the current consensus term", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(epoch_start_lsn.desc().into_iter().cloned()); let peer_horizon_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_peer_horizon_lsn", "LSN of the most lagging safekeeper", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(peer_horizon_lsn.desc().into_iter().cloned()); let remote_consistent_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_remote_consistent_lsn", "LSN which is persisted to the remote storage in pageserver", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(remote_consistent_lsn.desc().into_iter().cloned()); let ps_last_received_lsn = GenericGaugeVec::new( Opts::new( "safekeeper_ps_last_received_lsn", "Last LSN received by the pageserver, acknowledged in the feedback", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(ps_last_received_lsn.desc().into_iter().cloned()); let feedback_last_time_seconds = GenericGaugeVec::new( Opts::new( "safekeeper_feedback_last_time_seconds", "Timestamp of the last feedback from the pageserver", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(feedback_last_time_seconds.desc().into_iter().cloned()); let ps_feedback_count = GenericGaugeVec::new( Opts::new( "safekeeper_ps_feedback_count_total", "Number of feedbacks received from the pageserver", ), &["tenant_id", "timeline_id"], ) .unwrap(); let ps_corruption_detected = IntGaugeVec::new( Opts::new( "safekeeper_ps_corruption_detected", "1 if corruption was detected in the timeline according to feedback from the pageserver, 0 otherwise", ), &["tenant_id", "timeline_id"], ) .unwrap(); let timeline_active = GenericGaugeVec::new( Opts::new( "safekeeper_timeline_active", "Reports 1 for active timelines, 0 for inactive", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(timeline_active.desc().into_iter().cloned()); let wal_backup_active = GenericGaugeVec::new( Opts::new( "safekeeper_wal_backup_active", "Reports 1 for timelines with active WAL backup, 0 otherwise", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(wal_backup_active.desc().into_iter().cloned()); let connected_computes = IntGaugeVec::new( Opts::new( "safekeeper_connected_computes", "Number of active compute connections", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(connected_computes.desc().into_iter().cloned()); let disk_usage = GenericGaugeVec::new( Opts::new( "safekeeper_disk_usage_bytes", "Estimated disk space used to store WAL segments", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(disk_usage.desc().into_iter().cloned()); let acceptor_term = GenericGaugeVec::new( Opts::new("safekeeper_acceptor_term", "Current consensus term"), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(acceptor_term.desc().into_iter().cloned()); let written_wal_bytes = GenericGaugeVec::new( Opts::new( "safekeeper_written_wal_bytes_total", "Number of WAL bytes written to disk, grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(written_wal_bytes.desc().into_iter().cloned()); let written_wal_seconds = GaugeVec::new( Opts::new( "safekeeper_written_wal_seconds_total", "Total time spent in write(2) writing WAL to disk, grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(written_wal_seconds.desc().into_iter().cloned()); let flushed_wal_seconds = GaugeVec::new( Opts::new( "safekeeper_flushed_wal_seconds_total", "Total time spent in fsync(2) flushing WAL to disk, grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(flushed_wal_seconds.desc().into_iter().cloned()); let collect_timeline_metrics = Gauge::new( "safekeeper_collect_timeline_metrics_seconds", "Time spent collecting timeline metrics, including obtaining mutex lock for all timelines", ) .unwrap(); descs.extend(collect_timeline_metrics.desc().into_iter().cloned()); let timelines_count = IntGauge::new( "safekeeper_timelines", "Total number of timelines loaded in-memory", ) .unwrap(); descs.extend(timelines_count.desc().into_iter().cloned()); let active_timelines_count = IntGauge::new( "safekeeper_active_timelines", "Total number of active timelines", ) .unwrap(); descs.extend(active_timelines_count.desc().into_iter().cloned()); let interpreted_wal_reader_tasks = GenericGaugeVec::new( Opts::new( "safekeeper_interpreted_wal_reader_tasks", "Number of active interpreted wal reader tasks, grouped by timeline", ), &["tenant_id", "timeline_id"], ) .unwrap(); descs.extend(interpreted_wal_reader_tasks.desc().into_iter().cloned()); TimelineCollector { global_timelines, descs, commit_lsn, backup_lsn, flush_lsn, epoch_start_lsn, peer_horizon_lsn, remote_consistent_lsn, ps_last_received_lsn, feedback_last_time_seconds, ps_feedback_count, ps_corruption_detected, timeline_active, wal_backup_active, connected_computes, disk_usage, acceptor_term, written_wal_bytes, written_wal_seconds, flushed_wal_seconds, collect_timeline_metrics, timelines_count, active_timelines_count, interpreted_wal_reader_tasks, } } } impl Collector for TimelineCollector { fn desc(&self) -> Vec<&Desc> { self.descs.iter().collect() } fn collect(&self) -> Vec<MetricFamily> { let start_collecting = Instant::now(); // reset all metrics to clean up inactive timelines self.commit_lsn.reset(); self.backup_lsn.reset(); self.flush_lsn.reset(); self.epoch_start_lsn.reset(); self.peer_horizon_lsn.reset(); self.remote_consistent_lsn.reset(); self.ps_last_received_lsn.reset(); self.feedback_last_time_seconds.reset(); self.ps_feedback_count.reset(); self.timeline_active.reset(); self.wal_backup_active.reset(); self.connected_computes.reset(); self.disk_usage.reset(); self.acceptor_term.reset(); self.written_wal_bytes.reset(); self.interpreted_wal_reader_tasks.reset(); self.written_wal_seconds.reset(); self.flushed_wal_seconds.reset(); let timelines_count = self.global_timelines.get_all().len(); let mut active_timelines_count = 0; // Prometheus Collector is sync, and data is stored under async lock. To // bridge the gap with a crutch, collect data in spawned thread with // local tokio runtime. let global_timelines = self.global_timelines.clone(); let infos = std::thread::spawn(|| { let rt = tokio::runtime::Builder::new_current_thread() .build() .expect("failed to create rt"); rt.block_on(collect_timeline_metrics(global_timelines)) }) .join() .expect("collect_timeline_metrics thread panicked"); for tli in &infos { let tenant_id = tli.ttid.tenant_id.to_string(); let timeline_id = tli.ttid.timeline_id.to_string(); let labels = &[tenant_id.as_str(), timeline_id.as_str()]; if tli.timeline_is_active { active_timelines_count += 1; } self.commit_lsn .with_label_values(labels) .set(tli.mem_state.commit_lsn.into()); self.backup_lsn .with_label_values(labels) .set(tli.mem_state.backup_lsn.into()); self.flush_lsn .with_label_values(labels) .set(tli.flush_lsn.into()); self.epoch_start_lsn .with_label_values(labels) .set(tli.epoch_start_lsn.into()); self.peer_horizon_lsn .with_label_values(labels) .set(tli.mem_state.peer_horizon_lsn.into()); self.remote_consistent_lsn .with_label_values(labels) .set(tli.mem_state.remote_consistent_lsn.into()); self.timeline_active .with_label_values(labels) .set(tli.timeline_is_active as u64); self.wal_backup_active .with_label_values(labels) .set(tli.wal_backup_active as u64); self.connected_computes .with_label_values(labels) .set(tli.num_computes as i64); self.acceptor_term .with_label_values(labels) .set(tli.persisted_state.acceptor_state.term); self.written_wal_bytes .with_label_values(labels) .set(tli.wal_storage.write_wal_bytes); self.interpreted_wal_reader_tasks .with_label_values(labels)
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/send_interpreted_wal.rs
safekeeper/src/send_interpreted_wal.rs
use std::collections::HashMap; use std::fmt::Display; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::time::Duration; use anyhow::{Context, anyhow}; use futures::StreamExt; use futures::future::Either; use pageserver_api::shard::ShardIdentity; use postgres_backend::{CopyStreamHandlerEnd, PostgresBackend}; use postgres_ffi::waldecoder::{WalDecodeError, WalStreamDecoder}; use postgres_ffi::{PgMajorVersion, get_current_timestamp}; use pq_proto::{BeMessage, InterpretedWalRecordsBody, WalSndKeepAlive}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::sync::mpsc::error::SendError; use tokio::task::JoinHandle; use tokio::time::MissedTickBehavior; use tracing::{Instrument, error, info, info_span}; use utils::critical_timeline; use utils::lsn::Lsn; use utils::postgres_client::{Compression, InterpretedFormat}; use wal_decoder::models::{InterpretedWalRecord, InterpretedWalRecords}; use wal_decoder::wire_format::ToWireFormat; use crate::metrics::WAL_READERS; use crate::send_wal::{EndWatchView, WalSenderGuard}; use crate::timeline::WalResidentTimeline; use crate::wal_reader_stream::{StreamingWalReader, WalBytes}; /// Identifier used to differentiate between senders of the same /// shard. /// /// In the steady state there's only one, but two pageservers may /// temporarily have the same shard attached and attempt to ingest /// WAL for it. See also [`ShardSenderId`]. #[derive(Hash, Eq, PartialEq, Copy, Clone)] struct SenderId(u8); impl SenderId { fn first() -> Self { SenderId(0) } fn next(&self) -> Self { SenderId(self.0.checked_add(1).expect("few senders")) } } #[derive(Hash, Eq, PartialEq)] struct ShardSenderId { shard: ShardIdentity, sender_id: SenderId, } impl Display for ShardSenderId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.sender_id.0, self.shard.shard_slug()) } } impl ShardSenderId { fn new(shard: ShardIdentity, sender_id: SenderId) -> Self { ShardSenderId { shard, sender_id } } fn shard(&self) -> ShardIdentity { self.shard } } /// Shard-aware fan-out interpreted record reader. /// Reads WAL from disk, decodes it, intepretets it, and sends /// it to any [`InterpretedWalSender`] connected to it. /// Each [`InterpretedWalSender`] corresponds to one shard /// and gets interpreted records concerning that shard only. pub(crate) struct InterpretedWalReader { wal_stream: StreamingWalReader, shard_senders: HashMap<ShardIdentity, smallvec::SmallVec<[ShardSenderState; 1]>>, shard_notification_rx: Option<tokio::sync::mpsc::UnboundedReceiver<AttachShardNotification>>, state: Arc<std::sync::RwLock<InterpretedWalReaderState>>, pg_version: PgMajorVersion, } /// A handle for [`InterpretedWalReader`] which allows for interacting with it /// when it runs as a separate tokio task. #[derive(Debug)] pub(crate) struct InterpretedWalReaderHandle { join_handle: JoinHandle<Result<(), InterpretedWalReaderError>>, state: Arc<std::sync::RwLock<InterpretedWalReaderState>>, shard_notification_tx: tokio::sync::mpsc::UnboundedSender<AttachShardNotification>, } struct ShardSenderState { sender_id: SenderId, tx: tokio::sync::mpsc::Sender<Batch>, next_record_lsn: Lsn, } /// State of [`InterpretedWalReader`] visible outside of the task running it. #[derive(Debug)] pub(crate) enum InterpretedWalReaderState { Running { current_position: Lsn, /// Tracks the start of the PG WAL LSN from which the current batch of /// interpreted records originated. current_batch_wal_start: Option<Lsn>, }, Done, } pub(crate) struct Batch { wal_end_lsn: Lsn, available_wal_end_lsn: Lsn, records: InterpretedWalRecords, } #[derive(thiserror::Error, Debug)] pub enum InterpretedWalReaderError { /// Handler initiates the end of streaming. #[error("decode error: {0}")] Decode(#[from] WalDecodeError), #[error("read or interpret error: {0}")] ReadOrInterpret(#[from] anyhow::Error), #[error("wal stream closed")] WalStreamClosed, } enum CurrentPositionUpdate { Reset { from: Lsn, to: Lsn }, NotReset(Lsn), } impl CurrentPositionUpdate { fn current_position(&self) -> Lsn { match self { CurrentPositionUpdate::Reset { from: _, to } => *to, CurrentPositionUpdate::NotReset(lsn) => *lsn, } } fn previous_position(&self) -> Lsn { match self { CurrentPositionUpdate::Reset { from, to: _ } => *from, CurrentPositionUpdate::NotReset(lsn) => *lsn, } } } impl InterpretedWalReaderState { fn current_position(&self) -> Option<Lsn> { match self { InterpretedWalReaderState::Running { current_position, .. } => Some(*current_position), InterpretedWalReaderState::Done => None, } } #[cfg(test)] fn current_batch_wal_start(&self) -> Option<Lsn> { match self { InterpretedWalReaderState::Running { current_batch_wal_start, .. } => *current_batch_wal_start, InterpretedWalReaderState::Done => None, } } // Reset the current position of the WAL reader if the requested starting position // of the new shard is smaller than the current value. fn maybe_reset(&mut self, new_shard_start_pos: Lsn) -> CurrentPositionUpdate { match self { InterpretedWalReaderState::Running { current_position, current_batch_wal_start, } => { if new_shard_start_pos < *current_position { let from = *current_position; *current_position = new_shard_start_pos; *current_batch_wal_start = None; CurrentPositionUpdate::Reset { from, to: *current_position, } } else { // Edge case: The new shard is at the same current position as // the reader. Note that the current position is WAL record aligned, // so the reader might have done some partial reads and updated the // batch start. If that's the case, adjust the batch start to match // starting position of the new shard. It can lead to some shards // seeing overlaps, but in that case the actual record LSNs are checked // which should be fine based on the filtering logic. if let Some(start) = current_batch_wal_start { *start = std::cmp::min(*start, new_shard_start_pos); } CurrentPositionUpdate::NotReset(*current_position) } } InterpretedWalReaderState::Done => { panic!("maybe_reset called on finished reader") } } } fn update_current_batch_wal_start(&mut self, lsn: Lsn) { match self { InterpretedWalReaderState::Running { current_batch_wal_start, .. } => { if current_batch_wal_start.is_none() { *current_batch_wal_start = Some(lsn); } } InterpretedWalReaderState::Done => { panic!("update_current_batch_wal_start called on finished reader") } } } fn replace_current_batch_wal_start(&mut self, with: Lsn) -> Lsn { match self { InterpretedWalReaderState::Running { current_batch_wal_start, .. } => current_batch_wal_start.replace(with).unwrap(), InterpretedWalReaderState::Done => { panic!("take_current_batch_wal_start called on finished reader") } } } fn update_current_position(&mut self, lsn: Lsn) { match self { InterpretedWalReaderState::Running { current_position, .. } => { *current_position = lsn; } InterpretedWalReaderState::Done => { panic!("update_current_position called on finished reader") } } } } pub(crate) struct AttachShardNotification { shard_id: ShardIdentity, sender: tokio::sync::mpsc::Sender<Batch>, start_pos: Lsn, } impl InterpretedWalReader { /// Spawn the reader in a separate tokio task and return a handle pub(crate) fn spawn( wal_stream: StreamingWalReader, start_pos: Lsn, tx: tokio::sync::mpsc::Sender<Batch>, shard: ShardIdentity, pg_version: PgMajorVersion, appname: &Option<String>, ) -> InterpretedWalReaderHandle { let state = Arc::new(std::sync::RwLock::new(InterpretedWalReaderState::Running { current_position: start_pos, current_batch_wal_start: None, })); let (shard_notification_tx, shard_notification_rx) = tokio::sync::mpsc::unbounded_channel(); let ttid = wal_stream.ttid; let reader = InterpretedWalReader { wal_stream, shard_senders: HashMap::from([( shard, smallvec::smallvec![ShardSenderState { sender_id: SenderId::first(), tx, next_record_lsn: start_pos, }], )]), shard_notification_rx: Some(shard_notification_rx), state: state.clone(), pg_version, }; let metric = WAL_READERS .get_metric_with_label_values(&["task", appname.as_deref().unwrap_or("safekeeper")]) .unwrap(); let join_handle = tokio::task::spawn( async move { metric.inc(); scopeguard::defer! { metric.dec(); } reader .run_impl(start_pos) .await .inspect_err(|err| match err { // TODO: we may want to differentiate these errors further. InterpretedWalReaderError::Decode(_) => { critical_timeline!( ttid.tenant_id, ttid.timeline_id, // Hadron: The corruption flag is only used in PS so that it can feed this information back to SKs. // We do not use these flags in SKs. None::<&AtomicBool>, "failed to read WAL record: {err:?}" ); } err => error!("failed to read WAL record: {err}"), }) } .instrument(info_span!("interpreted wal reader")), ); InterpretedWalReaderHandle { join_handle, state, shard_notification_tx, } } /// Construct the reader without spawning anything /// Callers should drive the future returned by [`Self::run`]. pub(crate) fn new( wal_stream: StreamingWalReader, start_pos: Lsn, tx: tokio::sync::mpsc::Sender<Batch>, shard: ShardIdentity, pg_version: PgMajorVersion, shard_notification_rx: Option< tokio::sync::mpsc::UnboundedReceiver<AttachShardNotification>, >, ) -> InterpretedWalReader { let state = Arc::new(std::sync::RwLock::new(InterpretedWalReaderState::Running { current_position: start_pos, current_batch_wal_start: None, })); InterpretedWalReader { wal_stream, shard_senders: HashMap::from([( shard, smallvec::smallvec![ShardSenderState { sender_id: SenderId::first(), tx, next_record_lsn: start_pos, }], )]), shard_notification_rx, state: state.clone(), pg_version, } } /// Entry point for future (polling) based wal reader. pub(crate) async fn run( self, start_pos: Lsn, appname: &Option<String>, ) -> Result<(), CopyStreamHandlerEnd> { let metric = WAL_READERS .get_metric_with_label_values(&["future", appname.as_deref().unwrap_or("safekeeper")]) .unwrap(); metric.inc(); scopeguard::defer! { metric.dec(); } let ttid = self.wal_stream.ttid; match self.run_impl(start_pos).await { Err(err @ InterpretedWalReaderError::Decode(_)) => { critical_timeline!( ttid.tenant_id, ttid.timeline_id, // Hadron: The corruption flag is only used in PS so that it can feed this information back to SKs. // We do not use these flags in SKs. None::<&AtomicBool>, "failed to decode WAL record: {err:?}" ); } Err(err) => error!("failed to read WAL record: {err}"), Ok(()) => info!("interpreted wal reader exiting"), } Err(CopyStreamHandlerEnd::Other(anyhow!( "interpreted wal reader finished" ))) } /// Send interpreted WAL to one or more [`InterpretedWalSender`]s /// Stops when an error is encountered or when the [`InterpretedWalReaderHandle`] /// goes out of scope. async fn run_impl(mut self, start_pos: Lsn) -> Result<(), InterpretedWalReaderError> { let defer_state = self.state.clone(); scopeguard::defer! { *defer_state.write().unwrap() = InterpretedWalReaderState::Done; } let mut wal_decoder = WalStreamDecoder::new(start_pos, self.pg_version); loop { tokio::select! { // Main branch for reading WAL and forwarding it wal_or_reset = self.wal_stream.next() => { let wal = wal_or_reset.map(|wor| wor.get_wal().expect("reset handled in select branch below")); let WalBytes { wal, wal_start_lsn, wal_end_lsn, available_wal_end_lsn, } = match wal { Some(some) => some.map_err(InterpretedWalReaderError::ReadOrInterpret)?, None => { // [`StreamingWalReader::next`] is an endless stream of WAL. // It shouldn't ever finish unless it panicked or became internally // inconsistent. return Result::Err(InterpretedWalReaderError::WalStreamClosed); } }; self.state.write().unwrap().update_current_batch_wal_start(wal_start_lsn); wal_decoder.feed_bytes(&wal); // Deserialize and interpret WAL records from this batch of WAL. // Interpreted records for each shard are collected separately. let shard_ids = self.shard_senders.keys().copied().collect::<Vec<_>>(); let mut records_by_sender: HashMap<ShardSenderId, Vec<InterpretedWalRecord>> = HashMap::new(); let mut max_next_record_lsn = None; let mut max_end_record_lsn = None; while let Some((next_record_lsn, recdata)) = wal_decoder.poll_decode()? { assert!(next_record_lsn.is_aligned()); max_next_record_lsn = Some(next_record_lsn); max_end_record_lsn = Some(wal_decoder.lsn()); let interpreted = InterpretedWalRecord::from_bytes_filtered( recdata, &shard_ids, next_record_lsn, self.pg_version, ) .with_context(|| "Failed to interpret WAL")?; for (shard, record) in interpreted { // Shard zero needs to track the start LSN of the latest record // in adition to the LSN of the next record to ingest. The former // is included in basebackup persisted by the compute in WAL. if !shard.is_shard_zero() && record.is_empty() { continue; } let mut states_iter = self.shard_senders .get(&shard) .expect("keys collected above") .iter() .filter(|state| record.next_record_lsn > state.next_record_lsn) .peekable(); while let Some(state) = states_iter.next() { let shard_sender_id = ShardSenderId::new(shard, state.sender_id); // The most commont case is one sender per shard. Peek and break to avoid the // clone in that situation. if states_iter.peek().is_none() { records_by_sender.entry(shard_sender_id).or_default().push(record); break; } else { records_by_sender.entry(shard_sender_id).or_default().push(record.clone()); } } } } let max_next_record_lsn = match max_next_record_lsn { Some(lsn) => lsn, None => { continue; } }; // Update the current position such that new receivers can decide // whether to attach to us or spawn a new WAL reader. let batch_wal_start_lsn = { let mut guard = self.state.write().unwrap(); guard.update_current_position(max_next_record_lsn); guard.replace_current_batch_wal_start(max_end_record_lsn.unwrap()) }; // Send interpreted records downstream. Anything that has already been seen // by a shard is filtered out. let mut shard_senders_to_remove = Vec::new(); for (shard, states) in &mut self.shard_senders { for state in states { let shard_sender_id = ShardSenderId::new(*shard, state.sender_id); let batch = if max_next_record_lsn > state.next_record_lsn { // This batch contains at least one record that this shard has not // seen yet. let records = records_by_sender.remove(&shard_sender_id).unwrap_or_default(); InterpretedWalRecords { records, next_record_lsn: max_next_record_lsn, raw_wal_start_lsn: Some(batch_wal_start_lsn), } } else if wal_end_lsn > state.next_record_lsn { // All the records in this batch were seen by the shard // However, the batch maps to a chunk of WAL that the // shard has not yet seen. Notify it of the start LSN // of the PG WAL chunk such that it doesn't look like a gap. InterpretedWalRecords { records: Vec::default(), next_record_lsn: state.next_record_lsn, raw_wal_start_lsn: Some(batch_wal_start_lsn), } } else { // The shard has seen this chunk of WAL before. Skip it. continue; }; let res = state.tx.send(Batch { wal_end_lsn, available_wal_end_lsn, records: batch, }).await; if res.is_err() { shard_senders_to_remove.push(shard_sender_id); } else { state.next_record_lsn = std::cmp::max(state.next_record_lsn, max_next_record_lsn); } } } // Clean up any shard senders that have dropped out. // This is inefficient, but such events are rare (connection to PS termination) // and the number of subscriptions on the same shards very small (only one // for the steady state). for to_remove in shard_senders_to_remove { let shard_senders = self.shard_senders.get_mut(&to_remove.shard()).expect("saw it above"); if let Some(idx) = shard_senders.iter().position(|s| s.sender_id == to_remove.sender_id) { shard_senders.remove(idx); tracing::info!("Removed shard sender {}", to_remove); } if shard_senders.is_empty() { self.shard_senders.remove(&to_remove.shard()); } } }, // Listen for new shards that want to attach to this reader. // If the reader is not running as a task, then this is not supported // (see the pending branch below). notification = match self.shard_notification_rx.as_mut() { Some(rx) => Either::Left(rx.recv()), None => Either::Right(std::future::pending()) } => { if let Some(n) = notification { let AttachShardNotification { shard_id, sender, start_pos } = n; // Update internal and external state, then reset the WAL stream // if required. let senders = self.shard_senders.entry(shard_id).or_default(); // Clean up any shard senders that have dropped out before adding the new // one. This avoids a build up of dead senders. senders.retain(|sender| { let closed = sender.tx.is_closed(); if closed { let sender_id = ShardSenderId::new(shard_id, sender.sender_id); tracing::info!("Removed shard sender {}", sender_id); } !closed }); let new_sender_id = match senders.last() { Some(sender) => sender.sender_id.next(), None => SenderId::first() }; senders.push(ShardSenderState { sender_id: new_sender_id, tx: sender, next_record_lsn: start_pos}); // If the shard is subscribing below the current position the we need // to update the cursor that tracks where we are at in the WAL // ([`Self::state`]) and reset the WAL stream itself // (`[Self::wal_stream`]). This must be done atomically from the POV of // anything outside the select statement. let position_reset = self.state.write().unwrap().maybe_reset(start_pos); match position_reset { CurrentPositionUpdate::Reset { from: _, to } => { self.wal_stream.reset(to).await; wal_decoder = WalStreamDecoder::new(to, self.pg_version); }, CurrentPositionUpdate::NotReset(_) => {} }; tracing::info!( "Added shard sender {} with start_pos={} previous_pos={} current_pos={}", ShardSenderId::new(shard_id, new_sender_id), start_pos, position_reset.previous_position(), position_reset.current_position(), ); } } } } } #[cfg(test)] fn state(&self) -> Arc<std::sync::RwLock<InterpretedWalReaderState>> { self.state.clone() } } impl InterpretedWalReaderHandle { /// Fan-out the reader by attaching a new shard to it pub(crate) fn fanout( &self, shard_id: ShardIdentity, sender: tokio::sync::mpsc::Sender<Batch>, start_pos: Lsn, ) -> Result<(), SendError<AttachShardNotification>> { self.shard_notification_tx.send(AttachShardNotification { shard_id, sender, start_pos, }) } /// Get the current WAL position of the reader pub(crate) fn current_position(&self) -> Option<Lsn> { self.state.read().unwrap().current_position() } pub(crate) fn abort(&self) { self.join_handle.abort() } } impl Drop for InterpretedWalReaderHandle { fn drop(&mut self) { tracing::info!("Aborting interpreted wal reader"); self.abort() } } pub(crate) struct InterpretedWalSender<'a, IO> { pub(crate) format: InterpretedFormat, pub(crate) compression: Option<Compression>, pub(crate) appname: Option<String>, pub(crate) tli: WalResidentTimeline, pub(crate) start_lsn: Lsn, pub(crate) pgb: &'a mut PostgresBackend<IO>, pub(crate) end_watch_view: EndWatchView, pub(crate) wal_sender_guard: Arc<WalSenderGuard>, pub(crate) rx: tokio::sync::mpsc::Receiver<Batch>, } impl<IO: AsyncRead + AsyncWrite + Unpin> InterpretedWalSender<'_, IO> { /// Send interpreted WAL records over the network. /// Also manages keep-alives if nothing was sent for a while. pub(crate) async fn run(mut self) -> Result<(), CopyStreamHandlerEnd> { let mut keepalive_ticker = tokio::time::interval(Duration::from_secs(1)); keepalive_ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); keepalive_ticker.reset(); let mut wal_position = self.start_lsn; loop { tokio::select! { batch = self.rx.recv() => { let batch = match batch { Some(b) => b, None => { return Result::Err( CopyStreamHandlerEnd::Other(anyhow!("Interpreted WAL reader exited early")) ); } }; wal_position = batch.wal_end_lsn; let buf = batch .records .to_wire(self.format, self.compression) .await .with_context(|| "Failed to serialize interpreted WAL") .map_err(CopyStreamHandlerEnd::from)?; // Reset the keep alive ticker since we are sending something // over the wire now. keepalive_ticker.reset(); self.pgb .write_message(&BeMessage::InterpretedWalRecords(InterpretedWalRecordsBody { streaming_lsn: batch.wal_end_lsn.0, commit_lsn: batch.available_wal_end_lsn.0, data: &buf, })).await?; } // Send a periodic keep alive when the connection has been idle for a while. // Since we've been idle, also check if we can stop streaming. _ = keepalive_ticker.tick() => { if let Some(remote_consistent_lsn) = self.wal_sender_guard .walsenders() .get_ws_remote_consistent_lsn(self.wal_sender_guard.id()) { if self.tli.should_walsender_stop(remote_consistent_lsn).await { // Stop streaming if the receivers are caught up and // there's no active compute. This causes the loop in // [`crate::send_interpreted_wal::InterpretedWalSender::run`] // to exit and terminate the WAL stream. break; } } self.pgb .write_message(&BeMessage::KeepAlive(WalSndKeepAlive { wal_end: self.end_watch_view.get().0, timestamp: get_current_timestamp(), request_reply: true, })) .await?; }, } } Err(CopyStreamHandlerEnd::ServerInitiated(format!( "ending streaming to {:?} at {}, receiver is caughtup and there is no computes", self.appname, wal_position, ))) } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::str::FromStr; use std::time::Duration; use pageserver_api::shard::{DEFAULT_STRIPE_SIZE, ShardIdentity}; use postgres_ffi::{MAX_SEND_SIZE, PgMajorVersion}; use tokio::sync::mpsc::error::TryRecvError; use utils::id::{NodeId, TenantTimelineId}; use utils::lsn::Lsn; use utils::shard::{ShardCount, ShardNumber}; use crate::send_interpreted_wal::{AttachShardNotification, Batch, InterpretedWalReader}; use crate::test_utils::Env; use crate::wal_reader_stream::StreamingWalReader; #[tokio::test] async fn test_interpreted_wal_reader_fanout() { let _ = env_logger::builder().is_test(true).try_init(); const SIZE: usize = 8 * 1024; const MSG_COUNT: usize = 200; const PG_VERSION: PgMajorVersion = PgMajorVersion::PG17; const SHARD_COUNT: u8 = 2; let start_lsn = Lsn::from_str("0/149FD18").unwrap(); let env = Env::new(true).unwrap(); let tli = env .make_timeline(NodeId(1), TenantTimelineId::generate(), start_lsn) .await .unwrap(); let resident_tli = tli.wal_residence_guard().await.unwrap(); let end_watch = Env::write_wal(tli, start_lsn, SIZE, MSG_COUNT, c"neon-file:", None) .await .unwrap(); let end_pos = end_watch.get(); tracing::info!("Doing first round of reads ..."); let streaming_wal_reader = StreamingWalReader::new( resident_tli, None, start_lsn, end_pos, end_watch, MAX_SEND_SIZE, ); let shard_0 = ShardIdentity::new(ShardNumber(0), ShardCount(SHARD_COUNT), DEFAULT_STRIPE_SIZE) .unwrap(); let shard_1 = ShardIdentity::new(ShardNumber(1), ShardCount(SHARD_COUNT), DEFAULT_STRIPE_SIZE) .unwrap(); let mut shards = HashMap::new(); for shard_number in 0..SHARD_COUNT { let shard_id = ShardIdentity::new( ShardNumber(shard_number), ShardCount(SHARD_COUNT), DEFAULT_STRIPE_SIZE, ) .unwrap(); let (tx, rx) = tokio::sync::mpsc::channel::<Batch>(MSG_COUNT * 2); shards.insert(shard_id, (Some(tx), Some(rx))); }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
true
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/broker.rs
safekeeper/src/broker.rs
//! Communication with the broker, providing safekeeper peers and pageserver coordination. use std::sync::Arc; use std::sync::atomic::AtomicU64; use std::time::{Duration, Instant, UNIX_EPOCH}; use anyhow::{Context, Error, Result, anyhow, bail}; use storage_broker::proto::subscribe_safekeeper_info_request::SubscriptionKey as ProtoSubscriptionKey; use storage_broker::proto::{ FilterTenantTimelineId, MessageType, SafekeeperDiscoveryResponse, SubscribeByFilterRequest, SubscribeSafekeeperInfoRequest, TypeSubscription, TypedMessage, }; use storage_broker::{Request, parse_proto_ttid}; use tokio::task::JoinHandle; use tokio::time::sleep; use tracing::*; use crate::metrics::{ BROKER_ITERATION_TIMELINES, BROKER_PULLED_UPDATES, BROKER_PUSH_ALL_UPDATES_SECONDS, BROKER_PUSHED_UPDATES, }; use crate::{GlobalTimelines, SafeKeeperConf}; const RETRY_INTERVAL_MSEC: u64 = 1000; const PUSH_INTERVAL_MSEC: u64 = 1000; fn make_tls_config(conf: &SafeKeeperConf) -> storage_broker::ClientTlsConfig { storage_broker::ClientTlsConfig::new().ca_certificates( conf.ssl_ca_certs .iter() .map(pem::encode) .map(storage_broker::Certificate::from_pem), ) } /// Push once in a while data about all active timelines to the broker. async fn push_loop( conf: Arc<SafeKeeperConf>, global_timelines: Arc<GlobalTimelines>, ) -> anyhow::Result<()> { if conf.disable_periodic_broker_push { info!("broker push_loop is disabled, doing nothing..."); futures::future::pending::<()>().await; // sleep forever return Ok(()); } let active_timelines_set = global_timelines.get_global_broker_active_set(); let mut client = storage_broker::connect( conf.broker_endpoint.clone(), conf.broker_keepalive_interval, make_tls_config(&conf), )?; let push_interval = Duration::from_millis(PUSH_INTERVAL_MSEC); let outbound = async_stream::stream! { loop { // Note: we lock runtime here and in timeline methods as GlobalTimelines // is under plain mutex. That's ok, all this code is not performance // sensitive and there is no risk of deadlock as we don't await while // lock is held. let now = Instant::now(); let all_tlis = active_timelines_set.get_all(); let mut n_pushed_tlis = 0; for tli in &all_tlis { let sk_info = tli.get_safekeeper_info(&conf).await; yield sk_info; BROKER_PUSHED_UPDATES.inc(); n_pushed_tlis += 1; } let elapsed = now.elapsed(); BROKER_PUSH_ALL_UPDATES_SECONDS.observe(elapsed.as_secs_f64()); BROKER_ITERATION_TIMELINES.observe(n_pushed_tlis as f64); if elapsed > push_interval / 2 { info!("broker push is too long, pushed {} timeline updates to broker in {:?}", n_pushed_tlis, elapsed); } sleep(push_interval).await; } }; client .publish_safekeeper_info(Request::new(outbound)) .await?; Ok(()) } /// Subscribe and fetch all the interesting data from the broker. #[instrument(name = "broker_pull", skip_all)] async fn pull_loop( conf: Arc<SafeKeeperConf>, global_timelines: Arc<GlobalTimelines>, stats: Arc<BrokerStats>, ) -> Result<()> { let mut client = storage_broker::connect( conf.broker_endpoint.clone(), conf.broker_keepalive_interval, make_tls_config(&conf), )?; // TODO: subscribe only to local timelines instead of all let request = SubscribeSafekeeperInfoRequest { subscription_key: Some(ProtoSubscriptionKey::All(())), }; let mut stream = client .subscribe_safekeeper_info(request) .await .context("subscribe_safekeper_info request failed")? .into_inner(); let ok_counter = BROKER_PULLED_UPDATES.with_label_values(&["ok"]); let not_found = BROKER_PULLED_UPDATES.with_label_values(&["not_found"]); let err_counter = BROKER_PULLED_UPDATES.with_label_values(&["error"]); while let Some(msg) = stream.message().await? { stats.update_pulled(); let proto_ttid = msg .tenant_timeline_id .as_ref() .ok_or_else(|| anyhow!("missing tenant_timeline_id"))?; let ttid = parse_proto_ttid(proto_ttid)?; if let Ok(tli) = global_timelines.get(ttid) { // Note that we also receive *our own* info. That's // important, as it is used as an indication of live // connection to the broker. // note: there are blocking operations below, but it's considered fine for now let res = tli.record_safekeeper_info(msg).await; if res.is_ok() { ok_counter.inc(); } else { err_counter.inc(); } res?; } else { not_found.inc(); } } bail!("end of stream"); } /// Process incoming discover requests. This is done in a separate task to avoid /// interfering with the normal pull/push loops. async fn discover_loop( conf: Arc<SafeKeeperConf>, global_timelines: Arc<GlobalTimelines>, stats: Arc<BrokerStats>, ) -> Result<()> { let mut client = storage_broker::connect( conf.broker_endpoint.clone(), conf.broker_keepalive_interval, make_tls_config(&conf), )?; let request = SubscribeByFilterRequest { types: vec![TypeSubscription { r#type: MessageType::SafekeeperDiscoveryRequest as i32, }], tenant_timeline_id: Some(FilterTenantTimelineId { enabled: false, tenant_timeline_id: None, }), }; let mut stream = client .subscribe_by_filter(request) .await .context("subscribe_by_filter request failed")? .into_inner(); let discover_counter = BROKER_PULLED_UPDATES.with_label_values(&["discover"]); while let Some(typed_msg) = stream.message().await? { stats.update_pulled(); match typed_msg.r#type() { MessageType::SafekeeperDiscoveryRequest => { let msg = typed_msg .safekeeper_discovery_request .expect("proto type mismatch from broker message"); let proto_ttid = msg .tenant_timeline_id .as_ref() .ok_or_else(|| anyhow!("missing tenant_timeline_id"))?; let ttid = parse_proto_ttid(proto_ttid)?; if let Ok(tli) = global_timelines.get(ttid) { // we received a discovery request for a timeline we know about discover_counter.inc(); // create and reply with discovery response let sk_info = tli.get_safekeeper_info(&conf).await; let response = SafekeeperDiscoveryResponse { safekeeper_id: sk_info.safekeeper_id, tenant_timeline_id: sk_info.tenant_timeline_id, commit_lsn: sk_info.commit_lsn, safekeeper_connstr: sk_info.safekeeper_connstr, availability_zone: sk_info.availability_zone, standby_horizon: 0, }; // note this is a blocking call client .publish_one(TypedMessage { r#type: MessageType::SafekeeperDiscoveryResponse as i32, safekeeper_timeline_info: None, safekeeper_discovery_request: None, safekeeper_discovery_response: Some(response), }) .await?; } } _ => { warn!( "unexpected message type i32 {}, {:?}", typed_msg.r#type, typed_msg.r#type() ); } } } bail!("end of stream"); } pub async fn task_main( conf: Arc<SafeKeeperConf>, global_timelines: Arc<GlobalTimelines>, ) -> anyhow::Result<()> { info!("started, broker endpoint {:?}", conf.broker_endpoint); let mut ticker = tokio::time::interval(Duration::from_millis(RETRY_INTERVAL_MSEC)); let mut push_handle: Option<JoinHandle<Result<(), Error>>> = None; let mut pull_handle: Option<JoinHandle<Result<(), Error>>> = None; let mut discover_handle: Option<JoinHandle<Result<(), Error>>> = None; let stats = Arc::new(BrokerStats::new()); let stats_task = task_stats(stats.clone()); tokio::pin!(stats_task); // Selecting on JoinHandles requires some squats; is there a better way to // reap tasks individually? // Handling failures in task itself won't catch panic and in Tokio, task's // panic doesn't kill the whole executor, so it is better to do reaping // here. loop { tokio::select! { res = async { push_handle.as_mut().unwrap().await }, if push_handle.is_some() => { // was it panic or normal error? let err = match res { Ok(res_internal) => res_internal.unwrap_err(), Err(err_outer) => err_outer.into(), }; warn!("push task failed: {:?}", err); push_handle = None; }, res = async { pull_handle.as_mut().unwrap().await }, if pull_handle.is_some() => { // was it panic or normal error? match res { Ok(res_internal) => if let Err(err_inner) = res_internal { warn!("pull task failed: {:?}", err_inner); } Err(err_outer) => { warn!("pull task panicked: {:?}", err_outer) } }; pull_handle = None; }, res = async { discover_handle.as_mut().unwrap().await }, if discover_handle.is_some() => { // was it panic or normal error? match res { Ok(res_internal) => if let Err(err_inner) = res_internal { warn!("discover task failed: {:?}", err_inner); } Err(err_outer) => { warn!("discover task panicked: {:?}", err_outer) } }; discover_handle = None; }, _ = ticker.tick() => { if push_handle.is_none() { push_handle = Some(tokio::spawn(push_loop(conf.clone(), global_timelines.clone()))); } if pull_handle.is_none() { pull_handle = Some(tokio::spawn(pull_loop(conf.clone(), global_timelines.clone(), stats.clone()))); } if discover_handle.is_none() { discover_handle = Some(tokio::spawn(discover_loop(conf.clone(), global_timelines.clone(), stats.clone()))); } }, _ = &mut stats_task => {} } } } struct BrokerStats { /// Timestamp of the last received message from the broker. last_pulled_ts: AtomicU64, } impl BrokerStats { fn new() -> Self { BrokerStats { last_pulled_ts: AtomicU64::new(0), } } fn now_millis() -> u64 { std::time::SystemTime::now() .duration_since(UNIX_EPOCH) .expect("time is before epoch") .as_millis() as u64 } /// Update last_pulled timestamp to current time. fn update_pulled(&self) { self.last_pulled_ts .store(Self::now_millis(), std::sync::atomic::Ordering::Relaxed); } } /// Periodically write to logs if there are issues with receiving data from the broker. async fn task_stats(stats: Arc<BrokerStats>) { let warn_duration = Duration::from_secs(10); let mut ticker = tokio::time::interval(warn_duration); loop { tokio::select! { _ = ticker.tick() => { let last_pulled = stats.last_pulled_ts.load(std::sync::atomic::Ordering::SeqCst); if last_pulled == 0 { // no broker updates yet continue; } let now = BrokerStats::now_millis(); if now > last_pulled && now - last_pulled > warn_duration.as_millis() as u64 { let ts = chrono::DateTime::from_timestamp_millis(last_pulled as i64).expect("invalid timestamp"); info!("no broker updates for some time, last update: {:?}", ts); } } } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false
neondatabase/neon
https://github.com/neondatabase/neon/blob/015b1c7cb3259a6fcd5039bc2bd46a462e163ae8/safekeeper/src/handler.rs
safekeeper/src/handler.rs
//! Part of Safekeeper pretending to be Postgres, i.e. handling Postgres //! protocol commands. use std::future::Future; use std::str::{self, FromStr}; use std::sync::Arc; use anyhow::Context; use jsonwebtoken::TokenData; use pageserver_api::models::ShardParameters; use pageserver_api::shard::{ShardIdentity, ShardStripeSize}; use postgres_backend::{PostgresBackend, QueryError}; use postgres_ffi::PG_TLI; use pq_proto::{BeMessage, FeStartupPacket, INT4_OID, RowDescriptor, TEXT_OID}; use regex::Regex; use safekeeper_api::Term; use safekeeper_api::models::ConnectionId; use tokio::io::{AsyncRead, AsyncWrite}; use tracing::{Instrument, debug, info, info_span}; use utils::auth::{Claims, JwtAuth, Scope}; use utils::id::{TenantId, TenantTimelineId, TimelineId}; use utils::lsn::Lsn; use utils::postgres_client::PostgresClientProtocol; use utils::shard::{ShardCount, ShardNumber}; use crate::auth::check_permission; use crate::metrics::{PG_QUERIES_GAUGE, TrafficMetrics}; use crate::timeline::TimelineError; use crate::{GlobalTimelines, SafeKeeperConf}; /// Safekeeper handler of postgres commands pub struct SafekeeperPostgresHandler { pub conf: Arc<SafeKeeperConf>, /// assigned application name pub appname: Option<String>, pub tenant_id: Option<TenantId>, pub timeline_id: Option<TimelineId>, pub ttid: TenantTimelineId, pub shard: Option<ShardIdentity>, pub protocol: Option<PostgresClientProtocol>, /// Unique connection id is logged in spans for observability. pub conn_id: ConnectionId, pub global_timelines: Arc<GlobalTimelines>, /// Auth scope allowed on the connections and public key used to check auth tokens. None if auth is not configured. auth: Option<(Scope, Arc<JwtAuth>)>, claims: Option<Claims>, io_metrics: Option<TrafficMetrics>, } /// Parsed Postgres command. enum SafekeeperPostgresCommand { StartWalPush { proto_version: u32, // Eventually timelines will be always created explicitly by storcon. // This option allows legacy behaviour for compute to do that until we // fully migrate. allow_timeline_creation: bool, }, StartReplication { start_lsn: Lsn, term: Option<Term>, }, IdentifySystem, TimelineStatus, } fn parse_cmd(cmd: &str) -> anyhow::Result<SafekeeperPostgresCommand> { if cmd.starts_with("START_WAL_PUSH") { // Allow additional options in postgres START_REPLICATION style like // START_WAL_PUSH (proto_version '3', allow_timeline_creation 'false'). // Parsing here is very naive and breaks in case of commas or // whitespaces in values, but enough for our purposes. let re = Regex::new(r"START_WAL_PUSH(\s+?\((.*)\))?").unwrap(); let caps = re .captures(cmd) .context(format!("failed to parse START_WAL_PUSH command {cmd}"))?; // capture () content let options = caps.get(2).map(|m| m.as_str()).unwrap_or(""); // default values let mut proto_version = 2; let mut allow_timeline_creation = true; for kvstr in options.split(",") { if kvstr.is_empty() { continue; } let mut kvit = kvstr.split_whitespace(); let key = kvit.next().context(format!( "failed to parse key in kv {kvstr} in command {cmd}" ))?; let value = kvit.next().context(format!( "failed to parse value in kv {kvstr} in command {cmd}" ))?; let value_trimmed = value.trim_matches('\''); if key == "proto_version" { proto_version = value_trimmed.parse::<u32>().context(format!( "failed to parse proto_version value {value} in command {cmd}" ))?; } if key == "allow_timeline_creation" { allow_timeline_creation = value_trimmed.parse::<bool>().context(format!( "failed to parse allow_timeline_creation value {value} in command {cmd}" ))?; } } Ok(SafekeeperPostgresCommand::StartWalPush { proto_version, allow_timeline_creation, }) } else if cmd.starts_with("START_REPLICATION") { let re = Regex::new( // We follow postgres START_REPLICATION LOGICAL options to pass term. r"START_REPLICATION(?: SLOT [^ ]+)?(?: PHYSICAL)? ([[:xdigit:]]+/[[:xdigit:]]+)(?: \(term='(\d+)'\))?", ) .unwrap(); let caps = re .captures(cmd) .context(format!("failed to parse START_REPLICATION command {cmd}"))?; let start_lsn = Lsn::from_str(&caps[1]).context("parse start LSN from START_REPLICATION command")?; let term = if let Some(m) = caps.get(2) { Some(m.as_str().parse::<u64>().context("invalid term")?) } else { None }; Ok(SafekeeperPostgresCommand::StartReplication { start_lsn, term }) } else if cmd.starts_with("IDENTIFY_SYSTEM") { Ok(SafekeeperPostgresCommand::IdentifySystem) } else if cmd.starts_with("TIMELINE_STATUS") { Ok(SafekeeperPostgresCommand::TimelineStatus) } else { anyhow::bail!("unsupported command {cmd}"); } } fn cmd_to_string(cmd: &SafekeeperPostgresCommand) -> &str { match cmd { SafekeeperPostgresCommand::StartWalPush { .. } => "START_WAL_PUSH", SafekeeperPostgresCommand::StartReplication { .. } => "START_REPLICATION", SafekeeperPostgresCommand::TimelineStatus => "TIMELINE_STATUS", SafekeeperPostgresCommand::IdentifySystem => "IDENTIFY_SYSTEM", } } impl<IO: AsyncRead + AsyncWrite + Unpin + Send> postgres_backend::Handler<IO> for SafekeeperPostgresHandler { // tenant_id and timeline_id are passed in connection string params fn startup( &mut self, _pgb: &mut PostgresBackend<IO>, sm: &FeStartupPacket, ) -> Result<(), QueryError> { if let FeStartupPacket::StartupMessage { params, .. } = sm { if let Some(options) = params.options_raw() { let mut shard_count: Option<u8> = None; let mut shard_number: Option<u8> = None; let mut shard_stripe_size: Option<u32> = None; for opt in options { // FIXME `ztenantid` and `ztimelineid` left for compatibility during deploy, // remove these after the PR gets deployed: // https://github.com/neondatabase/neon/pull/2433#discussion_r970005064 match opt.split_once('=') { Some(("protocol", value)) => { self.protocol = Some(serde_json::from_str(value).with_context(|| { format!("Failed to parse {value} as protocol") })?); } Some(("ztenantid", value)) | Some(("tenant_id", value)) => { self.tenant_id = Some(value.parse().with_context(|| { format!("Failed to parse {value} as tenant id") })?); } Some(("ztimelineid", value)) | Some(("timeline_id", value)) => { self.timeline_id = Some(value.parse().with_context(|| { format!("Failed to parse {value} as timeline id") })?); } Some(("availability_zone", client_az)) => { if let Some(metrics) = self.io_metrics.as_ref() { metrics.set_client_az(client_az) } } Some(("shard_count", value)) => { shard_count = Some(value.parse::<u8>().with_context(|| { format!("Failed to parse {value} as shard count") })?); } Some(("shard_number", value)) => { shard_number = Some(value.parse::<u8>().with_context(|| { format!("Failed to parse {value} as shard number") })?); } Some(("shard_stripe_size", value)) => { shard_stripe_size = Some(value.parse::<u32>().with_context(|| { format!("Failed to parse {value} as shard stripe size") })?); } _ => continue, } } match self.protocol() { PostgresClientProtocol::Vanilla => { if shard_count.is_some() || shard_number.is_some() || shard_stripe_size.is_some() { return Err(QueryError::Other(anyhow::anyhow!( "Shard params specified for vanilla protocol" ))); } } PostgresClientProtocol::Interpreted { .. } => { match (shard_count, shard_number, shard_stripe_size) { (Some(count), Some(number), Some(stripe_size)) => { let params = ShardParameters { count: ShardCount(count), stripe_size: ShardStripeSize(stripe_size), }; self.shard = Some(ShardIdentity::from_params(ShardNumber(number), params)); } _ => { return Err(QueryError::Other(anyhow::anyhow!( "Shard params were not specified" ))); } } } } } if let Some(app_name) = params.get("application_name") { self.appname = Some(app_name.to_owned()); if let Some(metrics) = self.io_metrics.as_ref() { metrics.set_app_name(app_name) } } let ttid = TenantTimelineId::new( self.tenant_id.unwrap_or(TenantId::from([0u8; 16])), self.timeline_id.unwrap_or(TimelineId::from([0u8; 16])), ); tracing::Span::current() .record("ttid", tracing::field::display(ttid)) .record( "application_name", tracing::field::debug(self.appname.clone()), ); if let Some(shard) = self.shard.as_ref() { if let Some(slug) = shard.shard_slug().strip_prefix("-") { tracing::Span::current().record("shard", tracing::field::display(slug)); } } Ok(()) } else { Err(QueryError::Other(anyhow::anyhow!( "Safekeeper received unexpected initial message: {sm:?}" ))) } } fn check_auth_jwt( &mut self, _pgb: &mut PostgresBackend<IO>, jwt_response: &[u8], ) -> Result<(), QueryError> { // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT // which requires auth to be present let (allowed_auth_scope, auth) = self .auth .as_ref() .expect("auth_type is configured but .auth of handler is missing"); let data: TokenData<Claims> = auth .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?) .map_err(|e| QueryError::Unauthorized(e.0))?; // The handler might be configured to allow only tenant scope tokens. if matches!(allowed_auth_scope, Scope::Tenant) && !matches!(data.claims.scope, Scope::Tenant) { return Err(QueryError::Unauthorized( "passed JWT token is for full access, but only tenant scope is allowed".into(), )); } if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() { return Err(QueryError::Unauthorized( "jwt token scope is Tenant, but tenant id is missing".into(), )); } debug!( "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}", data.claims.scope, data.claims.tenant_id, ); self.claims = Some(data.claims); Ok(()) } fn process_query( &mut self, pgb: &mut PostgresBackend<IO>, query_string: &str, ) -> impl Future<Output = Result<(), QueryError>> { Box::pin(async move { if query_string .to_ascii_lowercase() .starts_with("set datestyle to ") { // important for debug because psycopg2 executes "SET datestyle TO 'ISO'" on connect pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?; return Ok(()); } let cmd = parse_cmd(query_string)?; let cmd_str = cmd_to_string(&cmd); let _guard = PG_QUERIES_GAUGE.with_label_values(&[cmd_str]).guard(); info!("got query {:?}", query_string); let tenant_id = self.tenant_id.context("tenantid is required")?; let timeline_id = self.timeline_id.context("timelineid is required")?; self.check_permission(Some(tenant_id))?; self.ttid = TenantTimelineId::new(tenant_id, timeline_id); match cmd { SafekeeperPostgresCommand::StartWalPush { proto_version, allow_timeline_creation, } => { self.handle_start_wal_push(pgb, proto_version, allow_timeline_creation) .instrument(info_span!("WAL receiver")) .await } SafekeeperPostgresCommand::StartReplication { start_lsn, term } => { self.handle_start_replication(pgb, start_lsn, term) .instrument(info_span!("WAL sender")) .await } SafekeeperPostgresCommand::IdentifySystem => self.handle_identify_system(pgb).await, SafekeeperPostgresCommand::TimelineStatus => self.handle_timeline_status(pgb).await, } }) } } impl SafekeeperPostgresHandler { pub fn new( conf: Arc<SafeKeeperConf>, conn_id: u32, io_metrics: Option<TrafficMetrics>, auth: Option<(Scope, Arc<JwtAuth>)>, global_timelines: Arc<GlobalTimelines>, ) -> Self { SafekeeperPostgresHandler { conf, appname: None, tenant_id: None, timeline_id: None, ttid: TenantTimelineId::empty(), shard: None, protocol: None, conn_id, claims: None, auth, io_metrics, global_timelines, } } pub fn protocol(&self) -> PostgresClientProtocol { self.protocol.unwrap_or(PostgresClientProtocol::Vanilla) } // when accessing management api supply None as an argument // when using to authorize tenant pass corresponding tenant id fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> { if self.auth.is_none() { // auth is set to Trust, nothing to check so just return ok return Ok(()); } // auth is some, just checked above, when auth is some // then claims are always present because of checks during connection init // so this expect won't trigger let claims = self .claims .as_ref() .expect("claims presence already checked"); check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0)) } async fn handle_timeline_status<IO: AsyncRead + AsyncWrite + Unpin>( &mut self, pgb: &mut PostgresBackend<IO>, ) -> Result<(), QueryError> { // Get timeline, handling "not found" error let tli = match self.global_timelines.get(self.ttid) { Ok(tli) => Ok(Some(tli)), Err(TimelineError::NotFound(_)) => Ok(None), Err(e) => Err(QueryError::Other(e.into())), }?; // Write row description pgb.write_message_noflush(&BeMessage::RowDescription(&[ RowDescriptor::text_col(b"flush_lsn"), RowDescriptor::text_col(b"commit_lsn"), ]))?; // Write row if timeline exists if let Some(tli) = tli { let (inmem, _state) = tli.get_state().await; let flush_lsn = tli.get_flush_lsn().await; let commit_lsn = inmem.commit_lsn; pgb.write_message_noflush(&BeMessage::DataRow(&[ Some(flush_lsn.to_string().as_bytes()), Some(commit_lsn.to_string().as_bytes()), ]))?; } pgb.write_message_noflush(&BeMessage::CommandComplete(b"TIMELINE_STATUS"))?; Ok(()) } /// /// Handle IDENTIFY_SYSTEM replication command /// async fn handle_identify_system<IO: AsyncRead + AsyncWrite + Unpin>( &mut self, pgb: &mut PostgresBackend<IO>, ) -> Result<(), QueryError> { let tli = self .global_timelines .get(self.ttid) .map_err(|e| QueryError::Other(e.into()))?; let lsn = if self.is_walproposer_recovery() { // walproposer should get all local WAL until flush_lsn tli.get_flush_lsn().await } else { // other clients shouldn't get any uncommitted WAL tli.get_state().await.0.commit_lsn } .to_string(); let sysid = tli.get_state().await.1.server.system_id.to_string(); let lsn_bytes = lsn.as_bytes(); let tli = PG_TLI.to_string(); let tli_bytes = tli.as_bytes(); let sysid_bytes = sysid.as_bytes(); pgb.write_message_noflush(&BeMessage::RowDescription(&[ RowDescriptor { name: b"systemid", typoid: TEXT_OID, typlen: -1, ..Default::default() }, RowDescriptor { name: b"timeline", typoid: INT4_OID, typlen: 4, ..Default::default() }, RowDescriptor { name: b"xlogpos", typoid: TEXT_OID, typlen: -1, ..Default::default() }, RowDescriptor { name: b"dbname", typoid: TEXT_OID, typlen: -1, ..Default::default() }, ]))? .write_message_noflush(&BeMessage::DataRow(&[ Some(sysid_bytes), Some(tli_bytes), Some(lsn_bytes), None, ]))? .write_message_noflush(&BeMessage::CommandComplete(b"IDENTIFY_SYSTEM"))?; Ok(()) } /// Returns true if current connection is a replication connection, originating /// from a walproposer recovery function. This connection gets a special handling: /// safekeeper must stream all local WAL till the flush_lsn, whether committed or not. pub fn is_walproposer_recovery(&self) -> bool { match &self.appname { None => false, Some(appname) => { appname == "wal_proposer_recovery" || // set by safekeeper peer recovery appname.starts_with("safekeeper") } } } } #[cfg(test)] mod tests { use super::SafekeeperPostgresCommand; /// Test parsing of START_WAL_PUSH command #[test] fn test_start_wal_push_parse() { let cmd = "START_WAL_PUSH"; let parsed = super::parse_cmd(cmd).expect("failed to parse"); match parsed { SafekeeperPostgresCommand::StartWalPush { proto_version, allow_timeline_creation, } => { assert_eq!(proto_version, 2); assert!(allow_timeline_creation); } _ => panic!("unexpected command"), } let cmd = "START_WAL_PUSH (proto_version '3', allow_timeline_creation 'false', unknown 'hoho')"; let parsed = super::parse_cmd(cmd).expect("failed to parse"); match parsed { SafekeeperPostgresCommand::StartWalPush { proto_version, allow_timeline_creation, } => { assert_eq!(proto_version, 3); assert!(!allow_timeline_creation); } _ => panic!("unexpected command"), } } }
rust
Apache-2.0
015b1c7cb3259a6fcd5039bc2bd46a462e163ae8
2026-01-04T15:40:24.223849Z
false