pgdo-lib 0.7.0

The convenience of SQLite – but with PostgreSQL (Library package)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! Create, start, introspect, stop, and destroy PostgreSQL clusters.

mod client;
pub mod config;
pub mod session;

mod error;
mod owner;
mod postmaster;

use std::ffi::{OsStr, OsString};
use std::io::{self, Read, Write};
use std::os::unix::prelude::OsStringExt;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Output};
use std::{fmt, fs};

use shell_quote::{QuoteExt, Sh};

use crate::runtime::{
    self,
    strategy::{Strategy, StrategyLike},
    Runtime,
};
use crate::version;
pub use client::{ClientError, ServerError};
pub use error::ClusterError;
pub use session::{Finish, Session, Takeover};

/// The outcome of an action on a cluster.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum State {
    /// The action we requested was performed from this process, e.g. we tried
    /// to create the cluster, and we did indeed create the cluster.
    Modified,
    /// The action we requested was performed by another process, or was not
    /// necessary, e.g. we tried to stop the cluster but it was already stopped.
    Unmodified,
}

use State::{Modified, Unmodified};

/// `template0` is always present in a PostgreSQL cluster.
///
/// This database is a template database, though it's used to a lesser extent
/// than `template1`.
///
/// `template0` should never be modified so it's rare to connect to this
/// database, even as a convenient default – see [`DATABASE_TEMPLATE1`] for an
/// explanation as to why.
pub const DATABASE_TEMPLATE0: &str = "template0";

/// `template1` is always present in a PostgreSQL cluster.
///
/// This database is used as the default template for creating new databases.
///
/// Connecting to a database prevents other sessions from creating new databases
/// using that database as a template; see PostgreSQL's [Template Databases][]
/// page to learn more about this limitation. Since `template1` is the default
/// template, connecting to this database prevents other sessions from using a
/// plain `CREATE DATABASE` command. In other words, it may be a good idea to
/// connect to this database _only_ when modifying it, not as a default.
///
/// [Template Databases]:
///     https://www.postgresql.org/docs/current/manage-ag-templatedbs.html
pub const DATABASE_TEMPLATE1: &str = "template1";

/// `postgres` is always created by `initdb` when building a PostgreSQL cluster.
///
/// From `initdb(1)`:
/// > The postgres database is a default database meant for use by users,
/// > utilities and third party applications.
///
/// Given that it can be problematic to connect to `template0` and `template1` –
/// see [`DATABASE_TEMPLATE1`] for an explanation – `postgres` is a convenient
/// default, hence this library uses `postgres` as the database from which to
/// perform administrative tasks, for example.
///
/// Unfortunately, `postgres` can be dropped, in which case some of the
/// functionality of this crate will be broken. Ideally we could connect to a
/// PostgreSQL cluster without specifying a database, but that is presently not
/// possible.
pub const DATABASE_POSTGRES: &str = "postgres";

/// The port that pgdo's clusters listen on. They listen only on a Unix-domain
/// socket in the data directory, so this does not conflict with any other
/// server; it determines only the socket's name, `.s.PGSQL.5432`.
///
/// pgdo passes it explicitly – when starting a server, and to commands run
/// against the cluster – so that `PGPORT` in the environment, or a `port`
/// setting in `postgresql.conf`, cannot move the socket.
pub const PORT: u16 = 5432;

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ClusterStatus {
    Running,
    Stopped,
    Missing,
}

impl fmt::Display for ClusterStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ClusterStatus::Running => write!(f, "running"),
            ClusterStatus::Stopped => write!(f, "stopped"),
            ClusterStatus::Missing => write!(f, "missing"),
        }
    }
}

