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 : }
62 :
63 : #[serde_with::serde_as]
64 0 : #[derive(serde::Deserialize)]
65 : struct Spec {
66 : encryption_secret: EncryptionSecret,
67 : #[serde_as(as = "serde_with::base64::Base64")]
68 : source_connstring_ciphertext_base64: Vec<u8>,
69 : }
70 :
71 0 : #[derive(serde::Deserialize)]
72 : enum EncryptionSecret {
73 : #[allow(clippy::upper_case_acronyms)]
74 : KMS { key_id: String },
75 : }
76 :
77 : #[tokio::main]
78 0 : pub(crate) async fn main() -> anyhow::Result<()> {
79 0 : utils::logging::init(
80 0 : utils::logging::LogFormat::Plain,
81 0 : utils::logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
82 0 : utils::logging::Output::Stdout,
83 0 : )?;
84 0 :
85 0 : info!("starting");
86 0 :
87 0 : let args = Args::parse();
88 0 :
89 0 : // Validate arguments
90 0 : if args.s3_prefix.is_none() && args.source_connection_string.is_none() {
91 0 : anyhow::bail!("either s3_prefix or source_connection_string must be specified");
92 0 : }
93 0 : if args.s3_prefix.is_some() && args.source_connection_string.is_some() {
94 0 : anyhow::bail!("only one of s3_prefix or source_connection_string can be specified");
95 0 : }
96 0 :
97 0 : let working_directory = args.working_directory;
98 0 : let pg_bin_dir = args.pg_bin_dir;
99 0 : let pg_lib_dir = args.pg_lib_dir;
100 0 :
101 0 : // Initialize AWS clients only if s3_prefix is specified
102 0 : let (aws_config, kms_client) = if args.s3_prefix.is_some() {
103 0 : let config = aws_config::load_defaults(BehaviorVersion::v2024_03_28()).await;
104 0 : let kms = aws_sdk_kms::Client::new(&config);
105 0 : (Some(config), Some(kms))
106 0 : } else {
107 0 : (None, None)
108 0 : };
109 0 :
110 0 : // Get source connection string either from S3 spec or direct argument
111 0 : let source_connection_string = if let Some(s3_prefix) = &args.s3_prefix {
112 0 : let spec: Spec = {
113 0 : let spec_key = s3_prefix.append("/spec.json");
114 0 : let s3_client = aws_sdk_s3::Client::new(aws_config.as_ref().unwrap());
115 0 : let object = s3_client
116 0 : .get_object()
117 0 : .bucket(&spec_key.bucket)
118 0 : .key(spec_key.key)
119 0 : .send()
120 0 : .await
121 0 : .context("get spec from s3")?
122 0 : .body
123 0 : .collect()
124 0 : .await
125 0 : .context("download spec body")?;
126 0 : serde_json::from_slice(&object.into_bytes()).context("parse spec as json")?
127 0 : };
128 0 :
129 0 : match spec.encryption_secret {
130 0 : EncryptionSecret::KMS { key_id } => {
131 0 : let mut output = kms_client
132 0 : .unwrap()
133 0 : .decrypt()
134 0 : .key_id(key_id)
135 0 : .ciphertext_blob(aws_sdk_s3::primitives::Blob::new(
136 0 : spec.source_connstring_ciphertext_base64,
137 0 : ))
138 0 : .send()
139 0 : .await
140 0 : .context("decrypt source connection string")?;
141 0 : let plaintext = output
142 0 : .plaintext
143 0 : .take()
144 0 : .context("get plaintext source connection string")?;
145 0 : String::from_utf8(plaintext.into_inner())
146 0 : .context("parse source connection string as utf8")?
147 0 : }
148 0 : }
149 0 : } else {
150 0 : args.source_connection_string.unwrap()
151 0 : };
152 0 :
153 0 : match tokio::fs::create_dir(&working_directory).await {
154 0 : Ok(()) => {}
155 0 : Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
156 0 : if !is_directory_empty(&working_directory)
157 0 : .await
158 0 : .context("check if working directory is empty")?
159 0 : {
160 0 : anyhow::bail!("working directory is not empty");
161 0 : } else {
162 0 : // ok
163 0 : }
164 0 : }
165 0 : Err(e) => return Err(anyhow::Error::new(e).context("create working directory")),
166 0 : }
167 0 :
168 0 : let pgdata_dir = working_directory.join("pgdata");
169 0 : tokio::fs::create_dir(&pgdata_dir)
170 0 : .await
171 0 : .context("create pgdata directory")?;
172 0 :
173 0 : let pgbin = pg_bin_dir.join("postgres");
174 0 : let pg_version = match get_pg_version(pgbin.as_ref()) {
175 0 : PostgresMajorVersion::V14 => 14,
176 0 : PostgresMajorVersion::V15 => 15,
177 0 : PostgresMajorVersion::V16 => 16,
178 0 : PostgresMajorVersion::V17 => 17,
179 0 : };
180 0 : let superuser = "cloud_admin"; // XXX: this shouldn't be hard-coded
181 0 : postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
182 0 : superuser,
183 0 : locale: "en_US.UTF-8", // XXX: this shouldn't be hard-coded,
184 0 : pg_version,
185 0 : initdb_bin: pg_bin_dir.join("initdb").as_ref(),
186 0 : library_search_path: &pg_lib_dir, // TODO: is this right? Prob works in compute image, not sure about neon_local.
187 0 : pgdata: &pgdata_dir,
188 0 : })
189 0 : .await
190 0 : .context("initdb")?;
191 0 :
192 0 : let nproc = num_cpus::get();
193 0 :
194 0 : //
195 0 : // Launch postgres process
196 0 : //
197 0 : let mut postgres_proc = tokio::process::Command::new(pgbin)
198 0 : .arg("-D")
199 0 : .arg(&pgdata_dir)
200 0 : .args(["-c", "wal_level=minimal"])
201 0 : .args(["-c", "shared_buffers=10GB"])
202 0 : .args(["-c", "max_wal_senders=0"])
203 0 : .args(["-c", "fsync=off"])
204 0 : .args(["-c", "full_page_writes=off"])
205 0 : .args(["-c", "synchronous_commit=off"])
206 0 : .args(["-c", "maintenance_work_mem=8388608"])
207 0 : .args(["-c", &format!("max_parallel_maintenance_workers={nproc}")])
208 0 : .args(["-c", &format!("max_parallel_workers={nproc}")])
209 0 : .args(["-c", &format!("max_parallel_workers_per_gather={nproc}")])
210 0 : .args(["-c", &format!("max_worker_processes={nproc}")])
211 0 : .args([
212 0 : "-c",
213 0 : &format!(
214 0 : "effective_io_concurrency={}",
215 0 : if cfg!(target_os = "macos") { 0 } else { 100 }
216 0 : ),
217 0 : ])
218 0 : .env_clear()
219 0 : .stdout(std::process::Stdio::piped())
220 0 : .stderr(std::process::Stdio::piped())
221 0 : .spawn()
222 0 : .context("spawn postgres")?;
223 0 :
224 0 : info!("spawned postgres, waiting for it to become ready");
225 0 : tokio::spawn(
226 0 : child_stdio_to_log::relay_process_output(
227 0 : postgres_proc.stdout.take(),
228 0 : postgres_proc.stderr.take(),
229 0 : )
230 0 : .instrument(info_span!("postgres")),
231 0 : );
232 0 :
233 0 : // Create neondb database in the running postgres
234 0 : let restore_pg_connstring =
235 0 : format!("host=localhost port=5432 user={superuser} dbname=postgres");
236 0 :
237 0 : let start_time = std::time::Instant::now();
238 0 :
239 0 : loop {
240 0 : if start_time.elapsed() > PG_WAIT_TIMEOUT {
241 0 : error!(
242 0 : "timeout exceeded: failed to poll postgres and create database within 10 minutes"
243 0 : );
244 0 : std::process::exit(1);
245 0 : }
246 0 :
247 0 : match tokio_postgres::connect(&restore_pg_connstring, tokio_postgres::NoTls).await {
248 0 : Ok((client, connection)) => {
249 0 : // Spawn the connection handling task to maintain the connection
250 0 : tokio::spawn(async move {
251 0 : if let Err(e) = connection.await {
252 0 : warn!("connection error: {}", e);
253 0 : }
254 0 : });
255 0 :
256 0 : match client.simple_query("CREATE DATABASE neondb;").await {
257 0 : Ok(_) => {
258 0 : info!("created neondb database");
259 0 : break;
260 0 : }
261 0 : Err(e) => {
262 0 : warn!(
263 0 : "failed to create database: {}, retying in {}s",
264 0 : e,
265 0 : PG_WAIT_RETRY_INTERVAL.as_secs_f32()
266 0 : );
267 0 : tokio::time::sleep(PG_WAIT_RETRY_INTERVAL).await;
268 0 : continue;
269 0 : }
270 0 : }
271 0 : }
272 0 : Err(_) => {
273 0 : info!(
274 0 : "postgres not ready yet, retrying in {}s",
275 0 : PG_WAIT_RETRY_INTERVAL.as_secs_f32()
276 0 : );
277 0 : tokio::time::sleep(PG_WAIT_RETRY_INTERVAL).await;
278 0 : continue;
279 0 : }
280 0 : }
281 0 : }
282 0 :
283 0 : let restore_pg_connstring = restore_pg_connstring.replace("dbname=postgres", "dbname=neondb");
284 0 :
285 0 : let dumpdir = working_directory.join("dumpdir");
286 0 :
287 0 : let common_args = [
288 0 : // schema mapping (prob suffices to specify them on one side)
289 0 : "--no-owner".to_string(),
290 0 : "--no-privileges".to_string(),
291 0 : "--no-publications".to_string(),
292 0 : "--no-security-labels".to_string(),
293 0 : "--no-subscriptions".to_string(),
294 0 : "--no-tablespaces".to_string(),
295 0 : // format
296 0 : "--format".to_string(),
297 0 : "directory".to_string(),
298 0 : // concurrency
299 0 : "--jobs".to_string(),
300 0 : num_cpus::get().to_string(),
301 0 : // progress updates
302 0 : "--verbose".to_string(),
303 0 : ];
304 0 :
305 0 : info!("dump into the working directory");
306 0 : {
307 0 : let mut pg_dump = tokio::process::Command::new(pg_bin_dir.join("pg_dump"))
308 0 : .args(&common_args)
309 0 : .arg("-f")
310 0 : .arg(&dumpdir)
311 0 : .arg("--no-sync")
312 0 : // POSITIONAL args
313 0 : // source db (db name included in connection string)
314 0 : .arg(&source_connection_string)
315 0 : // how we run it
316 0 : .env_clear()
317 0 : .kill_on_drop(true)
318 0 : .stdout(std::process::Stdio::piped())
319 0 : .stderr(std::process::Stdio::piped())
320 0 : .spawn()
321 0 : .context("spawn pg_dump")?;
322 0 :
323 0 : info!(pid=%pg_dump.id().unwrap(), "spawned pg_dump");
324 0 :
325 0 : tokio::spawn(
326 0 : child_stdio_to_log::relay_process_output(pg_dump.stdout.take(), pg_dump.stderr.take())
327 0 : .instrument(info_span!("pg_dump")),
328 0 : );
329 0 :
330 0 : let st = pg_dump.wait().await.context("wait for pg_dump")?;
331 0 : info!(status=?st, "pg_dump exited");
332 0 : if !st.success() {
333 0 : warn!(status=%st, "pg_dump failed, restore will likely fail as well");
334 0 : }
335 0 : }
336 0 :
337 0 : // TODO: do it in a streaming way, plenty of internal research done on this already
338 0 : // TODO: do the unlogged table trick
339 0 :
340 0 : info!("restore from working directory into vanilla postgres");
341 0 : {
342 0 : let mut pg_restore = tokio::process::Command::new(pg_bin_dir.join("pg_restore"))
343 0 : .args(&common_args)
344 0 : .arg("-d")
345 0 : .arg(&restore_pg_connstring)
346 0 : // POSITIONAL args
347 0 : .arg(&dumpdir)
348 0 : // how we run it
349 0 : .env_clear()
350 0 : .kill_on_drop(true)
351 0 : .stdout(std::process::Stdio::piped())
352 0 : .stderr(std::process::Stdio::piped())
353 0 : .spawn()
354 0 : .context("spawn pg_restore")?;
355 0 :
356 0 : info!(pid=%pg_restore.id().unwrap(), "spawned pg_restore");
357 0 : tokio::spawn(
358 0 : child_stdio_to_log::relay_process_output(
359 0 : pg_restore.stdout.take(),
360 0 : pg_restore.stderr.take(),
361 0 : )
362 0 : .instrument(info_span!("pg_restore")),
363 0 : );
364 0 : let st = pg_restore.wait().await.context("wait for pg_restore")?;
365 0 : info!(status=?st, "pg_restore exited");
366 0 : if !st.success() {
367 0 : warn!(status=%st, "pg_restore failed, restore will likely fail as well");
368 0 : }
369 0 : }
370 0 :
371 0 : // If interactive mode, wait for Ctrl+C
372 0 : if args.interactive {
373 0 : info!("Running in interactive mode. Press Ctrl+C to shut down.");
374 0 : tokio::signal::ctrl_c().await.context("wait for ctrl-c")?;
375 0 : }
376 0 :
377 0 : info!("shutdown postgres");
378 0 : {
379 0 : nix::sys::signal::kill(
380 0 : Pid::from_raw(
381 0 : i32::try_from(postgres_proc.id().unwrap()).expect("convert child pid to i32"),
382 0 : ),
383 0 : nix::sys::signal::SIGTERM,
384 0 : )
385 0 : .context("signal postgres to shut down")?;
386 0 : postgres_proc
387 0 : .wait()
388 0 : .await
389 0 : .context("wait for postgres to shut down")?;
390 0 : }
391 0 :
392 0 : // Only sync if s3_prefix was specified
393 0 : if let Some(s3_prefix) = args.s3_prefix {
394 0 : info!("upload pgdata");
395 0 : aws_s3_sync::sync(Utf8Path::new(&pgdata_dir), &s3_prefix.append("/pgdata/"))
396 0 : .await
397 0 : .context("sync dump directory to destination")?;
398 0 :
399 0 : info!("write status");
400 0 : {
401 0 : let status_dir = working_directory.join("status");
402 0 : std::fs::create_dir(&status_dir).context("create status directory")?;
403 0 : let status_file = status_dir.join("pgdata");
404 0 : std::fs::write(&status_file, serde_json::json!({"done": true}).to_string())
405 0 : .context("write status file")?;
406 0 : aws_s3_sync::sync(&status_dir, &s3_prefix.append("/status/"))
407 0 : .await
408 0 : .context("sync status directory to destination")?;
409 0 : }
410 0 : }
411 0 :
412 0 : Ok(())
413 0 : }
|