forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

cli.rs288 lines, 10.7 KiBHistoryRawDownload
1//! The command line of `in`. `in [--config <path>] [serve]` runs the server, and a bare `in` does the same.
2//! The other commands operate on a stopped instance: each takes the data-directory lock, so a server that is
3//! running makes them refuse with a message instead of racing it.
4//!
5//! Exit status: 0 for success, 1 for a failure or a check that found problems, 2 for a usage error (clap
6//! reports those itself).
7
8use std::path::{Path, PathBuf};
9use std::process::ExitCode;
10use std::time::SystemTime;
11
12use clap::{Parser, Subcommand};
13use in_core::backup;
14use in_core::config::{Backend, Config};
15use in_core::error::Error;
16use in_core::export::export_member;
17use in_core::fsck;
18use in_core::store::members::MemberFields;
19use in_core::time::now_stamp;
20
21use crate::boot;
22
23/// The parsed command line.
24#[derive(Debug, Parser)]
25#[command(name = "in", about = "The family's file drive", version)]
26pub struct Cli {
27 /// Configuration file. Without it, `IN_CONFIG` is used, then `config/in.toml`.
28 #[arg(long, global = true, value_name = "PATH")]
29 pub config: Option<PathBuf>,
30 /// The command. A bare `in` runs the server.
31 #[command(subcommand)]
32 pub command: Option<Command>,
33}
34
35/// The commands.
36#[derive(Debug, Subcommand)]
37pub enum Command {
38 /// Run the server. This is the default.
39 Serve,
40 /// Copy one person's live files into a folder tree that uses their folder and file names.
41 Export {
42 /// The person: their subject id, or their email address.
43 #[arg(long, value_name = "SUB|EMAIL")]
44 member: String,
45 /// The directory to write into. It is created when missing.
46 #[arg(long, value_name = "DIR")]
47 out: PathBuf,
48 },
49 /// Check the database and the blob tree against each other. Changes nothing unless `--quarantine` is given.
50 Fsck {
51 /// Also hash every blob and compare it with its row. Reads every byte, so it is slow.
52 #[arg(long)]
53 hash: bool,
54 /// Move orphan blobs that are over an hour old into `quarantine/` under the data directory. Local
55 /// storage only. Nothing is deleted.
56 #[arg(long)]
57 quarantine: bool,
58 },
59 /// Replace the database with the one in a backup set. The server must be stopped.
60 Restore {
61 /// The backup set directory (the one holding `in.db`, `manifest.json` and `manifest.mac`).
62 #[arg(long, value_name = "SET")]
63 from: PathBuf,
64 },
65 /// Quota maintenance.
66 Quota {
67 /// What to do.
68 #[command(subcommand)]
69 action: QuotaCommand,
70 },
71}
72
73/// The quota subcommands.
74#[derive(Debug, Subcommand)]
75pub enum QuotaCommand {
76 /// Recompute every person's used bytes from their files, and print the ones that were wrong.
77 Recompute,
78}
79
80/// Runs the command and maps the outcome to an exit status.
81pub async fn run(config: &Path, command: Command) -> ExitCode {
82 let outcome = match command {
83 Command::Serve => return serve(config).await,
84 Command::Export { member, out } => export(config, &member, &out).await,
85 Command::Fsck { hash, quarantine } => fsck_cmd(config, hash, quarantine).await,
86 Command::Restore { from } => restore(config, &from).await,
87 Command::Quota {
88 action: QuotaCommand::Recompute,
89 } => recompute(config).await,
90 };
91 match outcome {
92 Ok(true) => ExitCode::SUCCESS,
93 Ok(false) => ExitCode::FAILURE,
94 // A conflict here is the lock: say so in plain words, without the "conflict:" prefix.
95 Err(Error::Conflict(message)) => {
96 eprintln!("in: {message}");
97 ExitCode::FAILURE
98 }
99 Err(error) => {
100 eprintln!("in: {error}");
101 ExitCode::FAILURE
102 }
103 }
104}
105
106/// Runs the server and maps its outcome.
107async fn serve(config: &Path) -> ExitCode {
108 match boot::serve(config).await {
109 Ok(()) => ExitCode::SUCCESS,
110 Err(error) => {
111 tracing::error!(error = %error, "in stopped with an error");
112 ExitCode::FAILURE
113 }
114 }
115}
116
117/// Finds the person named by a subject id or an email address.
118async fn find_member(store: &in_core::store::Store, who: &str) -> Result<MemberFields, Error> {
119 let member = if who.contains('@') {
120 store.member_by_email(who).await?
121 } else {
122 store.member(who).await?
123 };
124 let member = member.ok_or_else(|| Error::Invalid(format!("no person named {who}")))?;
125 Ok(MemberFields {
126 sub: member.sub,
127 email: member.email,
128 name: member.name,
129 is_admin: member.is_admin,
130 locale: member.locale,
131 zoneinfo: member.zoneinfo,
132 picture_version: member.picture_version,
133 im_updated_at: member.im_updated_at,
134 })
135}
136
137/// `in export`. True when every file was written and verified.
138async fn export(config: &Path, who: &str, out: &Path) -> Result<bool, Error> {
139 let offline = boot::open_offline(config).await?;
140 let person = find_member(&offline.store, who).await?;
141 let report = export_member(&offline.store, offline.blobs.as_ref(), &person.sub, out).await?;
142 println!(
143 "exported {} files ({} bytes) and {} folders to {}",
144 report.files,
145 report.bytes,
146 report.folders,
147 out.display()
148 );
149 for id in &report.failed {
150 println!("failed: file {id} did not verify and was not written");
151 }
152 Ok(report.failed.is_empty())
153}
154
155/// `in fsck`. True when the check found nothing wrong. Orphans are reported but do not fail the check.
156async fn fsck_cmd(config_path: &Path, hash: bool, quarantine: bool) -> Result<bool, Error> {
157 let config = Config::load(config_path)?;
158 if quarantine && !matches!(config.storage.backend, Backend::Local) {
159 return Err(Error::Config(
160 "fsck --quarantine moves files on local disk, so it works only with the local blob backend".into(),
161 ));
162 }
163 let offline = boot::open_offline(config_path).await?;
164 let report = fsck::check(&offline.store, offline.blobs.as_ref(), hash).await?;
165 println!("database: {}", report.integrity.replace('\n', "; "));
166 println!("rows checked: {}", report.rows_checked);
167 println!("missing blobs: {}", report.missing_count);
168 for key in &report.missing {
169 println!(" missing {key}");
170 }
171 println!("size mismatches: {}", report.size_mismatch.len());
172 for key in &report.size_mismatch {
173 println!(" size {key}");
174 }
175 if hash {
176 println!("hash mismatches: {}", report.hash_mismatch.len());
177 for key in &report.hash_mismatch {
178 println!(" hash {key}");
179 }
180 }
181 println!("orphan blobs (no row names them): {}", report.orphan_count);
182 for key in &report.orphans {
183 println!(" orphan {key}");
184 }
185 if quarantine {
186 quarantine_orphans(&config, &offline).await?;
187 }
188 Ok(report.is_clean())
189}
190
191/// Moves the orphan blobs that are at least an hour old into the quarantine directory, and prints each one.
192async fn quarantine_orphans(config: &Config, offline: &boot::Offline) -> Result<(), Error> {
193 let data_dir = config.data_dir.canonicalize()?;
194 let found = fsck::orphans(&offline.store, offline.blobs.as_ref()).await?;
195 let moved = fsck::quarantine(
196 &data_dir.join(boot::BLOB_DIR),
197 &data_dir.join(fsck::QUARANTINE_DIR),
198 &found,
199 SystemTime::now(),
200 )?;
201 println!(
202 "quarantined {} orphan blobs to {}; {} younger than an hour were left in place",
203 moved.len(),
204 data_dir.join(fsck::QUARANTINE_DIR).display(),
205 found.len() - moved.len()
206 );
207 for key in &moved {
208 println!(" moved {key}");
209 }
210 Ok(())
211}
212
213/// `in restore`. Opens nothing of the database itself: the manifest's MAC is checked first (with the instance
214/// key, which must already exist), then the snapshot is verified, and only then is the file replaced. True
215/// when the restore completed.
216async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> {
217 let config = Config::load(config_path)?;
218 let _lock = boot::lock_data_dir(&config.data_dir)?;
219 let data_dir = config.data_dir.canonicalize()?;
220 // Read, never create: a missing key would make every set fail its MAC, and creating one here would hide that.
221 let key = in_core::secret::read_key(&data_dir.join(boot::KEY_FILE))?;
222 let stamp = now_stamp().replace([':', '.'], "-");
223 // The blob tree is opened only after the set has passed its checks, so a refusal creates nothing in it.
224 let outcome = match backup::restore(
225 &data_dir,
226 &config.database,
227 from,
228 || boot::open_blobs(&config, &data_dir),
229 &key,
230 &stamp,
231 )
232 .await
233 {
234 Ok(outcome) => outcome,
235 Err(Error::Invalid(code)) => match refusal_words(&code) {
236 Some(words) => {
237 eprintln!("in: {words}");
238 return Ok(false);
239 }
240 None => return Err(Error::Invalid(code)),
241 },
242 Err(error) => return Err(error),
243 };
244 println!(
245 "restored from {}: {} blobs listed, {} not in the blob tree",
246 from.display(),
247 outcome.blobs_listed,
248 outcome.blobs_missing
249 );
250 if let Some(previous) = &outcome.previous {
251 println!("the replaced database is kept at {}", previous.display());
252 }
253 Ok(true)
254}
255
256/// The plain words for a refused restore. The codes are what `in-core` returns and its tests match on them.
257fn refusal_words(code: &str) -> Option<&'static str> {
258 Some(match code {
259 "backup_hash" => {
260 "the backup's database does not match its manifest hash: the set is damaged"
261 }
262 "backup_mac_bad" => {
263 "the backup manifest's MAC does not verify: the set was changed, or this is not the instance key it was made with"
264 }
265 "backup_mac_missing" => "the backup set has no manifest MAC: the set is incomplete",
266 "backup_manifest_missing" => "the backup set has no manifest: the set is incomplete",
267 "backup_manifest_bad" => {
268 "the backup manifest is unreadable or from another format: the set cannot be restored by this build"
269 }
270 "backup_snapshot_missing" => "the backup set has no database file: the set is incomplete",
271 "backup_integrity" => "the backup's database fails its integrity check: the set is damaged",
272 _ => return None,
273 })
274}
275
276/// `in quota recompute`. True when it ran; drift that it corrected is printed, not failed.
277async fn recompute(config: &Path) -> Result<bool, Error> {
278 let offline = boot::open_offline(config).await?;
279 let drift = offline.store.reconcile_quota().await?;
280 println!("corrected {} people", drift.len());
281 for item in &drift {
282 println!(
283 " {}: stored {} bytes, now {} bytes",
284 item.sub, item.stored, item.actual
285 );
286 }
287 Ok(true)
288}