/// Representation of a PostgreSQL cluster.
///
/// The cluster may not yet exist on disk. It may exist but be stopped, or it
/// may be running. The methods here can be used to create, start, introspect,
/// stop, and destroy the cluster. There's no protection against concurrent
/// changes to the cluster made by other processes; use a [`Session`] for that.
///
/// In other words, `Cluster` is the low-level API; [`Session`] is the locking
/// API, and is what most code should use. In particular, [`create`],
/// [`start`], [`stop`], and [`destroy`] are unsafe to call while another
/// process might be doing the same, or might be using the cluster, so call them
/// directly only when you know no other process can be.
///
/// [`create`]: Self::create
/// [`start`]: Self::start
/// [`stop`]: Self::stop
/// [`destroy`]: Self::destroy
///
/// # Blocking
///
/// All methods here block. Most run external programs like `pg_ctl`, `initdb`,
/// or `psql`, and block until those finish; the rest talk to the cluster over a
/// socket with pgdo's minimal internal client, and block on that I/O. All are
/// safe to call from async code, but will block the calling thread; to avoid
/// that, call them within something like Tokio's `spawn_blocking`.
#[derive(Debug)]
pub struct Cluster {
    /// The data directory of the cluster.
    ///
    /// Corresponds to the `PGDATA` environment variable. pgdo keeps a few files
    /// of its own in here too, all named `pgdo.*`.
    ///
    /// This is also where the cluster's Unix-domain socket lives. Clusters
    /// managed by pgdo listen **only** on a Unix-domain socket, not on TCP. To
    /// connect with a client library, use this as the host, e.g. for SQLx use
    /// `PgConnectOptions::new().socket(&cluster.datadir)`. See also
    /// [`url`][`Self::url`].
    pub datadir: PathBuf,
    /// How to select the PostgreSQL installation to use with this cluster.
    pub strategy: Strategy,
}

/// Files and directories that pgdo keeps in a cluster's data directory,
/// alongside PostgreSQL's own.
mod files {
    /// Used by [`Session`][super::Session] to coordinate processes.
    pub(super) const LOCK: &str = "pgdo.lock";
    /// Where [`Cluster::create`][super::Cluster::create] runs `initdb`, before
    /// moving the result into the data directory.
    pub(super) const INIT: &str = "pgdo.init";
    /// Marks an in-progress move from [`INIT`] into the data directory; see
    /// [`Cluster::create`][super::Cluster::create].
    pub(super) const VERSION_INIT: &str = "PG_VERSION.init";
    /// Records which kernel and namespace owns a running cluster; see the
    /// `owner` module.
    pub(super) const OWNER: &str = "pgdo.owner";
    /// PostgreSQL's version file; its presence marks a cluster.
    pub(super) const VERSION: &str = "PG_VERSION";

    /// Is the given name one of pgdo's own files?
    pub(super) fn is_pgdo(name: &std::ffi::OsStr) -> bool {
        match name.to_str() {
            Some(LOCK | OWNER | INIT | VERSION_INIT) => true,
            // Temporary files written while claiming ownership.
            Some(name) => name.starts_with("pgdo.owner."),
            None => false,
        }
    }

    /// Is the given name one of the files that sessions use to coordinate?
    /// These must outlive the cluster itself; see `Session`.
    pub(super) fn is_session(name: &std::ffi::OsStr) -> bool {
        matches!(name.to_str(), Some(LOCK | OWNER))
    }
}

impl Cluster {
    /// Represent a cluster at the given path.
    pub fn new<P: AsRef<Path>, S: Into<Strategy>>(
        datadir: P,
        strategy: S,
    ) -> Result<Self, ClusterError> {
        Ok(Self {
            datadir: datadir.as_ref().to_owned(),
            strategy: strategy.into(),
        })
    }

    /// Determine the runtime to use with this cluster.
    fn runtime(&self) -> Result<Runtime, ClusterError> {
        let runtime = match version(self)? {
            None => self
                .strategy
                .fallback()
                .ok_or(ClusterError::RuntimeDefaultNotFound)?,
            Some(version) if !runtime::is_supported(version) => {
                return Err(ClusterError::UnsupportedVersion(version))
            }
            Some(version) => self
                .strategy
                .select(&version.into())
                .ok_or(ClusterError::RuntimeNotFound(version))?,
        };
        // Strategies that discover runtimes skip those that are unsupported,
        // but a strategy can also be given a specific runtime.
        if runtime.is_supported() {
            Ok(runtime)
        } else {
            Err(ClusterError::UnsupportedRuntime(runtime.version))
        }
    }

    /// Return a [`Command`] that will invoke `pg_ctl` with the environment
    /// referring to this cluster.
    fn ctl(&self) -> Result<Command, ClusterError> {
        let mut command = self.runtime()?.execute("pg_ctl");
        command.env("PGDATA", &self.datadir);
        command.env("PGHOST", &self.datadir);
        Ok(command)
    }

    /// Check if this cluster is running.
    ///
    /// Convenient call-through to [`status`][`Self::status`]; only returns
    /// `true` when the cluster is definitely running.
    pub fn running(&self) -> Result<bool, ClusterError> {
        self.status().map(|status| status == ClusterStatus::Running)
    }

