Skip to main content

tmp_postgrust/
synchronous.rs

1use std::convert::TryInto;
2use std::fs::create_dir_all;
3use std::io::BufReader;
4use std::io::Lines;
5use std::os::unix::process::CommandExt;
6use std::path::Path;
7use std::process::Child;
8use std::process::ChildStderr;
9use std::process::ChildStdout;
10use std::process::Command;
11use std::process::Stdio;
12use std::sync::Arc;
13
14use nix::sys::signal;
15use nix::sys::signal::Signal;
16use nix::unistd::User;
17use nix::unistd::{Pid, Uid};
18use tempfile::TempDir;
19use tracing::{debug, instrument};
20
21use crate::errors::{ProcessCapture, TmpPostgrustError, TmpPostgrustResult};
22use crate::search::all_dir_entries;
23use crate::search::build_copy_dst_path;
24use crate::POSTGRES_UID_GID;
25
26#[instrument(skip(command, fail))]
27fn exec_process(
28    command: &mut Command,
29    fail: impl FnOnce(ProcessCapture) -> TmpPostgrustError,
30) -> TmpPostgrustResult<()> {
31    debug!("running command: {:?}", command);
32
33    let output = command
34        .output()
35        .map_err(|err| TmpPostgrustError::ExecSubprocessFailed {
36            source: err,
37            command: format!("{command:?}"),
38        })?;
39
40    if output.status.success() {
41        for line in String::from_utf8(output.stdout).unwrap().lines() {
42            debug!("{}", line);
43        }
44        Ok(())
45    } else {
46        Err(fail(ProcessCapture {
47            stdout: String::from_utf8(output.stdout).unwrap(),
48            stderr: String::from_utf8(output.stderr).unwrap(),
49        }))
50    }
51}
52
53#[instrument]
54pub(crate) fn start_postgres_subprocess(
55    postgres_bin: &Path,
56    data_directory: &Path,
57    port: u32,
58) -> TmpPostgrustResult<Child> {
59    let mut command = Command::new(postgres_bin);
60    command
61        .env("PGDATA", data_directory.to_str().unwrap())
62        .arg("-p")
63        .arg(port.to_string())
64        .stdout(Stdio::piped())
65        .stderr(Stdio::piped());
66    cmd_as_non_root(&mut command);
67    command
68        .spawn()
69        .map_err(TmpPostgrustError::SpawnSubprocessFailed)
70}
71
72#[instrument]
73pub(crate) fn exec_init_db(initdb_bin: &Path, data_directory: &Path) -> TmpPostgrustResult<()> {
74    debug!("Initializing database in: {:?}", data_directory);
75
76    let mut command = Command::new(initdb_bin);
77    command
78        .env("PGDATA", data_directory.to_str().unwrap())
79        .arg("--username=postgres");
80    cmd_as_non_root(&mut command);
81    exec_process(&mut command, TmpPostgrustError::InitDBFailed)
82}
83
84#[instrument]
85pub(crate) fn exec_copy_dir(src_dir: &Path, dst_dir: &Path) -> TmpPostgrustResult<()> {
86    let (dirs, others) = all_dir_entries(src_dir)?;
87
88    for entry in dirs {
89        create_dir_all(build_copy_dst_path(&entry, src_dir, dst_dir)?)
90            .map_err(TmpPostgrustError::CopyCachedInitDBFailedFileNotFound)?;
91    }
92
93    for entry in others {
94        reflink_copy::reflink_or_copy(&entry, build_copy_dst_path(&entry, src_dir, dst_dir)?)
95            .map_err(TmpPostgrustError::CopyCachedInitDBFailedFileNotFound)?;
96    }
97
98    Ok(())
99}
100
101#[instrument]
102pub(crate) fn chown_to_non_root(dir: &Path) -> TmpPostgrustResult<()> {
103    let current_uid = Uid::effective();
104    if !current_uid.is_root() {
105        return Ok(());
106    }
107
108    let (uid, gid) = POSTGRES_UID_GID.get_or_init(|| {
109        User::from_name("postgres")
110            .ok()
111            .flatten()
112            .map(|u| (u.uid, u.gid))
113            .expect("no user `postgres` found is system")
114    });
115    let mut cmd = Command::new("chown");
116    cmd.arg("-R").arg(format!("{uid}:{gid}")).arg(dir);
117    exec_process(&mut cmd, TmpPostgrustError::UpdatingPermissionsFailed)?;
118    Ok(())
119}
120
121#[instrument]
122pub(crate) fn exec_create_db(
123    createdb_bin: &Path,
124    socket: &Path,
125    port: u32,
126    owner: &str,
127    dbname: &str,
128) -> TmpPostgrustResult<()> {
129    let mut command = Command::new(createdb_bin);
130    command
131        .arg("-h")
132        .arg(socket)
133        .arg("-p")
134        .arg(port.to_string())
135        .arg("-U")
136        .arg("postgres")
137        .arg("-O")
138        .arg(owner)
139        .arg("--echo")
140        .arg(dbname);
141    cmd_as_non_root(&mut command);
142    exec_process(&mut command, TmpPostgrustError::CreateDBFailed)
143}
144
145#[instrument]
146pub(crate) fn exec_create_user(
147    createuser_bin: &Path,
148    socket: &Path,
149    port: u32,
150    username: &str,
151) -> TmpPostgrustResult<()> {
152    let mut command = Command::new(createuser_bin);
153    command
154        .arg("-h")
155        .arg(socket)
156        .arg("-p")
157        .arg(port.to_string())
158        .arg("-U")
159        .arg("postgres")
160        .arg("--superuser")
161        .arg("--echo")
162        .arg(username);
163    cmd_as_non_root(&mut command);
164    exec_process(&mut command, TmpPostgrustError::CreateDBFailed)
165}
166
167/// `ProcessGuard` represents a postgresql process that is running in the background.
168/// once the guard is dropped the process will be killed.
169pub struct ProcessGuard {
170    /// Allows users to read stdout by line for debugging.
171    pub stdout_reader: Option<Lines<BufReader<ChildStdout>>>,
172    /// Allows users to read stderr by line for debugging.
173    pub stderr_reader: Option<Lines<BufReader<ChildStderr>>>,
174    /// Parameters for connecting to the temporary postgresql instance.
175    ///
176    /// A user shouldn't need to use these and should call `connection_string` instead.
177    ///
178    /// Port number that Postgresql is serving on
179    pub port: u32,
180    /// Database name to connect to.
181    pub db_name: String,
182    /// Username to connect as.
183    pub user_name: String,
184
185    // Signal that the postgres process should be killed.
186    pub(crate) postgres_process: Child,
187    // Prevent the data directory from being dropped while
188    // the process is running.
189    pub(crate) _data_directory: Arc<TempDir>,
190    // Prevent the cache directory from being dropped while
191    // the process is running.
192    pub(crate) _cache_directory: Arc<TempDir>,
193    /// Socket directory for connection to the running process.
194    pub(crate) socket_dir: Arc<TempDir>,
195}
196
197impl ProcessGuard {
198    /// Get a Postgresql format connection String for the process guard.
199    ///
200    /// # Panics
201    ///
202    /// Panics if a string file path cannot be obtained from the socket directory.
203    #[must_use]
204    pub fn connection_string(&self) -> String {
205        format!(
206            "postgresql:///?host={}&port={}&dbname={}&user={}",
207            self.socket_dir
208                .path()
209                .to_str()
210                .expect("Failed to convert socket directory to a path"),
211            self.port,
212            self.db_name,
213            self.user_name,
214        )
215    }
216}
217
218/// Signal that the process needs to end.
219impl Drop for ProcessGuard {
220    fn drop(&mut self) {
221        signal::kill(
222            Pid::from_raw(self.postgres_process.id().try_into().unwrap()),
223            Signal::SIGINT,
224        )
225        .unwrap();
226        self.postgres_process.wait().unwrap();
227    }
228}
229
230fn cmd_as_non_root(command: &mut Command) {
231    let current_uid = Uid::effective();
232    if current_uid.is_root() {
233        let (uid, gid) = POSTGRES_UID_GID.get_or_init(|| {
234            User::from_name("postgres")
235                .ok()
236                .flatten()
237                .map(|u| (u.uid, u.gid))
238                .expect("no user `postgres` found is system")
239        });
240        command.uid(uid.as_raw()).gid(gid.as_raw());
241        // PostgreSQL cannot be run as root, so change to default user
242        command.uid(uid.as_raw()).gid(gid.as_raw());
243    }
244}