]>
Commit | Line | Data |
---|---|---|
45f9b32e | 1 | use std::collections::HashMap; |
35fe981c | 2 | use std::ffi::OsStr; |
2d7d6e61 | 3 | use std::hash::BuildHasher; |
35fe981c WB |
4 | use std::os::unix::io::AsRawFd; |
5 | use std::path::{Path, PathBuf}; | |
6 | use std::sync::Arc; | |
43abba4b DM |
7 | |
8 | use anyhow::{bail, format_err, Error}; | |
43abba4b | 9 | use futures::future::FutureExt; |
35fe981c | 10 | use futures::select; |
45f9b32e | 11 | use futures::stream::{StreamExt, TryStreamExt}; |
35fe981c WB |
12 | use nix::unistd::{fork, ForkResult}; |
13 | use serde_json::Value; | |
14 | use tokio::signal::unix::{signal, SignalKind}; | |
43abba4b DM |
15 | |
16 | use proxmox::{sortable, identity}; | |
cc7995ac | 17 | use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment, schema::*, cli::*}; |
35fe981c | 18 | use proxmox::tools::fd::Fd; |
43abba4b | 19 | |
bbdda58b DM |
20 | use pbs_tools::crypt_config::CryptConfig; |
21 | use pbs_config::key_config::load_and_decrypt_key; | |
22 | use pbs_datastore::{BackupDir, BackupGroup, }; | |
eb5e0ae6 WB |
23 | use pbs_datastore::index::IndexFile; |
24 | use pbs_datastore::dynamic_index::BufferedDynamicReader; | |
ef4df211 | 25 | use pbs_datastore::cached_chunk_reader::CachedChunkReader; |
2b7f8dd5 WB |
26 | use pbs_client::tools::key_source::get_encryption_key_password; |
27 | use pbs_client::{BackupReader, RemoteChunkReader}; | |
3c8c2827 | 28 | use pbs_tools::json::required_string_param; |
2b7f8dd5 | 29 | |
43abba4b DM |
30 | use crate::{ |
31 | REPO_URL_SCHEMA, | |
32 | extract_repository_from_value, | |
43abba4b | 33 | complete_pxar_archive_name, |
2995aedf | 34 | complete_img_archive_name, |
43abba4b DM |
35 | complete_group_or_snapshot, |
36 | complete_repository, | |
37 | record_repository, | |
38 | connect, | |
39 | api_datastore_latest_snapshot, | |
40 | BufferedDynamicReadAt, | |
41 | }; | |
42 | ||
43 | #[sortable] | |
44 | const API_METHOD_MOUNT: ApiMethod = ApiMethod::new( | |
45 | &ApiHandler::Sync(&mount), | |
46 | &ObjectSchema::new( | |
47 | "Mount pxar archive.", | |
48 | &sorted!([ | |
49 | ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()), | |
50 | ("archive-name", false, &StringSchema::new("Backup archive name.").schema()), | |
51 | ("target", false, &StringSchema::new("Target directory path.").schema()), | |
52 | ("repository", true, &REPO_URL_SCHEMA), | |
53 | ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()), | |
45f9b32e SR |
54 | ("verbose", true, &BooleanSchema::new("Verbose output and stay in foreground.").default(false).schema()), |
55 | ]), | |
56 | ) | |
57 | ); | |
58 | ||
59 | #[sortable] | |
60 | const API_METHOD_MAP: ApiMethod = ApiMethod::new( | |
61 | &ApiHandler::Sync(&mount), | |
62 | &ObjectSchema::new( | |
63 | "Map a drive image from a VM backup to a local loopback device. Use 'unmap' to undo. | |
64 | WARNING: Only do this with *trusted* backups!", | |
65 | &sorted!([ | |
66 | ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()), | |
67 | ("archive-name", false, &StringSchema::new("Backup archive name.").schema()), | |
68 | ("repository", true, &REPO_URL_SCHEMA), | |
69 | ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()), | |
70 | ("verbose", true, &BooleanSchema::new("Verbose output and stay in foreground.").default(false).schema()), | |
71 | ]), | |
72 | ) | |
73 | ); | |
74 | ||
75 | #[sortable] | |
76 | const API_METHOD_UNMAP: ApiMethod = ApiMethod::new( | |
77 | &ApiHandler::Sync(&unmap), | |
78 | &ObjectSchema::new( | |
79 | "Unmap a loop device mapped with 'map' and release all resources.", | |
80 | &sorted!([ | |
2d7d6e61 | 81 | ("name", true, &StringSchema::new( |
2deee0e0 SR |
82 | concat!("Archive name, path to loopdev (/dev/loopX) or loop device number. ", |
83 | "Omit to list all current mappings and force cleaning up leftover instances.") | |
2d7d6e61 | 84 | ).schema()), |
43abba4b DM |
85 | ]), |
86 | ) | |
87 | ); | |
88 | ||
89 | pub fn mount_cmd_def() -> CliCommand { | |
90 | ||
91 | CliCommand::new(&API_METHOD_MOUNT) | |
92 | .arg_param(&["snapshot", "archive-name", "target"]) | |
93 | .completion_cb("repository", complete_repository) | |
94 | .completion_cb("snapshot", complete_group_or_snapshot) | |
95 | .completion_cb("archive-name", complete_pxar_archive_name) | |
2b7f8dd5 | 96 | .completion_cb("target", pbs_tools::fs::complete_file_name) |
43abba4b DM |
97 | } |
98 | ||
45f9b32e SR |
99 | pub fn map_cmd_def() -> CliCommand { |
100 | ||
101 | CliCommand::new(&API_METHOD_MAP) | |
102 | .arg_param(&["snapshot", "archive-name"]) | |
103 | .completion_cb("repository", complete_repository) | |
104 | .completion_cb("snapshot", complete_group_or_snapshot) | |
2995aedf | 105 | .completion_cb("archive-name", complete_img_archive_name) |
45f9b32e SR |
106 | } |
107 | ||
108 | pub fn unmap_cmd_def() -> CliCommand { | |
109 | ||
110 | CliCommand::new(&API_METHOD_UNMAP) | |
2d7d6e61 SR |
111 | .arg_param(&["name"]) |
112 | .completion_cb("name", complete_mapping_names) | |
113 | } | |
114 | ||
115 | fn complete_mapping_names<S: BuildHasher>(_arg: &str, _param: &HashMap<String, String, S>) | |
116 | -> Vec<String> | |
117 | { | |
eb5e0ae6 | 118 | match pbs_fuse_loop::find_all_mappings() { |
2d7d6e61 SR |
119 | Ok(mappings) => mappings |
120 | .filter_map(|(name, _)| { | |
eb5e0ae6 | 121 | pbs_systemd::unescape_unit(&name).ok() |
2d7d6e61 SR |
122 | }).collect(), |
123 | Err(_) => Vec::new() | |
124 | } | |
45f9b32e SR |
125 | } |
126 | ||
43abba4b DM |
127 | fn mount( |
128 | param: Value, | |
129 | _info: &ApiMethod, | |
130 | _rpcenv: &mut dyn RpcEnvironment, | |
131 | ) -> Result<Value, Error> { | |
132 | ||
133 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
134 | if verbose { | |
135 | // This will stay in foreground with debug output enabled as None is | |
136 | // passed for the RawFd. | |
d420962f | 137 | return pbs_runtime::main(mount_do(param, None)); |
43abba4b DM |
138 | } |
139 | ||
d1d74c43 | 140 | // Process should be daemonized. |
43abba4b | 141 | // Make sure to fork before the async runtime is instantiated to avoid troubles. |
eb5e0ae6 | 142 | let (pr, pw) = pbs_tools::io::pipe()?; |
0c4c6a7b | 143 | match unsafe { fork() } { |
43abba4b | 144 | Ok(ForkResult::Parent { .. }) => { |
35fe981c | 145 | drop(pw); |
43abba4b | 146 | // Blocks the parent process until we are ready to go in the child |
35fe981c | 147 | let _res = nix::unistd::read(pr.as_raw_fd(), &mut [0]).unwrap(); |
43abba4b DM |
148 | Ok(Value::Null) |
149 | } | |
150 | Ok(ForkResult::Child) => { | |
35fe981c | 151 | drop(pr); |
43abba4b | 152 | nix::unistd::setsid().unwrap(); |
d420962f | 153 | pbs_runtime::main(mount_do(param, Some(pw))) |
43abba4b DM |
154 | } |
155 | Err(_) => bail!("failed to daemonize process"), | |
156 | } | |
157 | } | |
158 | ||
35fe981c | 159 | async fn mount_do(param: Value, pipe: Option<Fd>) -> Result<Value, Error> { |
43abba4b | 160 | let repo = extract_repository_from_value(¶m)?; |
3c8c2827 | 161 | let archive_name = required_string_param(¶m, "archive-name")?; |
f3fde36b | 162 | let client = connect(&repo)?; |
43abba4b | 163 | |
45f9b32e SR |
164 | let target = param["target"].as_str(); |
165 | ||
43abba4b DM |
166 | record_repository(&repo); |
167 | ||
3c8c2827 | 168 | let path = required_string_param(¶m, "snapshot")?; |
43abba4b DM |
169 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { |
170 | let group: BackupGroup = path.parse()?; | |
171 | api_datastore_latest_snapshot(&client, repo.store(), group).await? | |
172 | } else { | |
173 | let snapshot: BackupDir = path.parse()?; | |
174 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
175 | }; | |
176 | ||
177 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); | |
178 | let crypt_config = match keyfile { | |
179 | None => None, | |
180 | Some(path) => { | |
6f2626ae | 181 | println!("Encryption key file: '{:?}'", path); |
ff8945fd | 182 | let (key, _, fingerprint) = load_and_decrypt_key(&path, &get_encryption_key_password)?; |
6f2626ae | 183 | println!("Encryption key fingerprint: '{}'", fingerprint); |
43abba4b DM |
184 | Some(Arc::new(CryptConfig::new(key)?)) |
185 | } | |
186 | }; | |
187 | ||
188 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
3984a5fd | 189 | if target.is_none() { |
45f9b32e SR |
190 | bail!("use the 'mount' command to mount pxar archives"); |
191 | } | |
43abba4b | 192 | format!("{}.didx", archive_name) |
45f9b32e | 193 | } else if archive_name.ends_with(".img") { |
3984a5fd | 194 | if target.is_some() { |
45f9b32e SR |
195 | bail!("use the 'map' command to map drive images"); |
196 | } | |
197 | format!("{}.fidx", archive_name) | |
43abba4b | 198 | } else { |
45f9b32e | 199 | bail!("Can only mount/map pxar archives and drive images."); |
43abba4b DM |
200 | }; |
201 | ||
202 | let client = BackupReader::start( | |
203 | client, | |
204 | crypt_config.clone(), | |
205 | repo.store(), | |
206 | &backup_type, | |
207 | &backup_id, | |
208 | backup_time, | |
209 | true, | |
210 | ).await?; | |
211 | ||
2107a5ae | 212 | let (manifest, _) = client.download_manifest().await?; |
23f9503a | 213 | manifest.check_fingerprint(crypt_config.as_ref().map(Arc::as_ref))?; |
43abba4b | 214 | |
871181d9 | 215 | let file_info = manifest.lookup_file_info(&server_archive_name)?; |
14f6c9cb | 216 | |
45f9b32e | 217 | let daemonize = || -> Result<(), Error> { |
43abba4b DM |
218 | if let Some(pipe) = pipe { |
219 | nix::unistd::chdir(Path::new("/")).unwrap(); | |
220 | // Finish creation of daemon by redirecting filedescriptors. | |
221 | let nullfd = nix::fcntl::open( | |
222 | "/dev/null", | |
223 | nix::fcntl::OFlag::O_RDWR, | |
224 | nix::sys::stat::Mode::empty(), | |
225 | ).unwrap(); | |
226 | nix::unistd::dup2(nullfd, 0).unwrap(); | |
227 | nix::unistd::dup2(nullfd, 1).unwrap(); | |
228 | nix::unistd::dup2(nullfd, 2).unwrap(); | |
229 | if nullfd > 2 { | |
230 | nix::unistd::close(nullfd).unwrap(); | |
231 | } | |
232 | // Signal the parent process that we are done with the setup and it can | |
233 | // terminate. | |
35fe981c WB |
234 | nix::unistd::write(pipe.as_raw_fd(), &[0u8])?; |
235 | let _: Fd = pipe; | |
43abba4b DM |
236 | } |
237 | ||
45f9b32e SR |
238 | Ok(()) |
239 | }; | |
240 | ||
241 | let options = OsStr::new("ro,default_permissions"); | |
242 | ||
243 | // handle SIGINT and SIGTERM | |
244 | let mut interrupt_int = signal(SignalKind::interrupt())?; | |
245 | let mut interrupt_term = signal(SignalKind::terminate())?; | |
b5a202ac FG |
246 | |
247 | let mut interrupt = futures::future::select(interrupt_int.recv().boxed(), interrupt_term.recv().boxed()); | |
45f9b32e SR |
248 | |
249 | if server_archive_name.ends_with(".didx") { | |
250 | let index = client.download_dynamic_index(&manifest, &server_archive_name).await?; | |
251 | let most_used = index.find_most_used_chunks(8); | |
252 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), most_used); | |
253 | let reader = BufferedDynamicReader::new(index, chunk_reader); | |
254 | let archive_size = reader.archive_size(); | |
2b7f8dd5 | 255 | let reader: pbs_client::pxar::fuse::Reader = |
45f9b32e | 256 | Arc::new(BufferedDynamicReadAt::new(reader)); |
2b7f8dd5 | 257 | let decoder = pbs_client::pxar::fuse::Accessor::new(reader, archive_size).await?; |
45f9b32e | 258 | |
2b7f8dd5 | 259 | let session = pbs_client::pxar::fuse::Session::mount( |
45f9b32e SR |
260 | decoder, |
261 | &options, | |
262 | false, | |
263 | Path::new(target.unwrap()), | |
264 | ) | |
265 | .map_err(|err| format_err!("pxar mount failed: {}", err))?; | |
266 | ||
267 | daemonize()?; | |
1d0b662b | 268 | |
43abba4b DM |
269 | select! { |
270 | res = session.fuse() => res?, | |
1d0b662b | 271 | _ = interrupt => { |
43abba4b DM |
272 | // exit on interrupted |
273 | } | |
274 | } | |
45f9b32e SR |
275 | } else if server_archive_name.ends_with(".fidx") { |
276 | let index = client.download_fixed_index(&manifest, &server_archive_name).await?; | |
277 | let size = index.index_bytes(); | |
278 | let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), HashMap::new()); | |
1ef6e8b6 | 279 | let reader = CachedChunkReader::new(chunk_reader, index, 8).seekable(); |
45f9b32e | 280 | |
2d7d6e61 | 281 | let name = &format!("{}:{}/{}", repo.to_string(), path, archive_name); |
eb5e0ae6 | 282 | let name_escaped = pbs_systemd::escape_unit(name, false); |
2d7d6e61 | 283 | |
eb5e0ae6 | 284 | let mut session = pbs_fuse_loop::FuseLoopSession::map_loop(size, reader, &name_escaped, options).await?; |
45f9b32e SR |
285 | let loopdev = session.loopdev_path.clone(); |
286 | ||
287 | let (st_send, st_recv) = futures::channel::mpsc::channel(1); | |
288 | let (mut abort_send, abort_recv) = futures::channel::mpsc::channel(1); | |
289 | let mut st_recv = st_recv.fuse(); | |
290 | let mut session_fut = session.main(st_send, abort_recv).boxed().fuse(); | |
291 | ||
292 | // poll until loop file is mapped (or errors) | |
293 | select! { | |
0bfcea6a | 294 | _res = session_fut => { |
45f9b32e SR |
295 | bail!("FUSE session unexpectedly ended before loop file mapping"); |
296 | }, | |
297 | res = st_recv.try_next() => { | |
298 | if let Err(err) = res { | |
299 | // init went wrong, abort now | |
300 | abort_send.try_send(()).map_err(|err| | |
301 | format_err!("error while sending abort signal - {}", err))?; | |
302 | // ignore and keep original error cause | |
303 | let _ = session_fut.await; | |
304 | return Err(err); | |
305 | } | |
306 | } | |
307 | } | |
308 | ||
309 | // daemonize only now to be able to print mapped loopdev or startup errors | |
2d7d6e61 | 310 | println!("Image '{}' mapped on {}", name, loopdev); |
45f9b32e SR |
311 | daemonize()?; |
312 | ||
313 | // continue polling until complete or interrupted (which also happens on unmap) | |
314 | select! { | |
315 | res = session_fut => res?, | |
316 | _ = interrupt => { | |
317 | // exit on interrupted | |
318 | abort_send.try_send(()).map_err(|err| | |
319 | format_err!("error while sending abort signal - {}", err))?; | |
320 | session_fut.await?; | |
321 | } | |
322 | } | |
323 | ||
324 | println!("Image unmapped"); | |
43abba4b | 325 | } else { |
45f9b32e | 326 | bail!("unknown archive file extension (expected .pxar or .img)"); |
43abba4b DM |
327 | } |
328 | ||
329 | Ok(Value::Null) | |
330 | } | |
45f9b32e SR |
331 | |
332 | fn unmap( | |
333 | param: Value, | |
334 | _info: &ApiMethod, | |
335 | _rpcenv: &mut dyn RpcEnvironment, | |
336 | ) -> Result<Value, Error> { | |
337 | ||
2d7d6e61 SR |
338 | let mut name = match param["name"].as_str() { |
339 | Some(name) => name.to_owned(), | |
340 | None => { | |
eb5e0ae6 | 341 | pbs_fuse_loop::cleanup_unused_run_files(None); |
2d7d6e61 | 342 | let mut any = false; |
eb5e0ae6 WB |
343 | for (backing, loopdev) in pbs_fuse_loop::find_all_mappings()? { |
344 | let name = pbs_systemd::unescape_unit(&backing)?; | |
4d104cd4 | 345 | println!("{}:\t{}", loopdev.unwrap_or_else(|| "(unmapped)".to_string()), name); |
2d7d6e61 SR |
346 | any = true; |
347 | } | |
348 | if !any { | |
349 | println!("Nothing mapped."); | |
350 | } | |
351 | return Ok(Value::Null); | |
352 | }, | |
353 | }; | |
45f9b32e | 354 | |
2d7d6e61 SR |
355 | // allow loop device number alone |
356 | if let Ok(num) = name.parse::<u8>() { | |
357 | name = format!("/dev/loop{}", num); | |
45f9b32e SR |
358 | } |
359 | ||
2d7d6e61 | 360 | if name.starts_with("/dev/loop") { |
eb5e0ae6 | 361 | pbs_fuse_loop::unmap_loopdev(name)?; |
2d7d6e61 | 362 | } else { |
eb5e0ae6 WB |
363 | let name = pbs_systemd::escape_unit(&name, false); |
364 | pbs_fuse_loop::unmap_name(name)?; | |
2d7d6e61 | 365 | } |
45f9b32e SR |
366 | |
367 | Ok(Value::Null) | |
368 | } |