    /// Check the status of this cluster.
    ///
    /// Tries to distinguish carefully between "definitely running", "definitely
    /// not running", "missing", and "don't know". The latter results in
    /// [`ClusterError`].
    pub fn status(&self) -> Result<ClusterStatus, ClusterError> {
        // Run `pg_ctl` in its own process group, so that it does not receive
        // signals sent from the terminal, e.g. SIGINT from Ctrl-C. A session
        // checks the status as it ends, while stopping the cluster, and as it
        // abandons a start; interrupting it then would leave the server running.
        let output = self.ctl()?.process_group(0).arg("status").output()?;
        // See https://www.postgresql.org/docs/current/app-pg-ctl.html for the
        // meaning of these exit codes. We check for specific codes to avoid
        // masking errors from insufficient permissions or missing executables,
        // for example.
        match output.status.code() {
            // The server is running.
            Some(0) => Ok(ClusterStatus::Running),
            // The data directory is present and accessible but the server is
            // not running.
            Some(3) => Ok(ClusterStatus::Stopped),
            // The data directory is not present or is not accessible. If it's
            // missing, then the server is not running. If it is present but not
            // accessible then we can't know if the server is running or not.
            Some(4) if !exists(self) => Ok(ClusterStatus::Missing),
            // Killed by signal, or some other exit code we don't understand.
            _ => Err(ClusterError::CommandError(output)),
        }
    }

    /// The lock file used by [`Session`] to coordinate processes.
    fn lockfile(&self) -> PathBuf {
        self.datadir.join(files::LOCK)
    }

    /// The file recording which kernel and namespace owns the running cluster.
    fn ownerfile(&self) -> PathBuf {
        self.datadir.join(files::OWNER)
    }

    /// Return the path to the PID file used in this cluster.
    ///
    /// The PID file does not necessarily exist.
    pub fn pidfile(&self) -> PathBuf {
        self.datadir.join("postmaster.pid")
    }

    /// Return the path to the log file used in this cluster.
    ///
    /// The log file does not necessarily exist.
    pub fn logfile(&self) -> PathBuf {
        self.datadir.join("postmaster.log")
    }

    /// Create the cluster if it does not already exist.
    ///
    /// `initdb` refuses to use a directory that is not empty, but pgdo keeps
    /// its own files – e.g. `pgdo.lock` – in the data directory. So this runs
    /// `initdb` in a subdirectory, `pgdo.init`, then moves the result up:
    ///
    /// 1. Move `pgdo.init/PG_VERSION` to `PG_VERSION.init`. This marks a move
    ///    in progress, and means that neither directory looks like a cluster.
    /// 2. Move everything else from `pgdo.init` into the data directory, then
    ///    remove `pgdo.init`.
    /// 3. Move `PG_VERSION.init` to `PG_VERSION`.
    ///
    /// If interrupted, calling this again will finish the job: if
    /// `PG_VERSION.init` exists, it resumes the move; otherwise it discards
    /// `pgdo.init`, if it exists, and runs `initdb` again.
    ///
    /// This refuses to create a cluster in a data directory that contains
    /// anything other than pgdo's own files; see
    /// [`ClusterError::DataDirNotEmpty`].
    ///
    /// Use this only while holding an exclusive lock on the cluster, e.g. via a
    /// [`Session`], or when no other process can be using the cluster.
    pub fn create(&self) -> Result<State, ClusterError> {
        if exists(self) {
            // Nothing more to do; the cluster is already in place.
            Ok(Unmodified)
        } else {
            fs::create_dir_all(&self.datadir)?;
            let initdir = self.datadir.join(files::INIT);
            let version_init = self.datadir.join(files::VERSION_INIT);

            if !version_init.exists() {
                // No move is in progress, but `initdb` may have been
                // interrupted; discard anything it left behind.
                match fs::remove_dir_all(&initdir) {
                    Err(err) if err.kind() != io::ErrorKind::NotFound => Err(err)?,
                    _ => (),
                }
                self.check_datadir_empty()?;
                self.initdb(&initdir)?;
                fs::rename(initdir.join(files::VERSION), &version_init)?;
            }

            // Move everything else. If resuming, `pgdo.init` may already be
            // gone.
            match fs::read_dir(&initdir) {
                Ok(entries) => {
                    for entry in entries {
                        let entry = entry?;
                        fs::rename(entry.path(), self.datadir.join(entry.file_name()))?;
                    }
                    // Match the permissions that `initdb` chose; PostgreSQL
                    // will refuse to start if the data directory is too
                    // permissive.
                    fs::set_permissions(&self.datadir, fs::metadata(&initdir)?.permissions())?;
                    fs::remove_dir(&initdir)?;
                }
                Err(err) if err.kind() == io::ErrorKind::NotFound => (),
                Err(err) => Err(err)?,
            }

            // Finally, make the data directory a cluster.
            fs::rename(&version_init, self.datadir.join(files::VERSION))?;
            Ok(Modified)
        }
    }

