Skip to main content

pgdo/
cluster.rs

1//! Create, start, introspect, stop, and destroy PostgreSQL clusters.
2
3mod client;
4pub mod config;
5pub mod session;
6
7mod error;
8mod owner;
9mod postmaster;
10
11use std::ffi::{OsStr, OsString};
12use std::io::{self, Read, Write};
13use std::os::unix::prelude::OsStringExt;
14use std::os::unix::process::CommandExt;
15use std::path::{Path, PathBuf};
16use std::process::{Command, ExitStatus, Output};
17use std::{fmt, fs};
18
19use shell_quote::{QuoteExt, Sh};
20
21use crate::runtime::{
22    self,
23    strategy::{Strategy, StrategyLike},
24    Runtime,
25};
26use crate::version;
27pub use client::{ClientError, ServerError};
28pub use error::ClusterError;
29pub use session::{Finish, Session, Takeover};
30
31/// The outcome of an action on a cluster.
32#[derive(Debug, Copy, Clone, PartialEq, Eq)]
33pub enum State {
34    /// The action we requested was performed from this process, e.g. we tried
35    /// to create the cluster, and we did indeed create the cluster.
36    Modified,
37    /// The action we requested was performed by another process, or was not
38    /// necessary, e.g. we tried to stop the cluster but it was already stopped.
39    Unmodified,
40}
41
42use State::{Modified, Unmodified};
43
44/// `template0` is always present in a PostgreSQL cluster.
45///
46/// This database is a template database, though it's used to a lesser extent
47/// than `template1`.
48///
49/// `template0` should never be modified so it's rare to connect to this
50/// database, even as a convenient default – see [`DATABASE_TEMPLATE1`] for an
51/// explanation as to why.
52pub const DATABASE_TEMPLATE0: &str = "template0";
53
54/// `template1` is always present in a PostgreSQL cluster.
55///
56/// This database is used as the default template for creating new databases.
57///
58/// Connecting to a database prevents other sessions from creating new databases
59/// using that database as a template; see PostgreSQL's [Template Databases][]
60/// page to learn more about this limitation. Since `template1` is the default
61/// template, connecting to this database prevents other sessions from using a
62/// plain `CREATE DATABASE` command. In other words, it may be a good idea to
63/// connect to this database _only_ when modifying it, not as a default.
64///
65/// [Template Databases]:
66///     https://www.postgresql.org/docs/current/manage-ag-templatedbs.html
67pub const DATABASE_TEMPLATE1: &str = "template1";
68
69/// `postgres` is always created by `initdb` when building a PostgreSQL cluster.
70///
71/// From `initdb(1)`:
72/// > The postgres database is a default database meant for use by users,
73/// > utilities and third party applications.
74///
75/// Given that it can be problematic to connect to `template0` and `template1` –
76/// see [`DATABASE_TEMPLATE1`] for an explanation – `postgres` is a convenient
77/// default, hence this library uses `postgres` as the database from which to
78/// perform administrative tasks, for example.
79///
80/// Unfortunately, `postgres` can be dropped, in which case some of the
81/// functionality of this crate will be broken. Ideally we could connect to a
82/// PostgreSQL cluster without specifying a database, but that is presently not
83/// possible.
84pub const DATABASE_POSTGRES: &str = "postgres";
85
86/// The port that pgdo's clusters listen on. They listen only on a Unix-domain
87/// socket in the data directory, so this does not conflict with any other
88/// server; it determines only the socket's name, `.s.PGSQL.5432`.
89///
90/// pgdo passes it explicitly – when starting a server, and to commands run
91/// against the cluster – so that `PGPORT` in the environment, or a `port`
92/// setting in `postgresql.conf`, cannot move the socket.
93pub const PORT: u16 = 5432;
94
95#[derive(Debug, PartialEq, Eq, Clone)]
96pub enum ClusterStatus {
97    Running,
98    Stopped,
99    Missing,
100}
101
102impl fmt::Display for ClusterStatus {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            ClusterStatus::Running => write!(f, "running"),
106            ClusterStatus::Stopped => write!(f, "stopped"),
107            ClusterStatus::Missing => write!(f, "missing"),
108        }
109    }
110}
111
112/// Representation of a PostgreSQL cluster.
113///
114/// The cluster may not yet exist on disk. It may exist but be stopped, or it
115/// may be running. The methods here can be used to create, start, introspect,
116/// stop, and destroy the cluster. There's no protection against concurrent
117/// changes to the cluster made by other processes; use a [`Session`] for that.
118///
119/// In other words, `Cluster` is the low-level API; [`Session`] is the locking
120/// API, and is what most code should use. In particular, [`create`],
121/// [`start`], [`stop`], and [`destroy`] are unsafe to call while another
122/// process might be doing the same, or might be using the cluster, so call them
123/// directly only when you know no other process can be.
124///
125/// [`create`]: Self::create
126/// [`start`]: Self::start
127/// [`stop`]: Self::stop
128/// [`destroy`]: Self::destroy
129///
130/// # Blocking
131///
132/// All methods here block. Most run external programs like `pg_ctl`, `initdb`,
133/// or `psql`, and block until those finish; the rest talk to the cluster over a
134/// socket with pgdo's minimal internal client, and block on that I/O. All are
135/// safe to call from async code, but will block the calling thread; to avoid
136/// that, call them within something like Tokio's `spawn_blocking`.
137#[derive(Debug)]
138pub struct Cluster {
139    /// The data directory of the cluster.
140    ///
141    /// Corresponds to the `PGDATA` environment variable. pgdo keeps a few files
142    /// of its own in here too, all named `pgdo.*`.
143    ///
144    /// This is also where the cluster's Unix-domain socket lives. Clusters
145    /// managed by pgdo listen **only** on a Unix-domain socket, not on TCP. To
146    /// connect with a client library, use this as the host, e.g. for SQLx use
147    /// `PgConnectOptions::new().socket(&cluster.datadir)`. See also
148    /// [`url`][`Self::url`].
149    pub datadir: PathBuf,
150    /// How to select the PostgreSQL installation to use with this cluster.
151    pub strategy: Strategy,
152}
153
154/// Files and directories that pgdo keeps in a cluster's data directory,
155/// alongside PostgreSQL's own.
156mod files {
157    /// Used by [`Session`][super::Session] to coordinate processes.
158    pub(super) const LOCK: &str = "pgdo.lock";
159    /// Where [`Cluster::create`][super::Cluster::create] runs `initdb`, before
160    /// moving the result into the data directory.
161    pub(super) const INIT: &str = "pgdo.init";
162    /// Marks an in-progress move from [`INIT`] into the data directory; see
163    /// [`Cluster::create`][super::Cluster::create].
164    pub(super) const VERSION_INIT: &str = "PG_VERSION.init";
165    /// Records which kernel and namespace owns a running cluster; see the
166    /// `owner` module.
167    pub(super) const OWNER: &str = "pgdo.owner";
168    /// PostgreSQL's version file; its presence marks a cluster.
169    pub(super) const VERSION: &str = "PG_VERSION";
170
171    /// Is the given name one of pgdo's own files?
172    pub(super) fn is_pgdo(name: &std::ffi::OsStr) -> bool {
173        match name.to_str() {
174            Some(LOCK | OWNER | INIT | VERSION_INIT) => true,
175            // Temporary files written while claiming ownership.
176            Some(name) => name.starts_with("pgdo.owner."),
177            None => false,
178        }
179    }
180
181    /// Is the given name one of the files that sessions use to coordinate?
182    /// These must outlive the cluster itself; see `Session`.
183    pub(super) fn is_session(name: &std::ffi::OsStr) -> bool {
184        matches!(name.to_str(), Some(LOCK | OWNER))
185    }
186}
187
188impl Cluster {
189    /// Represent a cluster at the given path.
190    pub fn new<P: AsRef<Path>, S: Into<Strategy>>(
191        datadir: P,
192        strategy: S,
193    ) -> Result<Self, ClusterError> {
194        Ok(Self {
195            datadir: datadir.as_ref().to_owned(),
196            strategy: strategy.into(),
197        })
198    }
199
200    /// Determine the runtime to use with this cluster.
201    fn runtime(&self) -> Result<Runtime, ClusterError> {
202        let runtime = match version(self)? {
203            None => self
204                .strategy
205                .fallback()
206                .ok_or(ClusterError::RuntimeDefaultNotFound)?,
207            Some(version) if !runtime::is_supported(version) => {
208                return Err(ClusterError::UnsupportedVersion(version))
209            }
210            Some(version) => self
211                .strategy
212                .select(&version.into())
213                .ok_or(ClusterError::RuntimeNotFound(version))?,
214        };
215        // Strategies that discover runtimes skip those that are unsupported,
216        // but a strategy can also be given a specific runtime.
217        if runtime.is_supported() {
218            Ok(runtime)
219        } else {
220            Err(ClusterError::UnsupportedRuntime(runtime.version))
221        }
222    }
223
224    /// Return a [`Command`] that will invoke `pg_ctl` with the environment
225    /// referring to this cluster.
226    fn ctl(&self) -> Result<Command, ClusterError> {
227        let mut command = self.runtime()?.execute("pg_ctl");
228        command.env("PGDATA", &self.datadir);
229        command.env("PGHOST", &self.datadir);
230        Ok(command)
231    }
232
233    /// Check if this cluster is running.
234    ///
235    /// Convenient call-through to [`status`][`Self::status`]; only returns
236    /// `true` when the cluster is definitely running.
237    pub fn running(&self) -> Result<bool, ClusterError> {
238        self.status().map(|status| status == ClusterStatus::Running)
239    }
240
241    /// Check the status of this cluster.
242    ///
243    /// Tries to distinguish carefully between "definitely running", "definitely
244    /// not running", "missing", and "don't know". The latter results in
245    /// [`ClusterError`].
246    pub fn status(&self) -> Result<ClusterStatus, ClusterError> {
247        // Run `pg_ctl` in its own process group, so that it does not receive
248        // signals sent from the terminal, e.g. SIGINT from Ctrl-C. A session
249        // checks the status as it ends, while stopping the cluster, and as it
250        // abandons a start; interrupting it then would leave the server running.
251        let output = self.ctl()?.process_group(0).arg("status").output()?;
252        // See https://www.postgresql.org/docs/current/app-pg-ctl.html for the
253        // meaning of these exit codes. We check for specific codes to avoid
254        // masking errors from insufficient permissions or missing executables,
255        // for example.
256        match output.status.code() {
257            // The server is running.
258            Some(0) => Ok(ClusterStatus::Running),
259            // The data directory is present and accessible but the server is
260            // not running.
261            Some(3) => Ok(ClusterStatus::Stopped),
262            // The data directory is not present or is not accessible. If it's
263            // missing, then the server is not running. If it is present but not
264            // accessible then we can't know if the server is running or not.
265            Some(4) if !exists(self) => Ok(ClusterStatus::Missing),
266            // Killed by signal, or some other exit code we don't understand.
267            _ => Err(ClusterError::CommandError(output)),
268        }
269    }
270
271    /// The lock file used by [`Session`] to coordinate processes.
272    fn lockfile(&self) -> PathBuf {
273        self.datadir.join(files::LOCK)
274    }
275
276    /// The file recording which kernel and namespace owns the running cluster.
277    fn ownerfile(&self) -> PathBuf {
278        self.datadir.join(files::OWNER)
279    }
280
281    /// Return the path to the PID file used in this cluster.
282    ///
283    /// The PID file does not necessarily exist.
284    pub fn pidfile(&self) -> PathBuf {
285        self.datadir.join("postmaster.pid")
286    }
287
288    /// Return the path to the log file used in this cluster.
289    ///
290    /// The log file does not necessarily exist.
291    pub fn logfile(&self) -> PathBuf {
292        self.datadir.join("postmaster.log")
293    }
294
295    /// Create the cluster if it does not already exist.
296    ///
297    /// `initdb` refuses to use a directory that is not empty, but pgdo keeps
298    /// its own files – e.g. `pgdo.lock` – in the data directory. So this runs
299    /// `initdb` in a subdirectory, `pgdo.init`, then moves the result up:
300    ///
301    /// 1. Move `pgdo.init/PG_VERSION` to `PG_VERSION.init`. This marks a move
302    ///    in progress, and means that neither directory looks like a cluster.
303    /// 2. Move everything else from `pgdo.init` into the data directory, then
304    ///    remove `pgdo.init`.
305    /// 3. Move `PG_VERSION.init` to `PG_VERSION`.
306    ///
307    /// If interrupted, calling this again will finish the job: if
308    /// `PG_VERSION.init` exists, it resumes the move; otherwise it discards
309    /// `pgdo.init`, if it exists, and runs `initdb` again.
310    ///
311    /// This refuses to create a cluster in a data directory that contains
312    /// anything other than pgdo's own files; see
313    /// [`ClusterError::DataDirNotEmpty`].
314    ///
315    /// Use this only while holding an exclusive lock on the cluster, e.g. via a
316    /// [`Session`], or when no other process can be using the cluster.
317    pub fn create(&self) -> Result<State, ClusterError> {
318        if exists(self) {
319            // Nothing more to do; the cluster is already in place.
320            Ok(Unmodified)
321        } else {
322            fs::create_dir_all(&self.datadir)?;
323            let initdir = self.datadir.join(files::INIT);
324            let version_init = self.datadir.join(files::VERSION_INIT);
325
326            if !version_init.exists() {
327                // No move is in progress, but `initdb` may have been
328                // interrupted; discard anything it left behind.
329                match fs::remove_dir_all(&initdir) {
330                    Err(err) if err.kind() != io::ErrorKind::NotFound => Err(err)?,
331                    _ => (),
332                }
333                self.check_datadir_empty()?;
334                self.initdb(&initdir)?;
335                fs::rename(initdir.join(files::VERSION), &version_init)?;
336            }
337
338            // Move everything else. If resuming, `pgdo.init` may already be
339            // gone.
340            match fs::read_dir(&initdir) {
341                Ok(entries) => {
342                    for entry in entries {
343                        let entry = entry?;
344                        fs::rename(entry.path(), self.datadir.join(entry.file_name()))?;
345                    }
346                    // Match the permissions that `initdb` chose; PostgreSQL
347                    // will refuse to start if the data directory is too
348                    // permissive.
349                    fs::set_permissions(&self.datadir, fs::metadata(&initdir)?.permissions())?;
350                    fs::remove_dir(&initdir)?;
351                }
352                Err(err) if err.kind() == io::ErrorKind::NotFound => (),
353                Err(err) => Err(err)?,
354            }
355
356            // Finally, make the data directory a cluster.
357            fs::rename(&version_init, self.datadir.join(files::VERSION))?;
358            Ok(Modified)
359        }
360    }
361
362    /// Was a [`create`][Self::create] interrupted while moving files into the
363    /// data directory? If so, calling `create` again will finish the job.
364    fn create_interrupted(&self) -> bool {
365        self.datadir.join(files::VERSION_INIT).exists()
366    }
367
368    /// Check that the data directory contains nothing but pgdo's own files.
369    fn check_datadir_empty(&self) -> Result<(), ClusterError> {
370        let mut entries = fs::read_dir(&self.datadir)?
371            .map(|entry| entry.map(|entry| entry.file_name()))
372            .filter(|name| !matches!(name, Ok(name) if files::is_pgdo(name)))
373            .map(|name| name.map(|name| name.to_string_lossy().into_owned()))
374            .collect::<Result<Vec<_>, _>>()?;
375        if entries.is_empty() {
376            Ok(())
377        } else {
378            entries.sort();
379            Err(ClusterError::DataDirNotEmpty(self.datadir.clone(), entries))
380        }
381    }
382
383    /// Run `initdb`, via `pg_ctl init`, into the given directory.
384    fn initdb(&self, dir: &Path) -> Result<State, ClusterError> {
385        let mut command = self.runtime()?.execute("pg_ctl");
386        #[allow(clippy::suspicious_command_arg_space)]
387        command
388            .env("PGDATA", dir)
389            .arg("init")
390            // Silent; `--silent` flag accepted only in PostgreSQL >=9.2.
391            .arg("-s")
392            // Options for `initdb`; `--options` flag accepted only in
393            // PostgreSQL >=10.
394            .arg("-o")
395            // Passing multiple flags in a single `arg(...)` is intentional.
396            // These constitute the single value for the `-o` flag above.
397            .arg("-E utf8 --locale C -A trust")
398            .env("TZ", "UTC");
399
400        bugs::retry_pg_ctl(&mut command, |_| Ok(()))
401    }
402
403    /// Start the cluster if it's not already running, with the given options.
404    ///
405    /// Returns [`State::Unmodified`] if the cluster is already running, meaning
406    /// the given options were **NOT** applied.
407    pub fn start(
408        &self,
409        options: &[(config::Parameter, config::Value)],
410    ) -> Result<State, ClusterError> {
411        // Ensure that the cluster has been created.
412        self.create()?;
413        // Check if we're running already.
414        if self.running()? {
415            // We didn't start this cluster; say so.
416            Ok(Unmodified)
417        } else {
418            // Construct the options that `pg_ctl` will pass through to
419            // `postgres`. These have to be carefully escaped for the target
420            // shell – which is likely to be `sh`. Here's what they mean:
421            //  -h <arg> -- host name; empty arg means Unix socket only.
422            //  -k -- socket directory.
423            //  -p -- port, which determines the socket's name.
424            //  -c name=value -- set a configuration parameter.
425            let options = {
426                let mut arg: Vec<u8> = b"-h '' -k ".into();
427                arg.push_quoted(Sh, &self.datadir);
428                arg.extend(format!(" -p {PORT}").as_bytes());
429                for (parameter, value) in options {
430                    arg.extend(b" -c ");
431                    arg.push_quoted(Sh, &format!("{parameter}={value}"));
432                }
433                OsString::from_vec(arg)
434            };
435
436            // Track the logs so that we can see if there's a retryable failure.
437            let logfile = self.logfile();
438            let logfile_name = logfile
439                .file_name()
440                .unwrap_or_else(|| "<unknown.log>".as_ref())
441                .display();
442            let mut log: logfile::LogFile = logfile.as_path().try_into()?;
443
444            // Next, invoke `pg_ctl` to start the cluster.
445            let mut command = self.ctl()?;
446            //  -l <file> -- log file.
447            //  -s -- no informational messages.
448            //  -w -- wait until startup is complete.
449            //  -o <string> -- options to pass through to `postgres`.
450            command
451                .arg("start")
452                .arg("-l")
453                .arg(&logfile)
454                .arg("-s")
455                .arg("-w")
456                .arg("-o")
457                .arg(options);
458
459            // Append new logs to the command's `Output` so that the retry
460            // machinery has visibility of it.
461            let append_logs_to_stderr = |output: &mut Output| {
462                writeln!(&mut output.stderr)?;
463                writeln!(&mut output.stderr, "-- {logfile_name} --")?;
464                log.read_to_end(&mut output.stderr)?;
465                Ok(())
466            };
467
468            bugs::retry_pg_ctl(&mut command, append_logs_to_stderr)
469        }
470    }
471
472    /// Connect to this cluster, as the current user, using pgdo's minimal
473    /// internal [`client`].
474    ///
475    /// When the database is not specified, connects to [`DATABASE_POSTGRES`].
476    fn connect(&self, database: Option<&str>) -> Result<client::Client, ClusterError> {
477        let user = crate::util::current_user()?;
478        let database = database.unwrap_or(DATABASE_POSTGRES);
479        Ok(client::Client::connect(&self.datadir, &user, database)?)
480    }
481
482    /// Return a URL for connecting to the given database in this cluster, e.g.
483    /// `postgresql://?host=%2Fpath%2Fto%2Fcluster&port=5432&dbname=postgres`.
484    ///
485    /// The URL has no user; clients typically default to the current user.
486    ///
487    /// It is not possible to return a URL for a cluster when its
488    /// [`datadir`][`Self::datadir`] is not valid UTF-8, in which case
489    /// `Ok(None)` is returned.
490    pub fn url(&self, database: &str) -> Result<Option<url::Url>, url::ParseError> {
491        match self.datadir.to_str() {
492            Some(datadir) => url::Url::parse_with_params(
493                "postgresql://",
494                [
495                    ("host", datadir),
496                    ("port", &PORT.to_string()),
497                    ("dbname", database),
498                ],
499            )
500            .map(Some),
501            None => Ok(None),
502        }
503    }
504
505    /// Run `psql` against this cluster, in the given database.
506    ///
507    /// When the database is not specified, connects to [`DATABASE_POSTGRES`].
508    pub fn shell(&self, database: Option<&str>) -> Result<ExitStatus, ClusterError> {
509        let mut command = self.runtime()?.execute("psql");
510        self.set_env(command.arg("--quiet"), database)?;
511        Ok(command.spawn()?.wait()?)
512    }
513
514    /// Run the given command against this cluster.
515    ///
516    /// The command is run with the `PGDATA`, `PGHOST`, and `PGDATABASE`
517    /// environment variables set appropriately.
518    ///
519    /// When the database is not specified, uses [`DATABASE_POSTGRES`].
520    pub fn exec<T: AsRef<OsStr>>(
521        &self,
522        database: Option<&str>,
523        command: T,
524        args: &[T],
525    ) -> Result<ExitStatus, ClusterError> {
526        let mut command = self.runtime()?.command(command);
527        self.set_env(command.args(args), database)?;
528        Ok(command.spawn()?.wait()?)
529    }
530
531    /// Set the environment variables for this cluster.
532    fn set_env(&self, command: &mut Command, database: Option<&str>) -> Result<(), ClusterError> {
533        let database = database.unwrap_or(DATABASE_POSTGRES);
534
535        // Set a few standard PostgreSQL environment variables.
536        command.env("PGDATA", &self.datadir);
537        command.env("PGHOST", &self.datadir);
538        command.env("PGPORT", PORT.to_string());
539        command.env("PGDATABASE", database);
540
541        // Set `DATABASE_URL` if `self.datadir` is valid UTF-8, otherwise ensure
542        // that `DATABASE_URL` is erased from the command's environment.
543        match self.url(database)? {
544            Some(url) => command.env("DATABASE_URL", url.as_str()),
545            None => command.env_remove("DATABASE_URL"),
546        };
547
548        Ok(())
549    }
550
551    /// The names of databases in this cluster.
552    pub fn databases(&self) -> Result<Vec<String>, ClusterError> {
553        let rows = self
554            .connect(None)?
555            .query("SELECT datname FROM pg_catalog.pg_database ORDER BY datname")?;
556        let datnames = rows
557            .iter()
558            .filter_map(|row| row.get(0).map(str::to_owned))
559            .collect();
560        Ok(datnames)
561    }
562
563    /// Create the named database.
564    ///
565    /// Returns [`Unmodified`] if the database already exists, otherwise it
566    /// returns [`Modified`].
567    pub fn createdb(&self, database: &str) -> Result<State, ClusterError> {
568        let statement = format!(
569            "CREATE DATABASE {}",
570            postgres_protocol::escape::escape_identifier(database)
571        );
572        match self.connect(None)?.execute(&statement) {
573            Err(client::ClientError::ServerError(err))
574                if err.code == client::DUPLICATE_DATABASE =>
575            {
576                Ok(Unmodified)
577            }
578            Err(err) => Err(err)?,
579            Ok(()) => Ok(Modified),
580        }
581    }
582
583    /// Drop the named database.
584    ///
585    /// Returns [`Unmodified`] if the database does not exist, otherwise it
586    /// returns [`Modified`].
587    pub fn dropdb(&self, database: &str) -> Result<State, ClusterError> {
588        let statement = format!(
589            "DROP DATABASE {}",
590            postgres_protocol::escape::escape_identifier(database)
591        );
592        match self.connect(None)?.execute(&statement) {
593            Err(client::ClientError::ServerError(err))
594                if err.code == client::UNDEFINED_DATABASE =>
595            {
596                Ok(Unmodified)
597            }
598            Err(err) => Err(err)?,
599            Ok(()) => Ok(Modified),
600        }
601    }
602
603    /// Stop the cluster if it's running.
604    pub fn stop(&self) -> Result<State, ClusterError> {
605        if self.running()? {
606            // pg_ctl options:
607            //  -w -- wait for shutdown to complete.
608            //  -m <mode> -- shutdown mode.
609            // Run `pg_ctl` in its own process group, so that it does not
610            // receive signals sent from the terminal, e.g. SIGINT from Ctrl-C:
611            // interrupting it would leave the server stopping, or still
612            // running.
613            let output = self
614                .ctl()?
615                .process_group(0)
616                .arg("stop")
617                .arg("-s")
618                .arg("-w")
619                .arg("-m")
620                .arg("fast")
621                .output()?;
622
623            if output.status.success() {
624                Ok(Modified) // We did actually stop the cluster; say so.
625            } else {
626                Err(ClusterError::CommandError(output))
627            }
628        } else {
629            // The cluster is not running, so there is nothing to do.
630            Ok(Unmodified)
631        }
632    }
633
634    /// Destroy the cluster if it exists, after stopping it.
635    ///
636    /// This removes everything in the data directory **except** the files that
637    /// sessions use to coordinate, i.e. `pgdo.lock` and `pgdo.owner`, then
638    /// removes the data directory if that leaves it empty.
639    /// A [`Session`] that ends with [`Finish::Destroy`] removes pgdo's files –
640    /// safely – and the data directory too.
641    pub fn destroy(&self) -> Result<State, ClusterError> {
642        self.stop()?;
643        self.remove()
644    }
645
646    /// Remove the cluster's files, as [`destroy`][Self::destroy] does, but
647    /// without stopping it first. The caller must know that no server is
648    /// running.
649    fn remove(&self) -> Result<State, ClusterError> {
650        let entries = match fs::read_dir(&self.datadir) {
651            Ok(entries) => entries,
652            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Unmodified),
653            Err(err) => Err(err)?,
654        };
655        for entry in entries {
656            let entry = entry?;
657            if !files::is_session(&entry.file_name()) {
658                let path = entry.path();
659                if entry.file_type()?.is_dir() {
660                    fs::remove_dir_all(path)?;
661                } else {
662                    fs::remove_file(path)?;
663                }
664            }
665        }
666        match fs::remove_dir(&self.datadir) {
667            Err(err)
668                if matches!(
669                    err.kind(),
670                    io::ErrorKind::NotFound | io::ErrorKind::DirectoryNotEmpty
671                ) => {}
672            result => result?,
673        }
674        Ok(Modified)
675    }
676}
677
678impl AsRef<Path> for Cluster {
679    fn as_ref(&self) -> &Path {
680        &self.datadir
681    }
682}
683
684/// A fairly simplistic but quick check: does the directory exist and does it
685/// look like a PostgreSQL cluster data directory, i.e. does it contain a file
686/// named `PG_VERSION`?
687///
688/// [`version()`] provides a more reliable measure, plus yields the version of
689/// PostgreSQL required to use the cluster.
690pub fn exists<P: AsRef<Path>>(datadir: P) -> bool {
691    let datadir = datadir.as_ref();
692    datadir.is_dir() && datadir.join("PG_VERSION").is_file()
693}
694
695/// Yields the version of PostgreSQL required to use a cluster.
696///
697/// This returns the version from the file named `PG_VERSION` in the data
698/// directory if it exists, otherwise this returns `None`. For PostgreSQL
699/// versions before 10 this is typically (maybe always) the major and point
700/// version, e.g. 9.4 rather than 9.4.26. For version 10 and above it appears to
701/// be just the major number, e.g. 14 rather than 14.2.
702pub fn version<P: AsRef<Path>>(
703    datadir: P,
704) -> Result<Option<version::PartialVersion>, ClusterError> {
705    let versionfile = datadir.as_ref().join("PG_VERSION");
706    match std::fs::read_to_string(versionfile) {
707        Ok(version) => Ok(Some(version.parse()?)),
708        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
709        Err(err) => Err(err)?,
710    }
711}
712
713/// Determine the names of superuser roles in a cluster (that can log in).
714///
715/// It may not be possible to even connect to a running cluster when you don't
716/// know a role to use.
717///
718/// This gets around the problem by launching the cluster in single-user mode
719/// and matching the output of a single query of the `pg_roles` table. It's
720/// hacky and fragile but it may work for you.
721///
722/// If no superusers are found, this returns an error containing the output from
723/// the `postgres` process.
724///
725/// # Panics
726///
727/// This function panics if the regular expression used to match the output does
728/// not compile; that's a bug and should never occur in a release build.
729///
730/// It can also panic if the thread that writes to the single-user `postgres`
731/// process itself panics, but under normal circumstances that also should never
732/// happen.
733///
734pub fn determine_superuser_role_names(
735    cluster: &Cluster,
736) -> Result<std::collections::HashSet<String>, ClusterError> {
737    use regex::Regex;
738    use std::io::Write;
739    use std::panic::panic_any;
740    use std::process::Stdio;
741    use std::sync::LazyLock;
742
743    const QUERY: &[u8] = b"select rolname from pg_roles where rolsuper and rolcanlogin\n";
744    static RE: LazyLock<Regex> = LazyLock::new(|| {
745        Regex::new(r#"\brolname\s*=\s*"(.+)""#)
746            .expect("invalid regex (for matching single-user role names)")
747    });
748
749    let mut child = cluster
750        .runtime()?
751        .execute("postgres")
752        .arg("--single")
753        .arg("-D")
754        .arg(&cluster.datadir)
755        .arg("postgres")
756        .stdin(Stdio::piped())
757        .stdout(Stdio::piped())
758        .stderr(Stdio::piped())
759        .spawn()?;
760
761    let mut stdin = child.stdin.take().expect("could not take stdin");
762    let writer = std::thread::spawn(move || stdin.write_all(QUERY));
763    let output = child.wait_with_output()?;
764    let stdout = String::from_utf8_lossy(&output.stdout);
765    let superusers: std::collections::HashSet<_> = RE
766        .captures_iter(&stdout)
767        .filter_map(|capture| capture.get(1))
768        .map(|m| m.as_str().to_owned())
769        .collect();
770
771    match writer.join() {
772        Err(err) => panic_any(err),
773        Ok(result) => result?,
774    }
775
776    if superusers.is_empty() {
777        Err(ClusterError::CommandError(output))
778    } else {
779        Ok(superusers)
780    }
781}
782
783pub type Options<'a> = &'a [(config::Parameter<'a>, config::Value)];
784
785// ----------------------------------------------------------------------
786
787mod logfile {
788    use std::fs::File;
789    use std::io::{self, ErrorKind::NotFound, Read, Seek};
790    use std::path::{Path, PathBuf};
791
792    /// Abstraction for reading a log file that may be appended to repeatedly.
793    ///
794    /// For example, `postmaster.log` may be written to each time we call
795    /// `pg_ctl start`. If it succeeds, a spawned `postgres` process will
796    /// continue writing to the log indefinitely, even after `pg_ctl` finishes.
797    /// If it fails, however, it will write out the cause to this log. It's this
798    /// information that we want to capture so that we can use it for deciding
799    /// whether or not to retry a call to `pg_ctl`.
800    ///
801    /// The log file does not need to exist when creating a new [`LogFile`], and
802    /// it will not create it. Its [`Read::read`] implementation will return
803    /// `Ok(0)` as long as the log file does not exist.
804    ///
805    /// Limitations of [`LogFile`]:
806    /// - It keeps the file handle open, meaning that if the log file is deleted
807    ///   and reopened, this will not see new logs.
808    /// - It will not detect if the log is truncated; again, this will not see
809    ///   new logs.
810    pub(super) struct LogFile {
811        path: PathBuf,
812        file: Option<File>,
813    }
814
815    impl TryFrom<&Path> for LogFile {
816        type Error = io::Error;
817
818        fn try_from(path: &Path) -> Result<Self, Self::Error> {
819            let file = match File::open(path) {
820                Err(err) if err.kind() == NotFound => None,
821                Err(err) => Err(err)?,
822                Ok(mut file) => {
823                    file.seek(io::SeekFrom::End(0))?;
824                    Some(file)
825                }
826            };
827            Ok(LogFile { path: path.to_owned(), file })
828        }
829    }
830
831    impl Read for LogFile {
832        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
833            if let Some(ref mut file) = self.file {
834                file.read(buf)
835            } else {
836                self.file = match File::open(&self.path) {
837                    Err(err) if err.kind() == NotFound => return Ok(0),
838                    Err(err) => Err(err)?,
839                    Ok(file) => Some(file),
840                };
841                match self.file {
842                    Some(ref mut file) => file.read(buf),
843                    None => Ok(0),
844                }
845            }
846        }
847    }
848}
849
850mod bugs {
851    use super::{ClusterError, State, State::Modified};
852    use regex::bytes::Regex;
853    use std::process::{Command, Output};
854    use std::{fmt::Write, sync, time::Duration};
855
856    /// Work around bugs in `pg_ctl`.
857    ///
858    /// In all presently released versions of PostgreSQL, `pg_ctl init` can fail
859    /// on some platforms (macOS, some BSDs) due to a semget(2) failure. This is
860    /// a particular problem in PostgreSQL 17.x (see the linked bug report below
861    /// to understand why). We try to work around this by retrying the command a
862    /// few times with a short delay between each attempt.
863    ///
864    /// We detect whether we want to retry by checking `pg_ctl`'s output for log
865    /// messages like these:
866    ///
867    ///   FATAL:  could not create semaphores: Invalid argument DETAIL: Failed
868    ///   system call was semget(189980241, 20, 03600).
869    ///
870    /// See the [initial bug
871    /// report](https://www.postgresql.org/message-id/CALL7chmzY3eXHA7zHnODUVGZLSvK3wYCSP0RmcDFHJY8f28Q3g@mail.gmail.com)
872    /// and its thread for _much_ more detail.
873    pub(super) fn retry_pg_ctl(
874        command: &mut Command,
875        mut supplement: impl FnMut(&mut Output) -> Result<(), ClusterError>,
876    ) -> Result<State, ClusterError> {
877        static SEMGET_BUG_LOG: sync::Once = sync::Once::new();
878        static SEMGET_BUG_RE1: sync::LazyLock<Regex> = sync::LazyLock::new(|| {
879            Regex::new(r"\bFATAL:\s+could not create semaphores: Invalid argument\b")
880                .expect("invalid regex (for matching semaphore errors #1)")
881        });
882        static SEMGET_BUG_RE2: sync::LazyLock<Regex> = sync::LazyLock::new(|| {
883            Regex::new(r"\bDETAIL:\s+Failed system call was semget\b")
884                .expect("invalid regex (for matching semaphore errors #2)")
885        });
886
887        fn is_retryable(logs: &[u8]) -> bool {
888            SEMGET_BUG_RE1.is_match(logs) && SEMGET_BUG_RE2.is_match(logs)
889        }
890
891        // Capture which `pg_ctl` command we're running – assume it's the first
892        // argument – for use with `notify` later on.
893        let command_summary = command.get_args().take(1).fold(
894            command.get_program().display().to_string(),
895            |mut summary, arg| {
896                write!(&mut summary, " {}", arg.display()).ok();
897                summary
898            },
899        );
900
901        // Function that attempts to run `command`.
902        let run = || {
903            use backoff::Error;
904            use ClusterError::{CommandError, IoError};
905            match command.output() {
906                Ok(output) if output.status.success() => Ok(Modified),
907                Ok(mut output) => {
908                    supplement(&mut output)?;
909                    if is_retryable(output.stderr.as_slice()) {
910                        Err(Error::transient(CommandError(output)))
911                    } else {
912                        Err(Error::permanent(CommandError(output)))
913                    }
914                }
915                Err(err) => Err(Error::permanent(IoError(err))),
916            }
917        };
918
919        // Function that notifies when `pg_ctl` fails transiently.
920        let notify = move |_, delay: Duration| {
921            SEMGET_BUG_LOG.call_once(|| {
922                log::info!(concat!(
923                    "In all presently released versions of PostgreSQL, `pg_ctl` can fail on ",
924                    "some platforms (macOS, some BSDs) due to a semget(2) failure. This is a ",
925                    "particular problem in PostgreSQL 17.x (the linked bug report has more ",
926                    "information). As an imperfect workaround, `pgdo` retries the command a ",
927                    "few times when it detects this specific error. Original bug report: ",
928                    "https://www.postgresql.org/message-id/CALL7chmzY3eXHA7zHnODUVGZLSvK3wYCSP0RmcDFHJY8f28Q3g@mail.gmail.com.",
929                ));
930            });
931            log::warn!("`{command_summary}` failed; retrying in {delay:?}…");
932        };
933
934        // Retry with exponential backoff + jitter.
935        let state = backoff::retry_notify(
936            backoff::ExponentialBackoffBuilder::new()
937                .with_initial_interval(Duration::from_millis(200))
938                .with_max_elapsed_time(Some(Duration::from_mins(1)))
939                .with_max_interval(Duration::from_secs(10))
940                .build(),
941            run,
942            notify,
943        )
944        .map_err(|err| match err {
945            backoff::Error::Permanent(err) => err,
946            backoff::Error::Transient { err, .. } => err,
947        })?;
948
949        Ok(state)
950    }
951}