1use std::net::TcpListener;
16use std::os::unix::process::CommandExt;
17use std::path::{Path, PathBuf};
18use std::process::Command;
19
20use anyhow::{Context, Result, bail};
21use sqlx::migrate::Migrator;
22
23static MIGRATOR: Migrator = sqlx::migrate!("../migrations");
27
28const PORT_RANGE: std::ops::Range<u16> = 54320..54340;
32
33const TIMEOUTS: &[&str] = &[
42 "-c",
43 "statement_timeout=120s",
44 "-c",
45 "idle_in_transaction_session_timeout=300s",
46];
47
48const CONNECTIONS: &[&str] = &["-c", "max_connections=400"];
50
51const DURABILITY_OFF: &[&str] = &[
56 "-c",
57 "fsync=off",
58 "-c",
59 "synchronous_commit=off",
60 "-c",
61 "full_page_writes=off",
62 "-c",
63 "autovacuum=off",
64];
65
66const SETUP_DURATIONS_SINCE: u32 = 18;
69
70const SOCKET_PATH_MAX: usize = 107;
72
73pub struct Postgres {
75 data_dir: PathBuf,
76 port: u16,
77 _lock: nix::fcntl::Flock<std::fs::File>,
79 _root: tempfile::TempDir,
81}
82
83impl Postgres {
84 pub fn database_url(&self) -> String {
85 format!("postgres://postgres@127.0.0.1:{}/nomisync", self.port)
86 }
87}
88
89impl Drop for Postgres {
90 fn drop(&mut self) {
91 let _ = Command::new("pg_ctl")
94 .process_group(0)
95 .args([
96 "-D",
97 &self.data_dir.to_string_lossy(),
98 "-m",
99 "immediate",
100 "stop",
101 ])
102 .status();
103 }
104}
105
106fn run(program: &str, args: &[&str]) -> Result<()> {
109 let status = Command::new(program)
110 .args(args)
111 .process_group(0)
112 .status()
113 .with_context(|| format!("failed to run {program}"))?;
114 if !status.success() {
115 bail!("{program} exited with {status}");
116 }
117 Ok(())
118}
119
120mod sweep;
121
122const CLUSTER_PREFIX: &str = "nomisync-ci-pg";
123
124const RAM_DISK: &str = "/dev/shm";
129
130const RAM_DISK_MIN_FREE: u64 = 4 << 30;
132
133fn ram_disk_has_room() -> bool {
134 nix::sys::statvfs::statvfs(RAM_DISK).is_ok_and(|fs| {
135 fs.blocks_available().saturating_mul(fs.fragment_size()) >= RAM_DISK_MIN_FREE
136 })
137}
138
139fn cluster_root() -> std::io::Result<tempfile::TempDir> {
140 sweep::sweep_stale_clusters(Path::new(RAM_DISK));
141 match ram_disk_has_room() {
142 true => tempfile::TempDir::with_prefix_in(CLUSTER_PREFIX, RAM_DISK),
143 false => tempfile::TempDir::with_prefix(CLUSTER_PREFIX),
144 }
145}
146
147pub async fn start() -> Result<Postgres> {
149 let root = cluster_root().context("could not make a temp dir")?;
152 let lock = sweep::hold(root.path()).context("could not lock the temp dir")?;
153 let data_dir = root.path().join("pgdata");
154 let socket_dir = data_dir.join("sockets");
155
156 run(
157 "initdb",
158 &[
159 "-D",
160 &data_dir.to_string_lossy(),
161 "-U",
162 "postgres",
163 "--auth=trust",
164 "--encoding=UTF8",
166 "--locale=C",
167 ],
168 )
169 .context("initdb failed")?;
170 std::fs::create_dir_all(&socket_dir).context("could not make the socket dir")?;
171 check_socket_path(&socket_dir)?;
172
173 let log = root.path().join("postgres.log");
174 let port = start_on_free_port(&data_dir, &socket_dir, &log)?;
175 let postgres = Postgres {
176 data_dir,
177 port,
178 _lock: lock,
179 _root: root,
180 };
181
182 println!(">> postgres: listening on 127.0.0.1:{port}");
183 create_and_migrate(&postgres).await?;
184 Ok(postgres)
185}
186
187fn start_on_free_port(data_dir: &Path, socket_dir: &Path, log: &Path) -> Result<u16> {
188 let major = server_major()?;
189 first_started(PORT_RANGE, port_is_free, |port| {
190 let options = server_options(major, port, socket_dir);
191 let status = Command::new("pg_ctl")
192 .process_group(0)
193 .args([
194 "-D",
195 &data_dir.to_string_lossy(),
196 "-l",
197 &log.to_string_lossy(),
198 "-w",
199 "-o",
200 &options,
201 "start",
202 ])
203 .status()
204 .context("failed to run pg_ctl")?;
205 Ok(status.success())
206 })
207 .with_context(|| format!("postgres log {}:\n{}", log.display(), log_tail(log)))
208}
209
210fn first_started(
214 ports: impl Iterator<Item = u16>,
215 probe: impl Fn(u16) -> bool,
216 mut attempt: impl FnMut(u16) -> Result<bool>,
217) -> Result<u16> {
218 let mut free = 0;
219 for port in ports.filter(|&port| probe(port)) {
220 free += 1;
221 if attempt(port)? {
222 return Ok(port);
223 }
224 }
225 match free {
226 0 => bail!("no free port in {PORT_RANGE:?}"),
227 _ => bail!("postgres failed to start on every free port in {PORT_RANGE:?}"),
228 }
229}
230
231fn server_options(major: u32, port: u16, socket_dir: &Path) -> String {
234 let diagnostics: &[&str] = match major >= SETUP_DURATIONS_SINCE {
235 true => &["-c", "log_connections=setup_durations"],
236 false => &[],
237 };
238 format!(
239 "-p {port} -c listen_addresses=127.0.0.1 -c unix_socket_directories={} {}",
240 socket_dir.display(),
241 [DURABILITY_OFF, TIMEOUTS, CONNECTIONS, diagnostics]
242 .concat()
243 .join(" ")
244 )
245}
246
247fn server_major() -> Result<u32> {
248 let output = Command::new("pg_ctl")
249 .arg("--version")
250 .output()
251 .context("failed to run pg_ctl --version")?;
252 if !output.status.success() {
253 bail!("pg_ctl --version exited with {}", output.status);
254 }
255 parse_major(&String::from_utf8_lossy(&output.stdout))
256}
257
258fn parse_major(version: &str) -> Result<u32> {
259 version
260 .split_whitespace()
261 .nth(2)
262 .and_then(|number| number.split('.').next())
263 .and_then(|major| major.parse().ok())
264 .with_context(|| format!("cannot read a major version from {version:?}"))
265}
266
267fn log_tail(log: &Path) -> String {
268 let text = std::fs::read_to_string(log).unwrap_or_default();
269 let lines: Vec<_> = text.lines().rev().take(10).collect();
270 lines.into_iter().rev().collect::<Vec<_>>().join("\n")
271}
272
273fn check_socket_path(socket_dir: &Path) -> Result<()> {
274 let longest = socket_dir.join(format!(".s.PGSQL.{}", PORT_RANGE.end));
275 let length = longest.as_os_str().len();
276 if length > SOCKET_PATH_MAX {
277 bail!(
278 "the socket path {longest:?} is {length} bytes, over the {SOCKET_PATH_MAX} a unix socket allows; use a shorter TMPDIR"
279 );
280 }
281 Ok(())
282}
283
284fn port_is_free(port: u16) -> bool {
285 TcpListener::bind(("127.0.0.1", port)).is_ok()
286}
287
288async fn create_and_migrate(postgres: &Postgres) -> Result<()> {
289 use sqlx::{Connection, Executor, PgConnection};
290
291 let admin = format!("postgres://postgres@127.0.0.1:{}/postgres", postgres.port);
292 let mut conn = PgConnection::connect(&admin)
293 .await
294 .context("could not connect to the new cluster")?;
295 conn.execute("CREATE DATABASE nomisync")
296 .await
297 .context("could not create the nomisync database")?;
298 conn.close().await.ok();
299
300 let mut conn = PgConnection::connect(&postgres.database_url())
301 .await
302 .context("could not connect to the nomisync database")?;
303 MIGRATOR.run(&mut conn).await.context("migrations failed")?;
304 conn.close().await.ok();
305
306 println!(
307 ">> postgres: migrated ({} migrations)",
308 MIGRATOR.iter().count()
309 );
310 Ok(())
311}
312
313#[cfg(test)]
314mod tests;