    /// Was a [`create`][Self::create] interrupted while moving files into the
    /// data directory? If so, calling `create` again will finish the job.
    fn create_interrupted(&self) -> bool {
        self.datadir.join(files::VERSION_INIT).exists()
    }

    /// Check that the data directory contains nothing but pgdo's own files.
    fn check_datadir_empty(&self) -> Result<(), ClusterError> {
        let mut entries = fs::read_dir(&self.datadir)?
            .map(|entry| entry.map(|entry| entry.file_name()))
            .filter(|name| !matches!(name, Ok(name) if files::is_pgdo(name)))
            .map(|name| name.map(|name| name.to_string_lossy().into_owned()))
            .collect::<Result<Vec<_>, _>>()?;
        if entries.is_empty() {
            Ok(())
        } else {
            entries.sort();
            Err(ClusterError::DataDirNotEmpty(self.datadir.clone(), entries))
        }
    }

    /// Run `initdb`, via `pg_ctl init`, into the given directory.
    fn initdb(&self, dir: &Path) -> Result<State, ClusterError> {
        let mut command = self.runtime()?.execute("pg_ctl");
        #[allow(clippy::suspicious_command_arg_space)]
        command
            .env("PGDATA", dir)
            .arg("init")
            // Silent; `--silent` flag accepted only in PostgreSQL >=9.2.
            .arg("-s")
            // Options for `initdb`; `--options` flag accepted only in
            // PostgreSQL >=10.
            .arg("-o")
            // Passing multiple flags in a single `arg(...)` is intentional.
            // These constitute the single value for the `-o` flag above.
            .arg("-E utf8 --locale C -A trust")
            .env("TZ", "UTC");

        bugs::retry_pg_ctl(&mut command, |_| Ok(()))
    }

    /// Start the cluster if it's not already running, with the given options.
    ///
    /// Returns [`State::Unmodified`] if the cluster is already running, meaning
    /// the given options were **NOT** applied.
    pub fn start(
        &self,
        options: &[(config::Parameter, config::Value)],
    ) -> Result<State, ClusterError> {
        // Ensure that the cluster has been created.
        self.create()?;
        // Check if we're running already.
        if self.running()? {
            // We didn't start this cluster; say so.
            Ok(Unmodified)
        } else {
            // Construct the options that `pg_ctl` will pass through to
            // `postgres`. These have to be carefully escaped for the target
            // shell – which is likely to be `sh`. Here's what they mean:
            //  -h <arg> -- host name; empty arg means Unix socket only.
            //  -k -- socket directory.
            //  -p -- port, which determines the socket's name.
            //  -c name=value -- set a configuration parameter.
            let options = {
                let mut arg: Vec<u8> = b"-h '' -k ".into();
                arg.push_quoted(Sh, &self.datadir);
                arg.extend(format!(" -p {PORT}").as_bytes());
                for (parameter, value) in options {
                    arg.extend(b" -c ");
                    arg.push_quoted(Sh, &format!("{parameter}={value}"));
                }
                OsString::from_vec(arg)
            };

            // Track the logs so that we can see if there's a retryable failure.
            let logfile = self.logfile();
            let logfile_name = logfile
                .file_name()
                .unwrap_or_else(|| "<unknown.log>".as_ref())
                .display();
            let mut log: logfile::LogFile = logfile.as_path().try_into()?;

            // Next, invoke `pg_ctl` to start the cluster.
            let mut command = self.ctl()?;
            //  -l <file> -- log file.
            //  -s -- no informational messages.
            //  -w -- wait until startup is complete.
            //  -o <string> -- options to pass through to `postgres`.
            command
                .arg("start")
                .arg("-l")
                .arg(&logfile)
                .arg("-s")
                .arg("-w")
                .arg("-o")
                .arg(options);

            // Append new logs to the command's `Output` so that the retry
            // machinery has visibility of it.
            let append_logs_to_stderr = |output: &mut Output| {
                writeln!(&mut output.stderr)?;
                writeln!(&mut output.stderr, "-- {logfile_name} --")?;
                log.read_to_end(&mut output.stderr)?;
                Ok(())
            };

            bugs::retry_pg_ctl(&mut command, append_logs_to_stderr)
        }
    }

