Skip to main content

Module session

Module session 

Source
Expand description

Use a cluster safely alongside other processes.

A Session creates and starts a cluster as necessary, and stops it – or destroys it – when the session ends, unless other sessions are still using it. Many processes can hold sessions on the same cluster at once, e.g. as part of a test suite; the last one out turns off the lights.

let tempdir = tempfile::tempdir()?;
let cluster = Cluster::new(tempdir.path().join("data"), Strategy::default())?;
let session = cluster.session(&[])?;
assert!(session.running()?);
let databases = session.databases()?;
session.end()?; // Or drop it; see `Session::end` for the difference.

Coordination uses flock(2) locks on the file pgdo.lock in the cluster’s data directory: a shared lock while the session is held; an exclusive lock to create and start the cluster, and to stop or destroy it. Because the lock file lives in the data directory, it works for any process that can see that directory, whatever path it uses to get there, as long as flock works on the filesystem and all processes run on the same kernel.

flock does not work between kernels, e.g. between macOS and a Linux VM, and PostgreSQL’s own check for a running server does not work between PID namespaces, e.g. between containers. So a session that starts a cluster also records its owner in pgdo.owner, and sessions refuse to use a cluster owned by another kernel; see Takeover. On the same kernel, a session in another namespace can use a running cluster via its Unix-domain socket, but only a session in the owner’s namespace will stop it.

When a session destroys a cluster it removes the lock file too. Another process might be waiting on that lock file, or might create a new one meanwhile, so after taking any lock, a session checks that the file it has locked is still the file at pgdo.lock; if not, it tries again.

Starting, ending, and dropping a session all block, sometimes for a while: they may wait for other processes to release locks, and they run pg_ctl. This is safe within an async context, but blocks the current thread; to avoid that, start and end sessions within something like Tokio’s spawn_blocking. See also Blocking.

Structs§

Session
A cluster that this process is using. See the module documentation.

Enums§

Finish
What to do with a cluster when a Session ends and no other sessions are using the cluster.
Takeover
Whether a Session may take over a cluster that was last used on another host or VM, i.e. from another kernel.

Functions§

interrupt
Ask sessions that are starting up in this process to give up as soon as they safely can, e.g. when the user presses Ctrl-C.