//! The operator command line: the words `iz` takes after its options, the lock that keeps two processes off //! one data directory, and the helpers the commands share. //! //! Commands: `iz [--config ] [serve]` runs the server (a bare `iz` does the same), `export --out ` //! writes the board to a new directory, `restore --from ` replaces the database and attachments //! with a verified backup set, and `fsck` checks the database and attachments without changing them. The //! configuration file is the `--config` path, then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is //! success, 1 a failure, 2 a usage error. //! //! The lock: every command that touches the data directory takes an exclusive lock on `iz.lock` inside it, //! held for the life of the process. A second process that finds the lock taken stops at once. What it is //! not: the lock does not protect the files from other users; the data directory is mode 0700 for that. pub mod export; pub mod fsck; pub mod restore; use std::fs::{File, OpenOptions, TryLockError}; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use std::process::ExitCode; use clap::{Parser, Subcommand}; use iz_core::config::Config; use iz_core::secret; use crate::boot::KEY_FILE; /// The file inside the data directory that carries the process lock. pub const LOCK_FILE: &str = "iz.lock"; /// The line printed when another process holds the lock. Operators search for it, so it is fixed. pub const BUSY_MESSAGE: &str = "iz is already running on this data directory; stop it (systemctl stop iz) before running this command"; /// The configuration file when neither `--config` nor `IZ_CONFIG` names one. pub const DEFAULT_CONFIG: &str = "config/iz.toml"; /// The environment variable that names the configuration file. pub const CONFIG_ENV: &str = "IZ_CONFIG"; /// The parsed command line. `--config` is global, so it works before or after the command word. #[derive(Debug, Parser)] #[command( name = "iz", about = "The iz task board: the server and its operator commands" )] pub struct Cli { /// The configuration file. Without it, `IZ_CONFIG`, then `config/iz.toml`. #[arg(long, global = true, value_name = "PATH")] pub config: Option, /// What to do. Without a command the server runs. #[command(subcommand)] pub command: Option, } /// The commands. `Serve` is the default. #[derive(Debug, Subcommand)] pub enum Command { /// Runs the server until SIGTERM or Ctrl-C. Serve, /// Writes the board, its attachments and a manifest into a new directory. Export { /// The directory to create. It must not exist or must be empty. #[arg(long, value_name = "DIR")] out: PathBuf, }, /// Replaces the database and attachments with a verified backup set. The previous files are kept. Restore { /// The backup set directory: `manifest.json` and the files it lists. #[arg(long, value_name = "DIR")] from: PathBuf, }, /// Checks the database and the attachments without changing anything. `--remote` also downloads the /// attachments held at the Files service and checks them, which needs the Files service configured. Fsck { /// Download and check the attachments held at the Files service. #[arg(long)] remote: bool, }, } /// The configuration path: the flag, else `IZ_CONFIG`, else the default. pub fn config_path(flag: Option) -> PathBuf { flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)) } /// Takes the exclusive lock on `data_dir/iz.lock`. The returned file holds the lock until it is dropped, /// so bind it to a variable that lives as long as the work does. A busy lock gives [`BUSY_MESSAGE`]; any /// other failure names the lock file. pub fn lock_data_dir(data_dir: &Path) -> Result { let path = data_dir.join(LOCK_FILE); // Mode 0600: only this user reads the lock file. `truncate(false)` keeps whatever the file holds. let file = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .mode(0o600) .open(&path) .map_err(|error| format!("iz: cannot open the lock file {}: {error}", path.display()))?; match file.try_lock() { Ok(()) => Ok(file), Err(TryLockError::WouldBlock) => Err(BUSY_MESSAGE.to_owned()), Err(TryLockError::Error(error)) => { Err(format!("iz: cannot lock {}: {error}", path.display())) } } } /// Prints the failure of [`lock_data_dir`] and gives the exit status 1. pub fn take_lock(data_dir: &Path) -> Result { lock_data_dir(data_dir).map_err(|message| { eprintln!("{message}"); ExitCode::FAILURE }) } /// Prints `iz: ` to stderr and gives the exit status 1. pub fn fail(message: impl std::fmt::Display) -> ExitCode { eprintln!("iz: {message}"); ExitCode::FAILURE } /// The text of an iz-core error for the user. A refused set or an invalid value is shown as its text /// alone; everything else keeps its prefix. pub fn describe(error: &iz_core::Error) -> String { match error { iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => text.clone(), other => other.to_string(), } } /// The data directory as an absolute path. It must exist: the commands that call this never create it. pub fn existing_data_dir(config: &Config) -> Result { config.data_dir.canonicalize().map_err(|error| { format!( "the data directory {} cannot be used: {error}", config.data_dir.display() ) }) } /// The instance key read from the data directory. It must exist: the commands that call this check or write /// manifests under it, and never create a key on the way. pub fn instance_key(data_dir: &Path) -> Result<[u8; 32], String> { let path = data_dir.join(KEY_FILE); secret::read_key(&path).map_err(|error| { format!( "the instance key {} cannot be used: {}", path.display(), describe(&error) ) }) } /// The database path, checked to be a regular file that is not a link. Nothing is created. pub fn database_file(config: &Config) -> Result { let meta = std::fs::symlink_metadata(&config.database).map_err(|error| { format!( "the database {} cannot be read: {error}", config.database.display() ) })?; if !meta.file_type().is_file() { return Err(format!( "the database {} is not a regular file", config.database.display() )); } Ok(config.database.clone()) } /// A UTC stamp that is safe in a file name: `20261028T093015Z`. pub fn file_stamp() -> String { jiff::Timestamp::now() .strftime("%Y%m%dT%H%M%SZ") .to_string() } #[cfg(test)] mod tests { use super::*; #[test] fn a_held_lock_is_refused_and_released_on_drop() { let dir = tempfile::tempdir().expect("temp dir"); let first = lock_data_dir(dir.path()).expect("first lock"); assert_eq!( lock_data_dir(dir.path()).err().as_deref(), Some(BUSY_MESSAGE) ); drop(first); lock_data_dir(dir.path()).expect("lock after release"); } }