    /// Connect to this cluster, as the current user, using pgdo's minimal
    /// internal [`client`].
    ///
    /// When the database is not specified, connects to [`DATABASE_POSTGRES`].
    fn connect(&self, database: Option<&str>) -> Result<client::Client, ClusterError> {
        let user = crate::util::current_user()?;
        let database = database.unwrap_or(DATABASE_POSTGRES);
        Ok(client::Client::connect(&self.datadir, &user, database)?)
    }

    /// Return a URL for connecting to the given database in this cluster, e.g.
    /// `postgresql://?host=%2Fpath%2Fto%2Fcluster&port=5432&dbname=postgres`.
    ///
    /// The URL has no user; clients typically default to the current user.
    ///
    /// It is not possible to return a URL for a cluster when its
    /// [`datadir`][`Self::datadir`] is not valid UTF-8, in which case
    /// `Ok(None)` is returned.
    pub fn url(&self, database: &str) -> Result<Option<url::Url>, url::ParseError> {
        match self.datadir.to_str() {
            Some(datadir) => url::Url::parse_with_params(
                "postgresql://",
                [
                    ("host", datadir),
                    ("port", &PORT.to_string()),
                    ("dbname", database),
                ],
            )
            .map(Some),
            None => Ok(None),
        }
    }

    /// Run `psql` against this cluster, in the given database.
    ///
    /// When the database is not specified, connects to [`DATABASE_POSTGRES`].
    pub fn shell(&self, database: Option<&str>) -> Result<ExitStatus, ClusterError> {
        let mut command = self.runtime()?.execute("psql");
        self.set_env(command.arg("--quiet"), database)?;
        Ok(command.spawn()?.wait()?)
    }

    /// Run the given command against this cluster.
    ///
    /// The command is run with the `PGDATA`, `PGHOST`, and `PGDATABASE`
    /// environment variables set appropriately.
    ///
    /// When the database is not specified, uses [`DATABASE_POSTGRES`].
    pub fn exec<T: AsRef<OsStr>>(
        &self,
        database: Option<&str>,
        command: T,
        args: &[T],
    ) -> Result<ExitStatus, ClusterError> {
        let mut command = self.runtime()?.command(command);
        self.set_env(command.args(args), database)?;
        Ok(command.spawn()?.wait()?)
    }

    /// Set the environment variables for this cluster.
    fn set_env(&self, command: &mut Command, database: Option<&str>) -> Result<(), ClusterError> {
        let database = database.unwrap_or(DATABASE_POSTGRES);

        // Set a few standard PostgreSQL environment variables.
        command.env("PGDATA", &self.datadir);
        command.env("PGHOST", &self.datadir);
        command.env("PGPORT", PORT.to_string());
        command.env("PGDATABASE", database);

        // Set `DATABASE_URL` if `self.datadir` is valid UTF-8, otherwise ensure
        // that `DATABASE_URL` is erased from the command's environment.
        match self.url(database)? {
            Some(url) => command.env("DATABASE_URL", url.as_str()),
            None => command.env_remove("DATABASE_URL"),
        };

        Ok(())
    }

    /// The names of databases in this cluster.
    pub fn databases(&self) -> Result<Vec<String>, ClusterError> {
        let rows = self
            .connect(None)?
            .query("SELECT datname FROM pg_catalog.pg_database ORDER BY datname")?;
        let datnames = rows
            .iter()
            .filter_map(|row| row.get(0).map(str::to_owned))
            .collect();
        Ok(datnames)
    }

    /// Create the named database.
    ///
    /// Returns [`Unmodified`] if the database already exists, otherwise it
    /// returns [`Modified`].
    pub fn createdb(&self, database: &str) -> Result<State, ClusterError> {
        let statement = format!(
            "CREATE DATABASE {}",
            postgres_protocol::escape::escape_identifier(database)
        );
        match self.connect(None)?.execute(&statement) {
            Err(client::ClientError::ServerError(err))
                if err.code == client::DUPLICATE_DATABASE =>
            {
                Ok(Unmodified)
            }
            Err(err) => Err(err)?,
            Ok(()) => Ok(Modified),
        }
    }

