forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

mod.rs196 lines, 7.3 KiBHistoryRawDownload
1//! The operator command line: the words `iz` takes after its options, the lock that keeps two processes off
2//! one data directory, and the helpers the commands share.
3//!
4//! Commands: `iz [--config <path>] [serve]` runs the server (a bare `iz` does the same), `export --out <dir>`
5//! writes the board to a new directory, `restore --from <set dir>` replaces the database and attachments
6//! with a verified backup set, and `fsck` checks the database and attachments without changing them. The
7//! configuration file is the `--config` path, then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is
8//! success, 1 a failure, 2 a usage error.
9//!
10//! The lock: every command that touches the data directory takes an exclusive lock on `iz.lock` inside it,
11//! held for the life of the process. A second process that finds the lock taken stops at once. What it is
12//! not: the lock does not protect the files from other users; the data directory is mode 0700 for that.
13
14pub mod export;
15pub mod fsck;
16pub mod restore;
17
18use std::fs::{File, OpenOptions, TryLockError};
19use std::os::unix::fs::OpenOptionsExt;
20use std::path::{Path, PathBuf};
21use std::process::ExitCode;
22
23use clap::{Parser, Subcommand};
24use iz_core::config::Config;
25use iz_core::secret;
26
27use crate::boot::KEY_FILE;
28
29/// The file inside the data directory that carries the process lock.
30pub const LOCK_FILE: &str = "iz.lock";
31
32/// The line printed when another process holds the lock. Operators search for it, so it is fixed.
33pub const BUSY_MESSAGE: &str = "iz is already running on this data directory; stop it (systemctl stop iz) before running this command";
34
35/// The configuration file when neither `--config` nor `IZ_CONFIG` names one.
36pub const DEFAULT_CONFIG: &str = "config/iz.toml";
37
38/// The environment variable that names the configuration file.
39pub const CONFIG_ENV: &str = "IZ_CONFIG";
40
41/// The parsed command line. `--config` is global, so it works before or after the command word.
42#[derive(Debug, Parser)]
43#[command(
44 name = "iz",
45 about = "The iz task board: the server and its operator commands"
46)]
47pub struct Cli {
48 /// The configuration file. Without it, `IZ_CONFIG`, then `config/iz.toml`.
49 #[arg(long, global = true, value_name = "PATH")]
50 pub config: Option<PathBuf>,
51 /// What to do. Without a command the server runs.
52 #[command(subcommand)]
53 pub command: Option<Command>,
54}
55
56/// The commands. `Serve` is the default.
57#[derive(Debug, Subcommand)]
58pub enum Command {
59 /// Runs the server until SIGTERM or Ctrl-C.
60 Serve,
61 /// Writes the board, its attachments and a manifest into a new directory.
62 Export {
63 /// The directory to create. It must not exist or must be empty.
64 #[arg(long, value_name = "DIR")]
65 out: PathBuf,
66 },
67 /// Replaces the database and attachments with a verified backup set. The previous files are kept.
68 Restore {
69 /// The backup set directory: `manifest.json` and the files it lists.
70 #[arg(long, value_name = "DIR")]
71 from: PathBuf,
72 },
73 /// Checks the database and the attachments without changing anything. `--remote` also downloads the
74 /// attachments held at the Files service and checks them, which needs the Files service configured.
75 Fsck {
76 /// Download and check the attachments held at the Files service.
77 #[arg(long)]
78 remote: bool,
79 },
80}
81
82/// The configuration path: the flag, else `IZ_CONFIG`, else the default.
83pub fn config_path(flag: Option<PathBuf>) -> PathBuf {
84 flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from))
85 .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG))
86}
87
88/// Takes the exclusive lock on `data_dir/iz.lock`. The returned file holds the lock until it is dropped,
89/// so bind it to a variable that lives as long as the work does. A busy lock gives [`BUSY_MESSAGE`]; any
90/// other failure names the lock file.
91pub fn lock_data_dir(data_dir: &Path) -> Result<File, String> {
92 let path = data_dir.join(LOCK_FILE);
93 // Mode 0600: only this user reads the lock file. `truncate(false)` keeps whatever the file holds.
94 let file = OpenOptions::new()
95 .read(true)
96 .write(true)
97 .create(true)
98 .truncate(false)
99 .mode(0o600)
100 .open(&path)
101 .map_err(|error| format!("iz: cannot open the lock file {}: {error}", path.display()))?;
102 match file.try_lock() {
103 Ok(()) => Ok(file),
104 Err(TryLockError::WouldBlock) => Err(BUSY_MESSAGE.to_owned()),
105 Err(TryLockError::Error(error)) => {
106 Err(format!("iz: cannot lock {}: {error}", path.display()))
107 }
108 }
109}
110
111/// Prints the failure of [`lock_data_dir`] and gives the exit status 1.
112pub fn take_lock(data_dir: &Path) -> Result<File, ExitCode> {
113 lock_data_dir(data_dir).map_err(|message| {
114 eprintln!("{message}");
115 ExitCode::FAILURE
116 })
117}
118
119/// Prints `iz: <message>` to stderr and gives the exit status 1.
120pub fn fail(message: impl std::fmt::Display) -> ExitCode {
121 eprintln!("iz: {message}");
122 ExitCode::FAILURE
123}
124
125/// The text of an iz-core error for the user. A refused set or an invalid value is shown as its text
126/// alone; everything else keeps its prefix.
127pub fn describe(error: &iz_core::Error) -> String {
128 match error {
129 iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => text.clone(),
130 other => other.to_string(),
131 }
132}
133
134/// The data directory as an absolute path. It must exist: the commands that call this never create it.
135pub fn existing_data_dir(config: &Config) -> Result<PathBuf, String> {
136 config.data_dir.canonicalize().map_err(|error| {
137 format!(
138 "the data directory {} cannot be used: {error}",
139 config.data_dir.display()
140 )
141 })
142}
143
144/// The instance key read from the data directory. It must exist: the commands that call this check or write
145/// manifests under it, and never create a key on the way.
146pub fn instance_key(data_dir: &Path) -> Result<[u8; 32], String> {
147 let path = data_dir.join(KEY_FILE);
148 secret::read_key(&path).map_err(|error| {
149 format!(
150 "the instance key {} cannot be used: {}",
151 path.display(),
152 describe(&error)
153 )
154 })
155}
156
157/// The database path, checked to be a regular file that is not a link. Nothing is created.
158pub fn database_file(config: &Config) -> Result<PathBuf, String> {
159 let meta = std::fs::symlink_metadata(&config.database).map_err(|error| {
160 format!(
161 "the database {} cannot be read: {error}",
162 config.database.display()
163 )
164 })?;
165 if !meta.file_type().is_file() {
166 return Err(format!(
167 "the database {} is not a regular file",
168 config.database.display()
169 ));
170 }
171 Ok(config.database.clone())
172}
173
174/// A UTC stamp that is safe in a file name: `20261028T093015Z`.
175pub fn file_stamp() -> String {
176 jiff::Timestamp::now()
177 .strftime("%Y%m%dT%H%M%SZ")
178 .to_string()
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn a_held_lock_is_refused_and_released_on_drop() {
187 let dir = tempfile::tempdir().expect("temp dir");
188 let first = lock_data_dir(dir.path()).expect("first lock");
189 assert_eq!(
190 lock_data_dir(dir.path()).err().as_deref(),
191 Some(BUSY_MESSAGE)
192 );
193 drop(first);
194 lock_data_dir(dir.path()).expect("lock after release");
195 }
196}