Line data Source code
1 : //! This program dumps a remote Postgres database into a local Postgres database
2 : //! and uploads the resulting PGDATA into object storage for import into a Timeline.
3 : //!
4 : //! # Context, Architecture, Design
5 : //!
6 : //! See cloud.git Fast Imports RFC (<https://github.com/neondatabase/cloud/pull/19799>)
7 : //! for the full picture.
8 : //! The RFC describing the storage pieces of importing the PGDATA dump into a Timeline
9 : //! is publicly accessible at <https://github.com/neondatabase/neon/pull/9538>.
10 : //!
11 : //! # This is a Prototype!
12 : //!
13 : //! This program is part of a prototype feature and not yet used in production.
14 : //!
15 : //! The cloud.git RFC contains lots of suggestions for improving e2e throughput
16 : //! of this step of the timeline import process.
17 : //!
18 : //! # Local Testing
19 : //!
20 : //! - Comment out most of the pgxns in compute-node.Dockerfile to speed up the build.
21 : //! - Build the image with the following command:
22 : //!
23 : //! ```bash
24 : //! docker buildx build --platform linux/amd64 --build-arg DEBIAN_VERSION=bullseye --build-arg GIT_VERSION=local --build-arg PG_VERSION=v14 --build-arg BUILD_TAG="$(date --iso-8601=s -u)" -t localhost:3030/localregistry/compute-node-v14:latest -f compute/compute-node.Dockerfile .
25 : //! docker push localhost:3030/localregistry/compute-node-v14:latest
26 : //! ```
27 :
28 : use anyhow::Context;
29 : use aws_config::BehaviorVersion;
30 : use camino::{Utf8Path, Utf8PathBuf};
31 : use clap::Parser;
32 : use compute_tools::extension_server::{get_pg_version, PostgresMajorVersion};
33 : use nix::unistd::Pid;
34 : use tracing::{error, info, info_span, warn, Instrument};
35 : use utils::fs_ext::is_directory_empty;
36 :
37 : #[path = "fast_import/aws_s3_sync.rs"]
38 : mod aws_s3_sync;
39 : #[path = "fast_import/child_stdio_to_log.rs"]
40 : mod child_stdio_to_log;
41 : #[path = "fast_import/s3_uri.rs"]
42 : mod s3_uri;
43 :
44 : const PG_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
45 : const PG_WAIT_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(300);
46 :
47 : #[derive(clap::Parser)]
48 : struct Args {
49 : #[clap(long)]
50 0 : working_directory: Utf8PathBuf,
51 : #[clap(long, env = "NEON_IMPORTER_S3_PREFIX")]
52 : s3_prefix: Option<s3_uri::S3Uri>,
53 : #[clap(long)]
54 : source_connection_string: Option<String>,
55 : #[clap(short, long)]
56 0 : interactive: bool,
57 : #[clap(long)]
58 0 : pg_bin_dir: Utf8PathBuf,
59 : #[clap(long)]
60 0 : pg_lib_dir: Utf8PathBuf,
61 : #[clap(long)]
62 : pg_port: Option<u16>, // port to run postgres on, 5432 is default
63 : }
64 :
65 : #[serde_with::serde_as]
66 0 : #[derive(serde::Deserialize)]
67 : struct Spec {
68 : encryption_secret: EncryptionSecret,
69 : #[serde_as(as = "serde_with::base64::Base64")]
70 : source_connstring_ciphertext_base64: Vec<u8>,
71 : }
72 :
73 0 : #[derive(serde::Deserialize)]
74 : enum EncryptionSecret {
75 : #[allow(clippy::upper_case_acronyms)]
76 : KMS { key_id: String },
77 : }
78 :
79 : // copied from pageserver_api::config::defaults::DEFAULT_LOCALE to avoid dependency just for a constant
80 : const DEFAULT_LOCALE: &str = if cfg!(target_os = "macos") {
81 : "C"
82 : } else {
83 : "C.UTF-8"
84 : };
85 :
86 : #[tokio::main]
87 0 : pub(crate) async fn main() -> anyhow::Result<()> {
88 0 : utils::logging::init(
89 0 : utils::logging::LogFormat::Plain,
90 0 : utils::logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
91 0 : utils::logging::Output::Stdout,
92 0 : )?;
93 0 :
94 0 : info!("starting");
95 0 :
96 0 : let args = Args::parse();
97 0 :
98 0 : // Validate arguments
99 0 : if args.s3_prefix.is_none() && args.source_connection_string.is_none() {
100 0 : anyhow::bail!("either s3_prefix or source_connection_string must be specified");
101 0 : }
102 0 : if args.s3_prefix.is_some() && args.source_connection_string.is_some() {
103 0 : anyhow::bail!("only one of s3_prefix or source_connection_string can be specified");
104 0 : }
105 0 :
106 0 : let working_directory = args.working_directory;
107 0 : let pg_bin_dir = args.pg_bin_dir;
108 0 : let pg_lib_dir = args.pg_lib_dir;
109 0 : let pg_port = args.pg_port.unwrap_or_else(|| {
110 0 : info!("pg_port not specified, using default 5432");
111 0 : 5432
112 0 : });
113 0 :
114 0 : // Initialize AWS clients only if s3_prefix is specified
115 0 : let (aws_config, kms_client) = if args.s3_prefix.is_some() {
116 0 : let config = aws_config::load_defaults(BehaviorVersion::v2024_03_28()).await;
117 0 : let kms = aws_sdk_kms::Client::new(&config);
118 0 : (Some(config), Some(kms))
119 0 : } else {
120 0 : (None, None)
121 0 : };
122 0 :
123 0 : // Get source connection string either from S3 spec or direct argument
124 0 : let source_connection_string = if let Some(s3_prefix) = &args.s3_prefix {
125 0 : let spec: Spec = {
126 0 : let spec_key = s3_prefix.append("/spec.json");
127 0 : let s3_client = aws_sdk_s3::Client::new(aws_config.as_ref().unwrap());
128 0 : let object = s3_client
129 0 : .get_object()
130 0 : .bucket(&spec_key.bucket)
131 0 : .key(spec_key.key)
132 0 : .send()
133 0 : .await
134 0 : .context("get spec from s3")?
135 0 : .body
136 0 : .collect()
137 0 : .await
138 0 : .context("download spec body")?;
139 0 : serde_json::from_slice(&object.into_bytes()).context("parse spec as json")?
140 0 : };
141 0 :
142 0 : match spec.encryption_secret {
143 0 : EncryptionSecret::KMS { key_id } => {
144 0 : let mut output = kms_client
145 0 : .unwrap()
146 0 : .decrypt()
147 0 : .key_id(key_id)
148 0 : .ciphertext_blob(aws_sdk_s3::primitives::Blob::new(
149 0 : spec.source_connstring_ciphertext_base64,
150 0 : ))
151 0 : .send()
152 0 : .await
153 0 : .context("decrypt source connection string")?;
154 0 : let plaintext = output
155 0 : .plaintext
156 0 : .take()
157 0 : .context("get plaintext source connection string")?;
158 0 : String::from_utf8(plaintext.into_inner())
159 0 : .context("parse source connection string as utf8")?
160 0 : }
161 0 : }
162 0 : } else {
163 0 : args.source_connection_string.unwrap()
164 0 : };
165 0 :
166 0 : match tokio::fs::create_dir(&working_directory).await {
167 0 : Ok(()) => {}
168 0 : Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
169 0 : if !is_directory_empty(&working_directory)
170 0 : .await
171 0 : .context("check if working directory is empty")?
172 0 : {
173 0 : anyhow::bail!("working directory is not empty");
174 0 : } else {
175 0 : // ok
176 0 : }
177 0 : }
178 0 : Err(e) => return Err(anyhow::Error::new(e).context("create working directory")),
179 0 : }
180 0 :
181 0 : let pgdata_dir = working_directory.join("pgdata");
182 0 : tokio::fs::create_dir(&pgdata_dir)
183 0 : .await
184 0 : .context("create pgdata directory")?;
185 0 :
186 0 : let pgbin = pg_bin_dir.join("postgres");
187 0 : let pg_version = match get_pg_version(pgbin.as_ref()) {
188 0 : PostgresMajorVersion::V14 => 14,
189 0 : PostgresMajorVersion::V15 => 15,
190 0 : PostgresMajorVersion::V16 => 16,
191 0 : PostgresMajorVersion::V17 => 17,
192 0 : };
193 0 : let superuser = "cloud_admin"; // XXX: this shouldn't be hard-coded
194 0 : postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
195 0 : superuser,
196 0 : locale: DEFAULT_LOCALE, // XXX: this shouldn't be hard-coded,
197 0 : pg_version,
198 0 : initdb_bin: pg_bin_dir.join("initdb").as_ref(),
199 0 : library_search_path: &pg_lib_dir, // TODO: is this right? Prob works in compute image, not sure about neon_local.
200 0 : pgdata: &pgdata_dir,
201 0 : })
202 0 : .await
203 0 : .context("initdb")?;
204 0 :
205 0 : let nproc = num_cpus::get();
206 0 :
207 0 : //
208 0 : // Launch postgres process
209 0 : //
210 0 : let mut postgres_proc = tokio::process::Command::new(pgbin)
211 0 : .arg("-D")
212 0 : .arg(&pgdata_dir)
213 0 : .args(["-p", &format!("{pg_port}")])
214 0 : .args(["-c", "wal_level=minimal"])
215 0 : .args(["-c", "shared_buffers=10GB"])
216 0 : .args(["-c", "max_wal_senders=0"])
217 0 : .args(["-c", "fsync=off"])
218 0 : .args(["-c", "full_page_writes=off"])
219 0 : .args(["-c", "synchronous_commit=off"])
220 0 : .args(["-c", "maintenance_work_mem=8388608"])
221 0 : .args(["-c", &format!("max_parallel_maintenance_workers={nproc}")])
222 0 : .args(["-c", &format!("max_parallel_workers={nproc}")])
223 0 : .args(["-c", &format!("max_parallel_workers_per_gather={nproc}")])
224 0 : .args(["-c", &format!("max_worker_processes={nproc}")])
225 0 : .args([
226 0 : "-c",
227 0 : &format!(
228 0 : "effective_io_concurrency={}",
229 0 : if cfg!(target_os = "macos") { 0 } else { 100 }
230 0 : ),
231 0 : ])
232 0 : .env_clear()
233 0 : .env("LD_LIBRARY_PATH", &pg_lib_dir)
234 0 : .stdout(std::process::Stdio::piped())
235 0 : .stderr(std::process::Stdio::piped())
236 0 : .spawn()
237 0 : .context("spawn postgres")?;
238 0 :
239 0 : info!("spawned postgres, waiting for it to become ready");
240 0 : tokio::spawn(
241 0 : child_stdio_to_log::relay_process_output(
242 0 : postgres_proc.stdout.take(),
243 0 : postgres_proc.stderr.take(),
244 0 : )
245 0 : .instrument(info_span!("postgres")),
246 0 : );
247 0 :
248 0 : // Create neondb database in the running postgres
249 0 : let restore_pg_connstring =
250 0 : format!("host=localhost port={pg_port} user={superuser} dbname=postgres");
251 0 :
252 0 : let start_time = std::time::Instant::now();
253 0 :
254 0 : loop {
255 0 : if start_time.elapsed() > PG_WAIT_TIMEOUT {
256 0 : error!(
257 0 : "timeout exceeded: failed to poll postgres and create database within 10 minutes"
258 0 : );
259 0 : std::process::exit(1);
260 0 : }
261 0 :
262 0 : match tokio_postgres::connect(&restore_pg_connstring, tokio_postgres::NoTls).await {
263 0 : Ok((client, connection)) => {
264 0 : // Spawn the connection handling task to maintain the connection
265 0 : tokio::spawn(async move {
266 0 : if let Err(e) = connection.await {
267 0 : warn!("connection error: {}", e);
268 0 : }
269 0 : });
270 0 :
271 0 : match client.simple_query("CREATE DATABASE neondb;").await {
272 0 : Ok(_) => {
273 0 : info!("created neondb database");
274 0 : break;
275 0 : }
276 0 : Err(e) => {
277 0 : warn!(
278 0 : "failed to create database: {}, retying in {}s",
279 0 : e,
280 0 : PG_WAIT_RETRY_INTERVAL.as_secs_f32()
281 0 : );
282 0 : tokio::time::sleep(PG_WAIT_RETRY_INTERVAL).await;
283 0 : continue;
284 0 : }
285 0 : }
286 0 : }
287 0 : Err(_) => {
288 0 : info!(
289 0 : "postgres not ready yet, retrying in {}s",
290 0 : PG_WAIT_RETRY_INTERVAL.as_secs_f32()
291 0 : );
292 0 : tokio::time::sleep(PG_WAIT_RETRY_INTERVAL).await;
293 0 : continue;
294 0 : }
295 0 : }
296 0 : }
297 0 :
298 0 : let restore_pg_connstring = restore_pg_connstring.replace("dbname=postgres", "dbname=neondb");
299 0 :
300 0 : let dumpdir = working_directory.join("dumpdir");
301 0 :
302 0 : let common_args = [
303 0 : // schema mapping (prob suffices to specify them on one side)
304 0 : "--no-owner".to_string(),
305 0 : "--no-privileges".to_string(),
306 0 : "--no-publications".to_string(),
307 0 : "--no-security-labels".to_string(),
308 0 : "--no-subscriptions".to_string(),
309 0 : "--no-tablespaces".to_string(),
310 0 : // format
311 0 : "--format".to_string(),
312 0 : "directory".to_string(),
313 0 : // concurrency
314 0 : "--jobs".to_string(),
315 0 : num_cpus::get().to_string(),
316 0 : // progress updates
317 0 : "--verbose".to_string(),
318 0 : ];
319 0 :
320 0 : info!("dump into the working directory");
321 0 : {
322 0 : let mut pg_dump = tokio::process::Command::new(pg_bin_dir.join("pg_dump"))
323 0 : .args(&common_args)
324 0 : .arg("-f")
325 0 : .arg(&dumpdir)
326 0 : .arg("--no-sync")
327 0 : // POSITIONAL args
328 0 : // source db (db name included in connection string)
329 0 : .arg(&source_connection_string)
330 0 : // how we run it
331 0 : .env_clear()
332 0 : .env("LD_LIBRARY_PATH", &pg_lib_dir)
333 0 : .kill_on_drop(true)
334 0 : .stdout(std::process::Stdio::piped())
335 0 : .stderr(std::process::Stdio::piped())
336 0 : .spawn()
337 0 : .context("spawn pg_dump")?;
338 0 :
339 0 : info!(pid=%pg_dump.id().unwrap(), "spawned pg_dump");
340 0 :
341 0 : tokio::spawn(
342 0 : child_stdio_to_log::relay_process_output(pg_dump.stdout.take(), pg_dump.stderr.take())
343 0 : .instrument(info_span!("pg_dump")),
344 0 : );
345 0 :
346 0 : let st = pg_dump.wait().await.context("wait for pg_dump")?;
347 0 : info!(status=?st, "pg_dump exited");
348 0 : if !st.success() {
349 0 : warn!(status=%st, "pg_dump failed, restore will likely fail as well");
350 0 : }
351 0 : }
352 0 :
353 0 : // TODO: do it in a streaming way, plenty of internal research done on this already
354 0 : // TODO: do the unlogged table trick
355 0 :
356 0 : info!("restore from working directory into vanilla postgres");
357 0 : {
358 0 : let mut pg_restore = tokio::process::Command::new(pg_bin_dir.join("pg_restore"))
359 0 : .args(&common_args)
360 0 : .arg("-d")
361 0 : .arg(&restore_pg_connstring)
362 0 : // POSITIONAL args
363 0 : .arg(&dumpdir)
364 0 : // how we run it
365 0 : .env_clear()
366 0 : .env("LD_LIBRARY_PATH", &pg_lib_dir)
367 0 : .kill_on_drop(true)
368 0 : .stdout(std::process::Stdio::piped())
369 0 : .stderr(std::process::Stdio::piped())
370 0 : .spawn()
371 0 : .context("spawn pg_restore")?;
372 0 :
373 0 : info!(pid=%pg_restore.id().unwrap(), "spawned pg_restore");
374 0 : tokio::spawn(
375 0 : child_stdio_to_log::relay_process_output(
376 0 : pg_restore.stdout.take(),
377 0 : pg_restore.stderr.take(),
378 0 : )
379 0 : .instrument(info_span!("pg_restore")),
380 0 : );
381 0 : let st = pg_restore.wait().await.context("wait for pg_restore")?;
382 0 : info!(status=?st, "pg_restore exited");
383 0 : if !st.success() {
384 0 : warn!(status=%st, "pg_restore failed, restore will likely fail as well");
385 0 : }
386 0 : }
387 0 :
388 0 : // If interactive mode, wait for Ctrl+C
389 0 : if args.interactive {
390 0 : info!("Running in interactive mode. Press Ctrl+C to shut down.");
391 0 : tokio::signal::ctrl_c().await.context("wait for ctrl-c")?;
392 0 : }
393 0 :
394 0 : info!("shutdown postgres");
395 0 : {
396 0 : nix::sys::signal::kill(
397 0 : Pid::from_raw(
398 0 : i32::try_from(postgres_proc.id().unwrap()).expect("convert child pid to i32"),
399 0 : ),
400 0 : nix::sys::signal::SIGTERM,
401 0 : )
402 0 : .context("signal postgres to shut down")?;
403 0 : postgres_proc
404 0 : .wait()
405 0 : .await
406 0 : .context("wait for postgres to shut down")?;
407 0 : }
408 0 :
409 0 : // Only sync if s3_prefix was specified
410 0 : if let Some(s3_prefix) = args.s3_prefix {
411 0 : info!("upload pgdata");
412 0 : aws_s3_sync::sync(Utf8Path::new(&pgdata_dir), &s3_prefix.append("/pgdata/"))
413 0 : .await
414 0 : .context("sync dump directory to destination")?;
415 0 :
416 0 : info!("write status");
417 0 : {
418 0 : let status_dir = working_directory.join("status");
419 0 : std::fs::create_dir(&status_dir).context("create status directory")?;
420 0 : let status_file = status_dir.join("pgdata");
421 0 : std::fs::write(&status_file, serde_json::json!({"done": true}).to_string())
422 0 : .context("write status file")?;
423 0 : aws_s3_sync::sync(&status_dir, &s3_prefix.append("/status/"))
424 0 : .await
425 0 : .context("sync status directory to destination")?;
426 0 : }
427 0 : }
428 0 :
429 0 : Ok(())
430 0 : }
|