    /// Drop the named database.
    ///
    /// Returns [`Unmodified`] if the database does not exist, otherwise it
    /// returns [`Modified`].
    pub fn dropdb(&self, database: &str) -> Result<State, ClusterError> {
        let statement = format!(
            "DROP DATABASE {}",
            postgres_protocol::escape::escape_identifier(database)
        );
        match self.connect(None)?.execute(&statement) {
            Err(client::ClientError::ServerError(err))
                if err.code == client::UNDEFINED_DATABASE =>
            {
                Ok(Unmodified)
            }
            Err(err) => Err(err)?,
            Ok(()) => Ok(Modified),
        }
    }

    /// Stop the cluster if it's running.
    pub fn stop(&self) -> Result<State, ClusterError> {
        if self.running()? {
            // pg_ctl options:
            //  -w -- wait for shutdown to complete.
            //  -m <mode> -- shutdown mode.
            // Run `pg_ctl` in its own process group, so that it does not
            // receive signals sent from the terminal, e.g. SIGINT from Ctrl-C:
            // interrupting it would leave the server stopping, or still
            // running.
            let output = self
                .ctl()?
                .process_group(0)
                .arg("stop")
                .arg("-s")
                .arg("-w")
                .arg("-m")
                .arg("fast")
                .output()?;

            if output.status.success() {
                Ok(Modified) // We did actually stop the cluster; say so.
            } else {
                Err(ClusterError::CommandError(output))
            }
        } else {
            // The cluster is not running, so there is nothing to do.
            Ok(Unmodified)
        }
    }

    /// Destroy the cluster if it exists, after stopping it.
    ///
    /// This removes everything in the data directory **except** the files that
    /// sessions use to coordinate, i.e. `pgdo.lock` and `pgdo.owner`, then
    /// removes the data directory if that leaves it empty.
    /// A [`Session`] that ends with [`Finish::Destroy`] removes pgdo's files –
    /// safely – and the data directory too.
    pub fn destroy(&self) -> Result<State, ClusterError> {
        self.stop()?;
        self.remove()
    }

    /// Remove the cluster's files, as [`destroy`][Self::destroy] does, but
    /// without stopping it first. The caller must know that no server is
    /// running.
    fn remove(&self) -> Result<State, ClusterError> {
        let entries = match fs::read_dir(&self.datadir) {
            Ok(entries) => entries,
            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Unmodified),
            Err(err) => Err(err)?,
        };
        for entry in entries {
            let entry = entry?;
            if !files::is_session(&entry.file_name()) {
                let path = entry.path();
                if entry.file_type()?.is_dir() {
                    fs::remove_dir_all(path)?;
                } else {
                    fs::remove_file(path)?;
                }
            }
        }
        match fs::remove_dir(&self.datadir) {
            Err(err)
                if matches!(
                    err.kind(),
                    io::ErrorKind::NotFound | io::ErrorKind::DirectoryNotEmpty
                ) => {}
            result => result?,
        }
        Ok(Modified)
    }
}

impl AsRef<Path> for Cluster {
    fn as_ref(&self) -> &Path {
        &self.datadir
    }
}

/// A fairly simplistic but quick check: does the directory exist and does it
/// look like a PostgreSQL cluster data directory, i.e. does it contain a file
/// named `PG_VERSION`?
///
/// [`version()`] provides a more reliable measure, plus yields the version of
/// PostgreSQL required to use the cluster.
pub fn exists<P: AsRef<Path>>(datadir: P) -> bool {
    let datadir = datadir.as_ref();
    datadir.is_dir() && datadir.join("PG_VERSION").is_file()
}

/// Yields the version of PostgreSQL required to use a cluster.
///
/// This returns the version from the file named `PG_VERSION` in the data
/// directory if it exists, otherwise this returns `None`. For PostgreSQL
/// versions before 10 this is typically (maybe always) the major and point
/// version, e.g. 9.4 rather than 9.4.26. For version 10 and above it appears to
/// be just the major number, e.g. 14 rather than 14.2.
pub fn version<P: AsRef<Path>>(
    datadir: P,
) -> Result<Option<version::PartialVersion>, ClusterError> {
    let versionfile = datadir.as_ref().join("PG_VERSION");
    match std::fs::read_to_string(versionfile) {
        Ok(version) => Ok(Some(version.parse()?)),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(err) => Err(err)?,
    }
}

