Skip to main content

pgdo/cluster/
session.rs

1//! Use a cluster safely alongside other processes.
2//!
3//! A [`Session`] creates and starts a cluster as necessary, and stops it – or
4//! destroys it – when the session ends, **unless** other sessions are still
5//! using it. Many processes can hold sessions on the same cluster at once, e.g.
6//! as part of a test suite; the last one out turns off the lights.
7//!
8//! ```rust
9//! # use pgdo::{cluster::Cluster, runtime::strategy::Strategy};
10//! let tempdir = tempfile::tempdir()?;
11//! let cluster = Cluster::new(tempdir.path().join("data"), Strategy::default())?;
12//! let session = cluster.session(&[])?;
13//! assert!(session.running()?);
14//! let databases = session.databases()?;
15//! session.end()?; // Or drop it; see `Session::end` for the difference.
16//! # Ok::<(), pgdo::cluster::ClusterError>(())
17//! ```
18//!
19//! Coordination uses [`flock(2)`](https://linux.die.net/man/2/flock) locks on
20//! the file `pgdo.lock` in the cluster's data directory: a shared lock while
21//! the session is held; an exclusive lock to create and start the cluster, and
22//! to stop or destroy it. Because the lock file lives in the data directory, it
23//! works for any process that can see that directory, whatever path it uses to
24//! get there, as long as `flock` works on the filesystem and all processes run
25//! on the same kernel.
26//!
27//! `flock` does not work between kernels, e.g. between macOS and a Linux VM,
28//! and PostgreSQL's own check for a running server does not work between PID
29//! namespaces, e.g. between containers. So a session that starts a cluster
30//! also records its owner in `pgdo.owner`, and sessions refuse to use a cluster
31//! owned by another kernel; see [`Takeover`]. On the same kernel, a session in
32//! another namespace can use a running cluster via its Unix-domain socket, but
33//! only a session in the owner's namespace will stop it.
34//!
35//! When a session destroys a cluster it removes the lock file too. Another
36//! process might be waiting on that lock file, or might create a new one
37//! meanwhile, so after taking any lock, a session checks that the file it has
38//! locked is still the file at `pgdo.lock`; if not, it tries again.
39//!
40//! Starting, ending, and dropping a session all block, sometimes for a while:
41//! they may wait for other processes to release locks, and they run `pg_ctl`.
42//! This is safe within an async context, but blocks the current thread; to
43//! avoid that, start and end sessions within something like Tokio's
44//! `spawn_blocking`. See also [Blocking][`Cluster#blocking`].
45
46use std::marker::PhantomData;
47use std::os::unix::fs::MetadataExt;
48use std::sync::atomic::{AtomicBool, Ordering};
49use std::time::Duration;
50use std::{fs, io, ops};
51
52use either::Either::{Left, Right};
53use rand::Rng;
54
55use super::owner::{self, Relation};
56use super::postmaster::{self, Postmaster};
57use super::{client, Cluster, ClusterError, Options, State};
58use crate::lock;
59
60/// Set by [`interrupt`].
61static INTERRUPTED: AtomicBool = AtomicBool::new(false);
62
63/// Ask sessions that are starting up in this process to give up as soon as they
64/// safely can, e.g. when the user presses Ctrl-C.
65///
66/// Sessions that are starting up stop with [`ClusterError::Interrupted`],
67/// stopping any server they started, and releasing anything they claimed.
68/// Sessions that have already started are not affected.
69///
70/// Signals are process-wide, so this is too: once called, every attempt to
71/// start a session in this process fails. It is safe to call from a signal
72/// handler.
73pub fn interrupt() {
74    INTERRUPTED.store(true, Ordering::SeqCst);
75}
76
77/// Has [`interrupt`] been called?
78fn interrupted() -> bool {
79    INTERRUPTED.load(Ordering::SeqCst)
80}
81
82/// What to do with a cluster when a [`Session`] ends and no other sessions are
83/// using the cluster.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub enum Finish {
86    /// Stop the cluster.
87    #[default]
88    Stop,
89    /// Stop the cluster and **delete its data directory**.
90    Destroy,
91}
92
93/// Whether a [`Session`] may take over a cluster that was last used on another
94/// host or VM, i.e. from another kernel.
95///
96/// pgdo cannot tell whether a server on another kernel is still running, only
97/// whether sessions there show signs of life – their heartbeats. A cluster
98/// without heartbeats may still be running, e.g. if pgdo was killed, so pgdo
99/// will not take it over unless asked.
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
101pub enum Takeover {
102    /// Refuse to use a cluster owned by another kernel.
103    #[default]
104    Never,
105    /// Take over a cluster owned by another kernel if it shows no signs of
106    /// life: its owner file is watched for a while – currently 30 seconds –
107    /// and if it changes at all, the cluster is not taken over. This does not
108    /// depend on the clocks of different kernels agreeing. **Danger**: if its
109    /// server is in fact still running, the cluster will be corrupted.
110    IfStale,
111}
112
113/// A cluster that this process is using. See the [module
114/// documentation][`self`].
115///
116/// Dereferences to [`Cluster`].
117#[derive(Debug)]
118pub struct Session {
119    cluster: Cluster,
120    lock: Option<lock::LockedFileShared>,
121    finish: Finish,
122    heartbeat: Option<owner::Heartbeat>,
123}
124
125impl Cluster {
126    /// Start a [`Session`] with this cluster, creating and starting it as
127    /// necessary.
128    ///
129    /// The cluster's data directory is created if it does not exist, and the
130    /// cluster's path is made absolute (canonicalized).
131    pub fn session(self, options: Options<'_>) -> Result<Session, ClusterError> {
132        self.session_with_takeover(options, Takeover::Never)
133    }
134
135    /// Start a [`Session`] with this cluster, as with
136    /// [`session`][Self::session], but choosing whether to take over a cluster
137    /// last used on another host or VM; see [`Takeover`].
138    pub fn session_with_takeover(
139        self,
140        options: Options<'_>,
141        takeover: Takeover,
142    ) -> Result<Session, ClusterError> {
143        self.start_session(options, takeover, &interrupted)
144    }
145
146    /// Start a [`Session`], checking `interrupted` – rather than [`interrupt`]
147    /// – to see if startup should be abandoned.
148    fn start_session(
149        mut self,
150        options: Options<'_>,
151        takeover: Takeover,
152        interrupted: Interrupted<'_>,
153    ) -> Result<Session, ClusterError> {
154        // Refuse a directory that is neither a cluster nor empty before putting
155        // a lock file in it. `Cluster::create` checks again, under the lock.
156        // Skip this if a `Cluster::create` was interrupted while moving files
157        // into place: it will finish the job.
158        if self.datadir.is_dir() && !super::exists(&self) && !self.create_interrupted() {
159            self.check_datadir_empty()?;
160        }
161        fs::create_dir_all(&self.datadir)?;
162        self.datadir = self.datadir.canonicalize()?;
163        let (lock, heartbeat) = startup(&self, options, takeover, interrupted)?;
164        Ok(Session {
165            cluster: self,
166            lock: Some(lock),
167            finish: Finish::default(),
168            heartbeat: Some(heartbeat),
169        })
170    }
171}
172
173impl Session {
174    /// Choose what happens when this session ends; see [`Finish`].
175    #[must_use]
176    pub fn finish(mut self, finish: Finish) -> Self {
177        self.finish = finish;
178        self
179    }
180
181    /// End this session.
182    ///
183    /// If no other sessions are using the cluster, it is stopped or destroyed
184    /// according to [`Finish`]. Returns [`State::Modified`] if this session did
185    /// so, else [`State::Unmodified`].
186    ///
187    /// Dropping a session does the same, but can only log errors.
188    pub fn end(mut self) -> Result<State, ClusterError> {
189        self.shutdown()
190    }
191
192    fn shutdown(&mut self) -> Result<State, ClusterError> {
193        match self.lock.take() {
194            None => Ok(State::Unmodified),
195            Some(lock) => {
196                // Keep the heartbeat going until this function returns, i.e.
197                // until the cluster is stopped and the owner file is gone;
198                // stopping can take a while. A heartbeat after the owner file
199                // is removed does nothing.
200                let _heartbeat = self.heartbeat.take();
201                match upgrade(lock)? {
202                    // The cluster is in use elsewhere. There's nothing more to
203                    // do.
204                    None => Ok(State::Unmodified),
205                    Some(lock) => self.end_exclusively(lock),
206                }
207            }
208        }
209    }
210
211    /// Stop or destroy the cluster, according to [`Finish`], now that this
212    /// session has an exclusive lock. The lock is released when `lock` is
213    /// dropped, which must happen only after everything else is done.
214    fn end_exclusively(&self, lock: lock::LockedFileExclusive) -> Result<State, ClusterError> {
215        match verify(&self.cluster, &lock)? {
216            // Our lock file was removed: while `upgrade` had released our lock,
217            // another session destroyed the cluster. There is nothing more to
218            // do.
219            None => Ok(State::Unmodified),
220            Some(verified) => match ownership(&self.cluster, &verified)? {
221                // Only a process in the owner's namespace can stop the server:
222                // `pg_ctl` signals the PID in `postmaster.pid`, which means
223                // nothing – or something else entirely – in other namespaces.
224                // Leave it running; a session in the owner's namespace will
225                // stop it when that session ends.
226                Ownership::SameKernel | Ownership::OtherKernel(_) => {
227                    log::warn!(
228                        "Leaving cluster {} running: it was started in another namespace, \
229                         from where it must be stopped.",
230                        self.cluster.datadir.display()
231                    );
232                    Ok(State::Unmodified)
233                }
234                Ownership::SameNamespace | Ownership::None | Ownership::Copy => match self.finish {
235                    Finish::Stop => {
236                        let state = stop(&self.cluster)?;
237                        owner::release(&self.cluster.ownerfile())?;
238                        Ok(state)
239                    }
240                    Finish::Destroy => {
241                        stop(&self.cluster)?;
242                        let state = self.cluster.remove()?;
243                        remove_datadir(&self.cluster)?;
244                        drop(lock);
245                        Ok(state)
246                    }
247                },
248            },
249        }
250    }
251}
252
253impl Drop for Session {
254    fn drop(&mut self) {
255        if let Err(err) = self.shutdown() {
256            log::error!(
257                "Error ending session with cluster {}: {err}",
258                self.cluster.datadir.display()
259            );
260        }
261    }
262}
263
264impl ops::Deref for Session {
265    type Target = Cluster;
266
267    fn deref(&self) -> &Self::Target {
268        &self.cluster
269    }
270}
271
272// ----------------------------------------------------------------------------
273
274/// Open the cluster's lock file, creating it – and the data directory – if
275/// necessary.
276fn open_lockfile(cluster: &Cluster) -> Result<lock::UnlockedFile, ClusterError> {
277    let path = cluster.lockfile();
278    match lock::UnlockedFile::try_from(path.as_path()) {
279        // The data directory may have been removed by a session that destroyed
280        // the cluster.
281        Err(err) if err.kind() == io::ErrorKind::NotFound => {
282            fs::create_dir_all(&cluster.datadir)?;
283            Ok(lock::UnlockedFile::try_from(path.as_path())?)
284        }
285        result => Ok(result?),
286    }
287}
288
289/// Proof that this process holds a lock on the cluster's current lock file, as
290/// of when it was checked. Obtained only from [`verify`], and borrows the lock,
291/// so it cannot outlive it. Functions whose results are meaningful only while
292/// holding the lock, e.g. [`ownership`], require one.
293struct Verified<'a>(PhantomData<&'a ()>);
294
295/// Check that the locked file is still the cluster's lock file. It may have
296/// been removed – and maybe replaced – by a session that destroyed the cluster.
297fn verify<'a, L: lock::Held>(
298    cluster: &Cluster,
299    lock: &'a L,
300) -> Result<Option<Verified<'a>>, ClusterError> {
301    let locked = lock.as_ref().metadata()?;
302    let current = match fs::metadata(cluster.lockfile()) {
303        Ok(current) => current,
304        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
305        Err(err) => Err(err)?,
306    };
307    let same = locked.dev() == current.dev() && locked.ino() == current.ino();
308    Ok(same.then_some(Verified(PhantomData)))
309}
310
311/// Who owns the cluster, from the point of view of this process.
312enum Ownership {
313    /// No owner file: the cluster is not running, or was started without one,
314    /// e.g. by an older version of pgdo, or by hand.
315    None,
316    /// The owner file was copied from another data directory; ignore it.
317    Copy,
318    /// Owned from this namespace.
319    SameNamespace,
320    /// Owned from another namespace – e.g. another container – on this kernel.
321    SameKernel,
322    /// Owned from another kernel, e.g. a VM.
323    OtherKernel(owner::Found),
324}
325
326/// Who owns the cluster? Requires proof of a current lock on the cluster.
327///
328/// The answer may be out of date by the time the caller acts on it: another
329/// process could claim the cluster just after we look. That's safe:
330///
331/// - On this kernel, a process claims the cluster only while holding an
332///   exclusive lock, so no claim can happen while we hold any lock.
333/// - On another kernel, our lock means nothing, so a claim can happen at any
334///   time. But when there is no owner, the caller's next step is to claim the
335///   cluster itself, and only one claim can succeed. If ours fails, the caller
336///   looks again, and finds the new owner.
337fn ownership(cluster: &Cluster, _: &Verified<'_>) -> Result<Ownership, ClusterError> {
338    match owner::read(&cluster.ownerfile())? {
339        None => Ok(Ownership::None),
340        Some(found) => {
341            let current = owner::Record::current(&cluster.datadir)?;
342            Ok(match found.record.relation(&current) {
343                Relation::Copy => Ownership::Copy,
344                Relation::SameNamespace => Ownership::SameNamespace,
345                Relation::SameKernel => Ownership::SameKernel,
346                Relation::OtherKernel => Ownership::OtherKernel(found),
347            })
348        }
349    }
350}
351
352/// Is the cluster running? How we can tell depends on who owns it. Requires
353/// proof of a current lock on the cluster.
354fn running(
355    cluster: &Cluster,
356    ownership: &Ownership,
357    _: &Verified<'_>,
358) -> Result<bool, ClusterError> {
359    Ok(match ownership {
360        // In the same namespace, we can check the server's PID.
361        Ownership::SameNamespace => server_here(cluster, postmaster::check(&cluster.datadir)?)?,
362        // From another namespace, only the socket can tell us.
363        Ownership::SameKernel => server_elsewhere(cluster)?,
364        // With no (meaningful) owner, a server could have been started from
365        // any namespace, so check both ways.
366        Ownership::None | Ownership::Copy => {
367            server_here(cluster, postmaster::check(&cluster.datadir)?)?
368                || server_elsewhere(cluster)?
369        }
370        // We cannot tell. Callers must deal with this case first.
371        Ownership::OtherKernel(_) => unreachable!("cannot tell if cluster runs on another kernel"),
372    })
373}
374
375/// Is a server for this cluster running in a namespace where we can signal it,
376/// i.e. where its PID in `postmaster.pid` means something?
377fn server_here(cluster: &Cluster, postmaster: Postmaster) -> Result<bool, ClusterError> {
378    match postmaster {
379        Postmaster::Running(_) => Ok(true),
380        Postmaster::Absent | Postmaster::Dead(_) | Postmaster::Other(_) => Ok(false),
381        // We cannot check the PID on this platform, so fall back to `pg_ctl
382        // status`, which trusts it.
383        Postmaster::Unknown(_) => cluster.running(),
384    }
385}
386
387/// Is a server for this cluster running, perhaps in another namespace, where
388/// its PID in `postmaster.pid` means nothing to us? Only its socket can tell.
389///
390/// The socket's name comes from the port in `postmaster.pid`, in case the
391/// server was started on a port other than [`PORT`][super::PORT]. But not the
392/// socket's directory: that is a path in the server's namespace, which may name
393/// another place here, e.g. when the data directory is a bind mount. pgdo puts
394/// the socket in the data directory, so look there.
395fn server_elsewhere(cluster: &Cluster) -> Result<bool, ClusterError> {
396    match postmaster::read(&cluster.datadir)? {
397        // A running server always has a `postmaster.pid`.
398        None => Ok(false),
399        Some(pidfile) => {
400            let port = pidfile.port.unwrap_or(super::PORT);
401            client::accepts_connections(&cluster.datadir, port).map_err(|source| {
402                ClusterError::ServerStateUnknown {
403                    path: client::socket_path(&cluster.datadir, port),
404                    source,
405                }
406            })
407        }
408    }
409}
410
411/// Stop the cluster's server, if there is one. Never signal a process that is
412/// not a PostgreSQL server for this cluster, e.g. one that reused the PID of a
413/// server that has gone.
414fn stop(cluster: &Cluster) -> Result<State, ClusterError> {
415    match postmaster::check(&cluster.datadir)? {
416        Postmaster::Running(_) | Postmaster::Unknown(_) => cluster.stop(),
417        Postmaster::Absent | Postmaster::Dead(_) => Ok(State::Unmodified),
418        Postmaster::Other(pid) => {
419            log::warn!(
420                "Not stopping cluster {}: its postmaster.pid names PID {pid}, which is not \
421                 a PostgreSQL server for this cluster.",
422                cluster.datadir.display()
423            );
424            Ok(State::Unmodified)
425        }
426    }
427}
428
429/// Refuse to use a cluster owned by another kernel, unless taking over is
430/// allowed. Whether to take over is then decided by observing the owner file.
431fn refuse_other_kernel(found: &owner::Found, takeover: Takeover) -> Result<(), ClusterError> {
432    let (hostname, age) = (found.record.hostname.clone(), found.age);
433    match takeover {
434        Takeover::IfStale => Ok(()),
435        Takeover::Never if found.is_fresh() => Err(ClusterError::InUseElsewhere { hostname, age }),
436        Takeover::Never => Err(ClusterError::StaleElsewhere { hostname, age }),
437    }
438}
439
440/// Sleep for a random time between 200ms and 1000ms. When many processes
441/// compete, this helps one of them rapidly acquire an exclusive lock and create
442/// and start the cluster.
443fn backoff() {
444    let delay = 200 + (rand::rng().next_u32() % 800);
445    std::thread::sleep(Duration::from_millis(u64::from(delay)));
446}
447
448/// How long to watch a stale owner file from another kernel before taking over.
449/// Much shorter in unit tests.
450const OBSERVE_BEFORE_TAKEOVER: Duration = if cfg!(test) {
451    Duration::from_millis(300)
452} else {
453    owner::OBSERVE_BEFORE_TAKEOVER
454};
455
456/// Start sending heartbeats for the cluster. Do this as soon as a session owns
457/// the cluster, or joins one that is running.
458fn heartbeat(cluster: &Cluster) -> owner::Heartbeat {
459    owner::Heartbeat::start(cluster.ownerfile(), owner::HEARTBEAT_INTERVAL)
460}
461
462/// Downgrade an exclusive lock to a shared lock, and start sending heartbeats.
463/// `flock` does not do this atomically: it releases the exclusive lock then
464/// takes a shared lock. In between, another session could stop – or even
465/// destroy – the cluster, so check again: returns `None` if the cluster is not
466/// running, or the lock file is not current.
467fn downgrade(
468    cluster: &Cluster,
469    lock: lock::LockedFileExclusive,
470    ownership: &Ownership,
471    heartbeat: owner::Heartbeat,
472) -> Result<Option<(lock::LockedFileShared, owner::Heartbeat)>, ClusterError> {
473    let lock = lock.lock_shared()?;
474    match verify(cluster, &lock)? {
475        Some(verified) if running(cluster, ownership, &verified)? => Ok(Some((lock, heartbeat))),
476        Some(_) | None => Ok(None),
477    }
478}
479
480/// Take over a cluster owned by another kernel, after watching its owner file
481/// for signs of life. Call this only with an exclusive lock, and only when
482/// taking over is allowed; see [`refuse_other_kernel`].
483fn take_over(
484    cluster: &Cluster,
485    found: &owner::Found,
486    interrupted: Interrupted<'_>,
487) -> Result<(), ClusterError> {
488    // Its owner's clock may disagree with ours, or its owner may be slow, so
489    // watch for heartbeats before taking over, whatever the owner file's age.
490    let ownerfile = cluster.ownerfile();
491    let hostname = &found.record.hostname;
492    log::warn!(
493        "Checking that cluster {} is no longer in use on {hostname}; this takes {}s.",
494        cluster.datadir.display(),
495        OBSERVE_BEFORE_TAKEOVER.as_secs(),
496    );
497    match owner::observe(&ownerfile, OBSERVE_BEFORE_TAKEOVER, interrupted)? {
498        owner::Observed::Changed => {
499            Err(ClusterError::InUseElsewhere { hostname: hostname.clone(), age: Duration::ZERO })
500        }
501        // The owner gave up the cluster.
502        owner::Observed::Gone => Ok(()),
503        // Someone had second thoughts about taking over.
504        owner::Observed::Interrupted => Err(ClusterError::Interrupted),
505        owner::Observed::Unchanged => {
506            log::warn!(
507                "Taking over cluster {} from {hostname}; last heartbeat {}.",
508                cluster.datadir.display(),
509                owner::ago(found.age),
510            );
511            Ok(owner::release(&ownerfile)?)
512        }
513    }
514}
515
516/// Claim ownership and start the cluster, or – if a server is running without
517/// an owner, e.g. one started by an older pgdo, or by hand – claim it and join
518/// it. Call this only with an exclusive lock, when there is no owner. Returns
519/// `None` if the caller should try again.
520fn start_or_join(
521    cluster: &Cluster,
522    lock: lock::LockedFileExclusive,
523    options: Options<'_>,
524    interrupted: Interrupted<'_>,
525) -> Result<Option<(lock::LockedFileShared, owner::Heartbeat)>, ClusterError> {
526    let ownerfile = cluster.ownerfile();
527    let postmaster = postmaster::check(&cluster.datadir)?;
528    if let Postmaster::Other(pid) = postmaster {
529        // `pg_ctl` would think this unrelated process is our server, and
530        // PostgreSQL would refuse to start.
531        Err(ClusterError::StalePidFile { pid })
532    } else {
533        // If a server is running, claim it so that other kernels see that it is
534        // in use, then join it. If we can see it only via its socket, it is in
535        // another namespace, which the claim must say.
536        let current = owner::Record::current(&cluster.datadir)?;
537        let joining = if server_here(cluster, postmaster)? {
538            Some(current.clone())
539        } else if server_elsewhere(cluster)? {
540            Some(current.clone().with_unknown_namespace())
541        } else {
542            None
543        };
544        if interrupted() {
545            Err(ClusterError::Interrupted)
546        } else if let Some(record) = joining {
547            if owner::claim(&ownerfile, &record)? {
548                let ownership = match verify(cluster, &lock)? {
549                    Some(verified) => ownership(cluster, &verified)?,
550                    None => return Ok(None),
551                };
552                downgrade(cluster, lock, &ownership, heartbeat(cluster))
553            } else {
554                // Another process claimed it first – which can happen only from
555                // another kernel, where our lock means nothing.
556                Ok(None)
557            }
558        } else if owner::claim(&ownerfile, &current)? {
559            // Start the heartbeat now: starting the cluster can take a while,
560            // e.g. during crash recovery.
561            let heartbeat = heartbeat(cluster);
562            match cluster.start(options) {
563                // Interrupted, e.g. by Ctrl-C, which also kills `pg_ctl`.
564                // Either way, do not leave a server running that no one is
565                // using.
566                Ok(_) | Err(_) if interrupted() => {
567                    abandon_start(cluster, heartbeat)?;
568                    Err(ClusterError::Interrupted)
569                }
570                Err(err) => {
571                    abandon_start(cluster, heartbeat)?;
572                    Err(err)
573                }
574                Ok(_) => downgrade(cluster, lock, &Ownership::SameNamespace, heartbeat),
575            }
576        } else {
577            // As above: another kernel claimed it first.
578            Ok(None)
579        }
580    }
581}
582
583/// Abandon starting the cluster, e.g. because `pg_ctl start` failed, or the
584/// user interrupted it. Call this only after claiming ownership and trying to
585/// start the cluster, while holding an exclusive lock.
586///
587/// If our server is running – `pg_ctl start` may give up waiting, or be killed,
588/// while the server carries on starting – stop it, so that no server is left
589/// running with no one using it, then release our claim. If it cannot be
590/// stopped, keep our claim: other kernels must not start another server.
591fn abandon_start(cluster: &Cluster, heartbeat: owner::Heartbeat) -> Result<(), ClusterError> {
592    let stopped = match postmaster::check(&cluster.datadir)? {
593        Postmaster::Absent | Postmaster::Dead(_) | Postmaster::Other(_) => true,
594        // We claimed the cluster and started its server from this namespace,
595        // so this is our server.
596        Postmaster::Running(_) | Postmaster::Unknown(_) => match cluster.stop() {
597            Ok(_) => true,
598            Err(err) => {
599                log::warn!(
600                    "Could not stop cluster {}, which may still be starting; leaving the \
601                     cluster claimed: {err}",
602                    cluster.datadir.display()
603                );
604                false
605            }
606        },
607    };
608    if stopped {
609        drop(heartbeat);
610        Ok(owner::release(&cluster.ownerfile())?)
611    } else {
612        Ok(())
613    }
614}
615
616/// Checks whether startup has been interrupted. See [`interrupt`].
617type Interrupted<'a> = &'a dyn Fn() -> bool;
618
619/// Take a shared lock, waiting while another process holds an exclusive lock,
620/// e.g. while it starts the cluster. Polls, rather than blocks, so that it can
621/// be interrupted.
622fn lock_shared(
623    mut lock: lock::UnlockedFile,
624    interrupted: Interrupted<'_>,
625) -> Result<lock::LockedFileShared, ClusterError> {
626    loop {
627        match lock.try_lock_shared()? {
628            Right(lock) => return Ok(lock),
629            Left(_) if interrupted() => return Err(ClusterError::Interrupted),
630            Left(unlocked) => {
631                lock = unlocked;
632                std::thread::sleep(Duration::from_millis(50));
633                continue;
634            }
635        }
636    }
637}
638
639/// Obtain a shared lock on the cluster, creating and starting it if necessary,
640/// and start sending heartbeats.
641fn startup(
642    cluster: &Cluster,
643    options: Options<'_>,
644    takeover: Takeover,
645    interrupted: Interrupted<'_>,
646) -> Result<(lock::LockedFileShared, owner::Heartbeat), ClusterError> {
647    loop {
648        if interrupted() {
649            return Err(ClusterError::Interrupted);
650        } else {
651            match open_lockfile(cluster)?.try_lock_exclusive()? {
652                Left(lock) => {
653                    // The cluster is locked elsewhere, shared or exclusively.
654                    // We optimistically take a shared lock. If the other lock
655                    // is also shared, this will not wait. If the other lock is
656                    // exclusive, this will wait until that lock is released (or
657                    // changed to a shared lock).
658                    let lock = lock_shared(lock, interrupted)?;
659                    match verify(cluster, &lock)? {
660                        // The lock file was removed while we waited; try again.
661                        None => continue,
662                        Some(verified) => {
663                            // If obtaining the lock blocked, i.e. the lock
664                            // elsewhere was exclusive, then the cluster may
665                            // have been started by the process that held that
666                            // exclusive lock. We should check.
667                            let ownership = ownership(cluster, &verified)?;
668                            if let Ownership::OtherKernel(found) = &ownership {
669                                // Taking over needs an exclusive lock. Release
670                                // ours, back off, and try again for one.
671                                refuse_other_kernel(found, takeover)?;
672                                drop(lock);
673                                backoff();
674                                continue;
675                            } else if running(cluster, &ownership, &verified)? {
676                                return Ok((lock, heartbeat(cluster)));
677                            } else {
678                                // Release all locks, back off, and try again.
679                                drop(lock);
680                                backoff();
681                                continue;
682                            }
683                        }
684                    }
685                }
686                Right(lock) => {
687                    match verify(cluster, &lock)? {
688                        // The lock file was removed before we locked it; try
689                        // again.
690                        None => continue,
691                        Some(verified) => {
692                            let ownerfile = cluster.ownerfile();
693                            match ownership(cluster, &verified)? {
694                                Ownership::OtherKernel(found) => {
695                                    refuse_other_kernel(&found, takeover)?;
696                                    take_over(cluster, &found, interrupted)?;
697                                    continue;
698                                }
699                                Ownership::Copy => {
700                                    owner::release(&ownerfile)?;
701                                    continue;
702                                }
703                                ownership @ (Ownership::SameNamespace | Ownership::SameKernel) => {
704                                    if running(cluster, &ownership, &verified)? {
705                                        // Use the running server.
706                                        match downgrade(
707                                            cluster,
708                                            lock,
709                                            &ownership,
710                                            heartbeat(cluster),
711                                        )? {
712                                            Some(joined) => return Ok(joined),
713                                            None => continue,
714                                        }
715                                    } else {
716                                        // The owner's server has gone, e.g. it
717                                        // crashed. Our exclusive lock shows
718                                        // that no session on this kernel is
719                                        // using the cluster, so we can take
720                                        // over.
721                                        owner::release(&ownerfile)?;
722                                        continue;
723                                    }
724                                }
725                                Ownership::None => {
726                                    match start_or_join(cluster, lock, options, interrupted)? {
727                                        Some(started_or_joined) => return Ok(started_or_joined),
728                                        None => continue,
729                                    }
730                                }
731                            }
732                        }
733                    }
734                }
735            }
736        }
737    }
738}
739
740/// Try to upgrade a shared lock to an exclusive lock, without blocking. Returns
741/// `None` if another process holds a lock, in which case ours is released.
742///
743/// `flock` does not convert locks atomically, and platforms differ when a
744/// conversion fails: Linux has then released the shared lock, but macOS keeps
745/// it. On macOS, two sessions ending at the same moment would each block the
746/// other's upgrade, and neither would stop the cluster. So unlock, and try once
747/// more: of two sessions doing this at once, the last to try will succeed.
748fn upgrade(
749    lock: lock::LockedFileShared,
750) -> Result<Option<lock::LockedFileExclusive>, ClusterError> {
751    match lock.try_lock_exclusive()? {
752        Right(lock) => Ok(Some(lock)),
753        Left(lock) => Ok(lock.unlock()?.try_lock_exclusive()?.right()),
754    }
755}
756
757/// Remove the cluster's owner file, lock file, and data directory. Call this
758/// only while holding an exclusive lock, after destroying the cluster.
759fn remove_datadir(cluster: &Cluster) -> Result<(), ClusterError> {
760    owner::release(&cluster.ownerfile())?;
761    match fs::remove_file(cluster.lockfile()) {
762        Err(err) if err.kind() != io::ErrorKind::NotFound => Err(err)?,
763        _ => (),
764    }
765    // Use `remove_dir`, not `remove_dir_all`: if another process has created
766    // something here in the meantime, e.g. a new lock file, leave it be.
767    match fs::remove_dir(&cluster.datadir) {
768        Err(err)
769            if matches!(
770                err.kind(),
771                io::ErrorKind::NotFound | io::ErrorKind::DirectoryNotEmpty
772            ) =>
773        {
774            Ok(())
775        }
776        result => Ok(result?),
777    }
778}
779
780#[cfg(test)]
781mod tests {
782    use std::time::{Duration, SystemTime};
783
784    use super::{ClusterError, Takeover};
785    use crate::cluster::{Cluster, ClusterStatus, State};
786    use crate::runtime::strategy::Strategy;
787
788    type TestResult = Result<(), Box<dyn std::error::Error>>;
789
790    /// Create a stopped cluster with an owner file that appears to be from
791    /// another kernel, last updated an hour ago.
792    fn cluster_owned_by_other_kernel(datadir: &std::path::Path) -> TestResult {
793        let session = Cluster::new(datadir, Strategy::default())?.session(&[])?;
794        let ours = std::fs::read_to_string(datadir.join("pgdo.owner"))?;
795        assert_eq!(session.end()?, State::Modified);
796        let theirs = ours
797            .lines()
798            .filter(|line| !line.starts_with("boot_id=") && !line.starts_with("hostname="))
799            .chain(["boot_id=some-other-kernel", "hostname=elsewhere"])
800            .collect::<Vec<_>>()
801            .join("\n")
802            + "\n";
803        let ownerfile = datadir.join("pgdo.owner");
804        std::fs::write(&ownerfile, theirs)?;
805        let file = std::fs::File::options().write(true).open(&ownerfile)?;
806        file.set_modified(SystemTime::now() - Duration::from_secs(3600))?;
807        Ok(())
808    }
809
810    #[test]
811    fn session_takes_over_stale_cluster_from_other_kernel_without_heartbeats() -> TestResult {
812        let tempdir = tempfile::tempdir()?;
813        let datadir = tempdir.path().join("data");
814        cluster_owned_by_other_kernel(&datadir)?;
815        let session = Cluster::new(&datadir, Strategy::default())?
816            .session_with_takeover(&[], Takeover::IfStale)?;
817        assert_eq!(session.status()?, ClusterStatus::Running);
818        let record = std::fs::read_to_string(datadir.join("pgdo.owner"))?;
819        assert!(!record.contains("some-other-kernel"));
820        assert_eq!(session.end()?, State::Modified);
821        Ok(())
822    }
823
824    /// If the owner's clock is ahead of ours, its owner file looks fresh – even
825    /// from the future – for a long time. Taking over relies on observing the
826    /// owner file, not on its age.
827    #[test]
828    fn session_takes_over_from_other_kernel_with_clock_ahead() -> TestResult {
829        let tempdir = tempfile::tempdir()?;
830        let datadir = tempdir.path().join("data");
831        cluster_owned_by_other_kernel(&datadir)?;
832        let file = std::fs::File::options()
833            .write(true)
834            .open(datadir.join("pgdo.owner"))?;
835        file.set_modified(SystemTime::now() + Duration::from_secs(3600))?;
836        // Without taking over: refused as in use.
837        assert!(matches!(
838            Cluster::new(&datadir, Strategy::default())?.session(&[]),
839            Err(ClusterError::InUseElsewhere { .. })
840        ));
841        // Taking over: no signs of life, so it is taken over.
842        let session = Cluster::new(&datadir, Strategy::default())?
843            .session_with_takeover(&[], Takeover::IfStale)?;
844        assert_eq!(session.status()?, ClusterStatus::Running);
845        assert_eq!(session.end()?, State::Modified);
846        Ok(())
847    }
848
849    /// Someone runs with `--force`, then thinks better of it and presses
850    /// Ctrl-C while pgdo watches the owner file. Nothing must be taken over.
851    #[test]
852    fn session_interrupted_while_watching_does_not_take_over() -> TestResult {
853        let tempdir = tempfile::tempdir()?;
854        let datadir = tempdir.path().join("data");
855        cluster_owned_by_other_kernel(&datadir)?;
856        let before = std::fs::read_to_string(datadir.join("pgdo.owner"))?;
857        let started = std::time::Instant::now();
858        let result = Cluster::new(&datadir, Strategy::default())?.start_session(
859            &[],
860            Takeover::IfStale,
861            &|| started.elapsed() > Duration::from_millis(50),
862        );
863        assert!(matches!(result, Err(ClusterError::Interrupted)));
864        assert_eq!(std::fs::read_to_string(datadir.join("pgdo.owner"))?, before);
865        let status = Cluster::new(&datadir, Strategy::default())?.status()?;
866        assert_eq!(status, ClusterStatus::Stopped);
867        Ok(())
868    }
869
870    /// Interrupted just as the server has started, i.e. after `pg_ctl start`
871    /// has returned: stop the server, and release the claim. (An interrupt
872    /// while `pg_ctl start` waits – e.g. Ctrl-C, which kills `pg_ctl` – makes
873    /// it fail, which the same path handles.)
874    #[test]
875    fn session_interrupted_after_starting_stops_server() -> TestResult {
876        let tempdir = tempfile::tempdir()?;
877        let datadir = tempdir.path().join("data");
878        let pidfile = datadir.join("postmaster.pid");
879        let result = Cluster::new(&datadir, Strategy::default())?.start_session(
880            &[],
881            Takeover::Never,
882            &|| pidfile.exists(),
883        );
884        assert!(matches!(result, Err(ClusterError::Interrupted)));
885        assert!(!datadir.join("pgdo.owner").exists());
886        let status = Cluster::new(&datadir, Strategy::default())?.status()?;
887        assert_eq!(status, ClusterStatus::Stopped);
888        Ok(())
889    }
890
891    /// Interrupted while waiting for another process's exclusive lock, e.g.
892    /// while it starts the cluster.
893    #[test]
894    fn session_interrupted_while_waiting_for_lock() -> TestResult {
895        let tempdir = tempfile::tempdir()?;
896        let datadir = tempdir.path().join("data");
897        std::fs::create_dir(&datadir)?;
898        let lockfile = datadir.join("pgdo.lock");
899        let _exclusive =
900            crate::lock::UnlockedFile::try_from(lockfile.as_path())?.lock_exclusive()?;
901        let started = std::time::Instant::now();
902        let result = Cluster::new(&datadir, Strategy::default())?.start_session(
903            &[],
904            Takeover::Never,
905            &|| started.elapsed() > Duration::from_millis(200),
906        );
907        assert!(matches!(result, Err(ClusterError::Interrupted)));
908        assert!(started.elapsed() < Duration::from_secs(3));
909        assert!(!datadir.join("pgdo.owner").exists());
910        Ok(())
911    }
912
913    /// Stops a cluster when dropped.
914    struct StopOnDrop<'a>(&'a Cluster);
915
916    impl Drop for StopOnDrop<'_> {
917        fn drop(&mut self) {
918            if let Err(err) = self.0.stop() {
919                eprintln!("Could not stop cluster: {err}");
920            }
921        }
922    }
923
924    /// Simulate a session destroying the cluster – removing its lock file –
925    /// while another session waits for the lock, and a third session starting
926    /// the cluster afresh, with a new lock file, before the waiting session
927    /// wakes. The waiting session must notice that the file it locked has
928    /// gone, and lock the current file instead. Otherwise it would hold a lock
929    /// no one else can see, and the third session – believing itself alone –
930    /// could stop the cluster under it.
931    #[test]
932    fn session_locks_current_lock_file_when_waiting_through_destroy() -> TestResult {
933        use crate::lock::UnlockedFile;
934        use std::os::unix::fs::MetadataExt;
935
936        let tempdir = tempfile::tempdir()?;
937        let datadir = tempdir.path().join("data");
938        std::fs::create_dir(&datadir)?;
939        let lockfile = datadir.join("pgdo.lock");
940
941        // Play the destroying session: hold an exclusive lock on the lock file.
942        let old_lock = UnlockedFile::try_from(lockfile.as_path())?.lock_exclusive()?;
943        let old_ino = std::fs::metadata(&lockfile)?.ino();
944
945        let waiting_cluster = Cluster::new(&datadir, Strategy::default())?;
946        let starting_cluster = Cluster::new(&datadir, Strategy::default())?;
947        // However this test ends, do not leave a server running in a data
948        // directory that is about to be deleted.
949        let _stop = StopOnDrop(&starting_cluster);
950        let (session, new_lock) = std::thread::scope(|scope| {
951            let waiting =
952                scope.spawn(|| waiting_cluster.start_session(&[], Takeover::Never, &|| false));
953            // Give the waiting session time to wait on the exclusive lock.
954            std::thread::sleep(Duration::from_millis(500));
955            assert!(!waiting.is_finished());
956            // Finish "destroying": remove the lock file.
957            std::fs::remove_file(&lockfile)?;
958            // Play the third session: create a new lock file, lock it, and
959            // start the cluster, then downgrade to a shared lock.
960            let new_lock = UnlockedFile::try_from(lockfile.as_path())?.lock_exclusive()?;
961            starting_cluster.start(&[])?;
962            let new_lock = new_lock.lock_shared()?;
963            // Now release the old lock, waking the waiting session.
964            drop(old_lock);
965            let session = waiting.join().unwrap()?;
966            Ok::<_, Box<dyn std::error::Error>>((session, new_lock))
967        })?;
968        assert_ne!(std::fs::metadata(&lockfile)?.ino(), old_ino);
969
970        // The third session ends. The waiting session must hold a lock on the
971        // current lock file, so an exclusive lock – which the third session
972        // would need to stop the cluster – is not available.
973        drop(new_lock);
974        let other = UnlockedFile::try_from(lockfile.as_path())?;
975        assert!(other.try_lock_exclusive()?.is_left());
976        assert_eq!(session.status()?, ClusterStatus::Running);
977
978        // Ending the session stops the cluster.
979        assert_eq!(session.end()?, State::Modified);
980        Ok(())
981    }
982
983    /// Clocks on different kernels can disagree, e.g. a VM's after its host
984    /// sleeps, so a live owner's heartbeats can look stale. Before taking over,
985    /// a session watches for heartbeats, whatever their times.
986    #[test]
987    fn session_does_not_take_over_from_other_kernel_with_heartbeats() -> TestResult {
988        let tempdir = tempfile::tempdir()?;
989        let datadir = tempdir.path().join("data");
990        cluster_owned_by_other_kernel(&datadir)?;
991        let ownerfile = datadir.join("pgdo.owner");
992        let before = std::fs::read_to_string(&ownerfile)?;
993
994        // Heartbeats from a kernel whose clock is an hour behind.
995        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
996        let beating = {
997            let (ownerfile, stop) = (ownerfile.clone(), stop.clone());
998            std::thread::spawn(move || {
999                let base = SystemTime::now() - Duration::from_secs(3600);
1000                for i in 1.. {
1001                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
1002                        break;
1003                    } else {
1004                        let file = std::fs::File::options()
1005                            .write(true)
1006                            .open(&ownerfile)
1007                            .unwrap();
1008                        file.set_modified(base + Duration::from_millis(i * 50))
1009                            .unwrap();
1010                        std::thread::sleep(Duration::from_millis(50));
1011                        continue;
1012                    }
1013                }
1014            })
1015        };
1016        let result = Cluster::new(&datadir, Strategy::default())?
1017            .session_with_takeover(&[], Takeover::IfStale);
1018        stop.store(true, std::sync::atomic::Ordering::Relaxed);
1019        beating.join().unwrap();
1020
1021        assert!(matches!(
1022            result,
1023            Err(ClusterError::InUseElsewhere { hostname, .. }) if hostname == "elsewhere"
1024        ));
1025        assert_eq!(std::fs::read_to_string(&ownerfile)?, before);
1026        let status = Cluster::new(&datadir, Strategy::default())?.status()?;
1027        assert_eq!(status, ClusterStatus::Stopped);
1028        Ok(())
1029    }
1030
1031    /// Two sessions ending at the same moment must not both fail to upgrade
1032    /// their locks, or neither would stop the cluster.
1033    #[test]
1034    fn upgrade_succeeds_for_one_of_two_sessions_ending_together() -> TestResult {
1035        use std::sync::{Arc, Barrier};
1036        let tempdir = tempfile::tempdir()?;
1037        let path = tempdir.path().join("pgdo.lock");
1038        for _ in 0..200 {
1039            let barrier = Arc::new(Barrier::new(2));
1040            let ending = [0, 1].map(|_| {
1041                let lock = crate::lock::UnlockedFile::try_from(path.as_path())
1042                    .and_then(|lock| Ok(lock.lock_shared()?));
1043                let barrier = Arc::clone(&barrier);
1044                std::thread::spawn(move || {
1045                    let lock = lock.unwrap();
1046                    barrier.wait();
1047                    // Hold any exclusive lock until both have tried.
1048                    let upgraded = super::upgrade(lock).unwrap();
1049                    std::thread::sleep(std::time::Duration::from_millis(1));
1050                    upgraded.is_some()
1051                })
1052            });
1053            let upgraded = ending.map(|thread| thread.join().unwrap());
1054            assert!(
1055                upgraded.contains(&true),
1056                "neither session upgraded its lock"
1057            );
1058        }
1059        Ok(())
1060    }
1061}