/// Determine the names of superuser roles in a cluster (that can log in).
///
/// It may not be possible to even connect to a running cluster when you don't
/// know a role to use.
///
/// This gets around the problem by launching the cluster in single-user mode
/// and matching the output of a single query of the `pg_roles` table. It's
/// hacky and fragile but it may work for you.
///
/// If no superusers are found, this returns an error containing the output from
/// the `postgres` process.
///
/// # Panics
///
/// This function panics if the regular expression used to match the output does
/// not compile; that's a bug and should never occur in a release build.
///
/// It can also panic if the thread that writes to the single-user `postgres`
/// process itself panics, but under normal circumstances that also should never
/// happen.
///
pub fn determine_superuser_role_names(
    cluster: &Cluster,
) -> Result<std::collections::HashSet<String>, ClusterError> {
    use regex::Regex;
    use std::io::Write;
    use std::panic::panic_any;
    use std::process::Stdio;
    use std::sync::LazyLock;

    const QUERY: &[u8] = b"select rolname from pg_roles where rolsuper and rolcanlogin\n";
    static RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"\brolname\s*=\s*"(.+)""#)
            .expect("invalid regex (for matching single-user role names)")
    });

    let mut child = cluster
        .runtime()?
        .execute("postgres")
        .arg("--single")
        .arg("-D")
        .arg(&cluster.datadir)
        .arg("postgres")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    let mut stdin = child.stdin.take().expect("could not take stdin");
    let writer = std::thread::spawn(move || stdin.write_all(QUERY));
    let output = child.wait_with_output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let superusers: std::collections::HashSet<_> = RE
        .captures_iter(&stdout)
        .filter_map(|capture| capture.get(1))
        .map(|m| m.as_str().to_owned())
        .collect();

    match writer.join() {
        Err(err) => panic_any(err),
        Ok(result) => result?,
    }

    if superusers.is_empty() {
        Err(ClusterError::CommandError(output))
    } else {
        Ok(superusers)
    }
}

pub type Options<'a> = &'a [(config::Parameter<'a>, config::Value)];

// ----------------------------------------------------------------------

mod logfile {
    use std::fs::File;
    use std::io::{self, ErrorKind::NotFound, Read, Seek};
    use std::path::{Path, PathBuf};

    /// Abstraction for reading a log file that may be appended to repeatedly.
    ///
    /// For example, `postmaster.log` may be written to each time we call
    /// `pg_ctl start`. If it succeeds, a spawned `postgres` process will
    /// continue writing to the log indefinitely, even after `pg_ctl` finishes.
    /// If it fails, however, it will write out the cause to this log. It's this
    /// information that we want to capture so that we can use it for deciding
    /// whether or not to retry a call to `pg_ctl`.
    ///
    /// The log file does not need to exist when creating a new [`LogFile`], and
    /// it will not create it. Its [`Read::read`] implementation will return
    /// `Ok(0)` as long as the log file does not exist.
    ///
    /// Limitations of [`LogFile`]:
    /// - It keeps the file handle open, meaning that if the log file is deleted
    ///   and reopened, this will not see new logs.
    /// - It will not detect if the log is truncated; again, this will not see
    ///   new logs.
    pub(super) struct LogFile {
        path: PathBuf,
        file: Option<File>,
    }

    impl TryFrom<&Path> for LogFile {
        type Error = io::Error;

        fn try_from(path: &Path) -> Result<Self, Self::Error> {
            let file = match File::open(path) {
                Err(err) if err.kind() == NotFound => None,
                Err(err) => Err(err)?,
                Ok(mut file) => {
                    file.seek(io::SeekFrom::End(0))?;
                    Some(file)
                }
            };
            Ok(LogFile { path: path.to_owned(), file })
        }
    }

    impl Read for LogFile {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if let Some(ref mut file) = self.file {
                file.read(buf)
            } else {
                self.file = match File::open(&self.path) {
                    Err(err) if err.kind() == NotFound => return Ok(0),
                    Err(err) => Err(err)?,
                    Ok(file) => Some(file),
                };
                match self.file {
                    Some(ref mut file) => file.read(buf),
                    None => Ok(0),
                }
            }
        }
    }
}

mod bugs {
    use super::{ClusterError, State, State::Modified};
    use regex::bytes::Regex;
    use std::process::{Command, Output};
    use std::{fmt::Write, sync, time::Duration};

    /// Work around bugs in `pg_ctl`.
    ///
    /// In all presently released versions of PostgreSQL, `pg_ctl init` can fail
    /// on some platforms (macOS, some BSDs) due to a semget(2) failure. This is
    /// a particular problem in PostgreSQL 17.x (see the linked bug report below
    /// to understand why). We try to work around this by retrying the command a
    /// few times with a short delay between each attempt.
    ///
    /// We detect whether we want to retry by checking `pg_ctl`'s output for log
    /// messages like these:
    ///
    ///   FATAL:  could not create semaphores: Invalid argument DETAIL: Failed
    ///   system call was semget(189980241, 20, 03600).
    ///
    /// See the [initial bug
    /// report](https://www.postgresql.org/message-id/CALL7chmzY3eXHA7zHnODUVGZLSvK3wYCSP0RmcDFHJY8f28Q3g@mail.gmail.com)
    /// and its thread for _much_ more detail.
    pub(super) fn retry_pg_ctl(
        command: &mut Command,
        mut supplement: impl FnMut(&mut Output) -> Result<(), ClusterError>,
    ) -> Result<State, ClusterError> {
        static SEMGET_BUG_LOG: sync::Once = sync::Once::new();
        static SEMGET_BUG_RE1: sync::LazyLock<Regex> = sync::LazyLock::new(|| {
            Regex::new(r"\bFATAL:\s+could not create semaphores: Invalid argument\b")
                .expect("invalid regex (for matching semaphore errors #1)")
        });
        static SEMGET_BUG_RE2: sync::LazyLock<Regex> = sync::LazyLock::new(|| {
            Regex::new(r"\bDETAIL:\s+Failed system call was semget\b")
                .expect("invalid regex (for matching semaphore errors #2)")
        });

        fn is_retryable(logs: &[u8]) -> bool {
            SEMGET_BUG_RE1.is_match(logs) && SEMGET_BUG_RE2.is_match(logs)
        }

        // Capture which `pg_ctl` command we're running – assume it's the first
        // argument – for use with `notify` later on.
        let command_summary = command.get_args().take(1).fold(
            command.get_program().display().to_string(),
            |mut summary, arg| {
                write!(&mut summary, " {}", arg.display()).ok();
                summary
            },
        );

        // Function that attempts to run `command`.
        let run = || {
            use backoff::Error;
            use ClusterError::{CommandError, IoError};
            match command.output() {
                Ok(output) if output.status.success() => Ok(Modified),
                Ok(mut output) => {
                    supplement(&mut output)?;
                    if is_retryable(output.stderr.as_slice()) {
                        Err(Error::transient(CommandError(output)))
                    } else {
                        Err(Error::permanent(CommandError(output)))
                    }
                }
                Err(err) => Err(Error::permanent(IoError(err))),
            }
        };

        // Function that notifies when `pg_ctl` fails transiently.
        let notify = move |_, delay: Duration| {
            SEMGET_BUG_LOG.call_once(|| {
                log::info!(concat!(
                    "In all presently released versions of PostgreSQL, `pg_ctl` can fail on ",
                    "some platforms (macOS, some BSDs) due to a semget(2) failure. This is a ",
                    "particular problem in PostgreSQL 17.x (the linked bug report has more ",
                    "information). As an imperfect workaround, `pgdo` retries the command a ",
                    "few times when it detects this specific error. Original bug report: ",
                    "https://www.postgresql.org/message-id/CALL7chmzY3eXHA7zHnODUVGZLSvK3wYCSP0RmcDFHJY8f28Q3g@mail.gmail.com.",
                ));
            });
            log::warn!("`{command_summary}` failed; retrying in {delay:?}…");
        };

        // Retry with exponential backoff + jitter.
        let state = backoff::retry_notify(
            backoff::ExponentialBackoffBuilder::new()
                .with_initial_interval(Duration::from_millis(200))
                .with_max_elapsed_time(Some(Duration::from_mins(1)))
                .with_max_interval(Duration::from_secs(10))
                .build(),
            run,
            notify,
        )
        .map_err(|err| match err {
            backoff::Error::Permanent(err) => err,
            backoff::Error::Transient { err, .. } => err,
        })?;

        Ok(state)
    }
}