]>
Commit | Line | Data |
---|---|---|
43abba4b DM |
1 | use std::path::PathBuf; |
2 | use std::sync::Arc; | |
3 | use std::os::unix::io::RawFd; | |
4 | use std::path::Path; | |
5 | use std::ffi::OsStr; | |
45f9b32e | 6 | use std::collections::HashMap; |
2d7d6e61 | 7 | use std::hash::BuildHasher; |
43abba4b DM |
8 | |
9 | use anyhow::{bail, format_err, Error}; | |
10 | use serde_json::Value; | |
11 | use tokio::signal::unix::{signal, SignalKind}; | |
12 | use nix::unistd::{fork, ForkResult, pipe}; | |
13 | use futures::select; | |
14 | use futures::future::FutureExt; | |
45f9b32e | 15 | use futures::stream::{StreamExt, TryStreamExt}; |
43abba4b DM |
16 | |
17 | use proxmox::{sortable, identity}; | |
cc7995ac | 18 | use proxmox::api::{ApiHandler, ApiMethod, RpcEnvironment, schema::*, cli::*}; |
43abba4b DM |
19 | |
20 | ||
21 | use proxmox_backup::tools; | |
22 | use proxmox_backup::backup::{ | |
23 | load_and_decrypt_key, | |
24 | CryptConfig, | |
25 | IndexFile, | |
26 | BackupDir, | |
27 | BackupGroup, | |
28 | BufferedDynamicReader, | |
45f9b32e | 29 | AsyncIndexReader, |
43abba4b DM |
30 | }; |
31 | ||
32 | use proxmox_backup::client::*; | |
43abba4b DM |
33 | |
34 | use crate::{ | |
35 | REPO_URL_SCHEMA, | |
36 | extract_repository_from_value, | |
43abba4b | 37 | complete_pxar_archive_name, |
2995aedf | 38 | complete_img_archive_name, |
43abba4b DM |
39 | complete_group_or_snapshot, |
40 | complete_repository, | |
41 | record_repository, | |
42 | connect, | |
43 | api_datastore_latest_snapshot, | |
44 | BufferedDynamicReadAt, | |
45 | }; | |
46 | ||
47 | #[sortable] | |
48 | const API_METHOD_MOUNT: ApiMethod = ApiMethod::new( | |
49 | &ApiHandler::Sync(&mount), | |
50 | &ObjectSchema::new( | |
51 | "Mount pxar archive.", | |
52 | &sorted!([ | |
53 | ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()), | |
54 | ("archive-name", false, &StringSchema::new("Backup archive name.").schema()), | |
55 | ("target", false, &StringSchema::new("Target directory path.").schema()), | |
56 | ("repository", true, &REPO_URL_SCHEMA), | |
57 | ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()), | |
45f9b32e SR |
58 | ("verbose", true, &BooleanSchema::new("Verbose output and stay in foreground.").default(false).schema()), |
59 | ]), | |
60 | ) | |
61 | ); | |
62 | ||
63 | #[sortable] | |
64 | const API_METHOD_MAP: ApiMethod = ApiMethod::new( | |
65 | &ApiHandler::Sync(&mount), | |
66 | &ObjectSchema::new( | |
67 | "Map a drive image from a VM backup to a local loopback device. Use 'unmap' to undo. | |
68 | WARNING: Only do this with *trusted* backups!", | |
69 | &sorted!([ | |
70 | ("snapshot", false, &StringSchema::new("Group/Snapshot path.").schema()), | |
71 | ("archive-name", false, &StringSchema::new("Backup archive name.").schema()), | |
72 | ("repository", true, &REPO_URL_SCHEMA), | |
73 | ("keyfile", true, &StringSchema::new("Path to encryption key.").schema()), | |
74 | ("verbose", true, &BooleanSchema::new("Verbose output and stay in foreground.").default(false).schema()), | |
75 | ]), | |
76 | ) | |
77 | ); | |
78 | ||
79 | #[sortable] | |
80 | const API_METHOD_UNMAP: ApiMethod = ApiMethod::new( | |
81 | &ApiHandler::Sync(&unmap), | |
82 | &ObjectSchema::new( | |
83 | "Unmap a loop device mapped with 'map' and release all resources.", | |
84 | &sorted!([ | |
2d7d6e61 | 85 | ("name", true, &StringSchema::new( |
2deee0e0 SR |
86 | concat!("Archive name, path to loopdev (/dev/loopX) or loop device number. ", |
87 | "Omit to list all current mappings and force cleaning up leftover instances.") | |
2d7d6e61 | 88 | ).schema()), |
43abba4b DM |
89 | ]), |
90 | ) | |
91 | ); | |
92 | ||
93 | pub fn mount_cmd_def() -> CliCommand { | |
94 | ||
95 | CliCommand::new(&API_METHOD_MOUNT) | |
96 | .arg_param(&["snapshot", "archive-name", "target"]) | |
97 | .completion_cb("repository", complete_repository) | |
98 | .completion_cb("snapshot", complete_group_or_snapshot) | |
99 | .completion_cb("archive-name", complete_pxar_archive_name) | |
100 | .completion_cb("target", tools::complete_file_name) | |
101 | } | |
102 | ||
45f9b32e SR |
103 | pub fn map_cmd_def() -> CliCommand { |
104 | ||
105 | CliCommand::new(&API_METHOD_MAP) | |
106 | .arg_param(&["snapshot", "archive-name"]) | |
107 | .completion_cb("repository", complete_repository) | |
108 | .completion_cb("snapshot", complete_group_or_snapshot) | |
2995aedf | 109 | .completion_cb("archive-name", complete_img_archive_name) |
45f9b32e SR |
110 | } |
111 | ||
112 | pub fn unmap_cmd_def() -> CliCommand { | |
113 | ||
114 | CliCommand::new(&API_METHOD_UNMAP) | |
2d7d6e61 SR |
115 | .arg_param(&["name"]) |
116 | .completion_cb("name", complete_mapping_names) | |
117 | } | |
118 | ||
119 | fn complete_mapping_names<S: BuildHasher>(_arg: &str, _param: &HashMap<String, String, S>) | |
120 | -> Vec<String> | |
121 | { | |
122 | match tools::fuse_loop::find_all_mappings() { | |
123 | Ok(mappings) => mappings | |
124 | .filter_map(|(name, _)| { | |
125 | tools::systemd::unescape_unit(&name).ok() | |
126 | }).collect(), | |
127 | Err(_) => Vec::new() | |
128 | } | |
45f9b32e SR |
129 | } |
130 | ||
43abba4b DM |
131 | fn mount( |
132 | param: Value, | |
133 | _info: &ApiMethod, | |
134 | _rpcenv: &mut dyn RpcEnvironment, | |
135 | ) -> Result<Value, Error> { | |
136 | ||
137 | let verbose = param["verbose"].as_bool().unwrap_or(false); | |
138 | if verbose { | |
139 | // This will stay in foreground with debug output enabled as None is | |
140 | // passed for the RawFd. | |
141 | return proxmox_backup::tools::runtime::main(mount_do(param, None)); | |
142 | } | |
143 | ||
144 | // Process should be deamonized. | |
145 | // Make sure to fork before the async runtime is instantiated to avoid troubles. | |
146 | let pipe = pipe()?; | |
147 | match fork() { | |
148 | Ok(ForkResult::Parent { .. }) => { | |
149 | nix::unistd::close(pipe.1).unwrap(); | |
150 | // Blocks the parent process until we are ready to go in the child | |
151 | let _res = nix::unistd::read(pipe.0, &mut [0]).unwrap(); | |
152 | Ok(Value::Null) | |
153 | } | |
154 | Ok(ForkResult::Child) => { | |
155 | nix::unistd::close(pipe.0).unwrap(); | |
156 | nix::unistd::setsid().unwrap(); | |
157 | proxmox_backup::tools::runtime::main(mount_do(param, Some(pipe.1))) | |
158 | } | |
159 | Err(_) => bail!("failed to daemonize process"), | |
160 | } | |
161 | } | |
162 | ||
163 | async fn mount_do(param: Value, pipe: Option<RawFd>) -> Result<Value, Error> { | |
164 | let repo = extract_repository_from_value(¶m)?; | |
165 | let archive_name = tools::required_string_param(¶m, "archive-name")?; | |
ba20987a | 166 | let client = connect(repo.host(), repo.port(), repo.user())?; |
43abba4b | 167 | |
45f9b32e SR |
168 | let target = param["target"].as_str(); |
169 | ||
43abba4b DM |
170 | record_repository(&repo); |
171 | ||
172 | let path = tools::required_string_param(¶m, "snapshot")?; | |
173 | let (backup_type, backup_id, backup_time) = if path.matches('/').count() == 1 { | |
174 | let group: BackupGroup = path.parse()?; | |
175 | api_datastore_latest_snapshot(&client, repo.store(), group).await? | |
176 | } else { | |
177 | let snapshot: BackupDir = path.parse()?; | |
178 | (snapshot.group().backup_type().to_owned(), snapshot.group().backup_id().to_owned(), snapshot.backup_time()) | |
179 | }; | |
180 | ||
181 | let keyfile = param["keyfile"].as_str().map(PathBuf::from); | |
182 | let crypt_config = match keyfile { | |
183 | None => None, | |
184 | Some(path) => { | |
9696f519 | 185 | let (key, _) = load_and_decrypt_key(&path, &crate::key::get_encryption_key_password)?; |
43abba4b DM |
186 | Some(Arc::new(CryptConfig::new(key)?)) |
187 | } | |
188 | }; | |
189 | ||
190 | let server_archive_name = if archive_name.ends_with(".pxar") { | |
45f9b32e SR |
191 | if let None = target { |
192 | bail!("use the 'mount' command to mount pxar archives"); | |
193 | } | |
43abba4b | 194 | format!("{}.didx", archive_name) |
45f9b32e SR |
195 | } else if archive_name.ends_with(".img") { |
196 | if let Some(_) = target { | |
197 | bail!("use the 'map' command to map drive images"); | |
198 | } | |
199 | format!("{}.fidx", archive_name) | |
43abba4b | 200 | } else { |
45f9b32e | 201 | bail!("Can only mount/map pxar archives and drive images."); |
43abba4b DM |
202 | }; |
203 | ||
204 | let client = BackupReader::start( | |
205 | client, | |
206 | crypt_config.clone(), | |
207 | repo.store(), | |
208 | &backup_type, | |
209 | &backup_id, | |
210 | backup_time, | |
211 | true, | |
212 | ).await?; | |
213 | ||
2107a5ae | 214 | let (manifest, _) = client.download_manifest().await?; |
43abba4b | 215 | |
871181d9 | 216 | let file_info = manifest.lookup_file_info(&server_archive_name)?; |
14f6c9cb | 217 | |
45f9b32e | 218 | let daemonize = || -> Result<(), Error> { |
43abba4b DM |
219 | if let Some(pipe) = pipe { |
220 | nix::unistd::chdir(Path::new("/")).unwrap(); | |
221 | // Finish creation of daemon by redirecting filedescriptors. | |
222 | let nullfd = nix::fcntl::open( | |
223 | "/dev/null", | |
224 | nix::fcntl::OFlag::O_RDWR, | |
225 | nix::sys::stat::Mode::empty(), | |
226 | ).unwrap(); | |
227 | nix::unistd::dup2(nullfd, 0).unwrap(); | |
228 | nix::unistd::dup2(nullfd, 1).unwrap(); | |
229 | nix::unistd::dup2(nullfd, 2).unwrap(); | |
230 | if nullfd > 2 { | |
231 | nix::unistd::close(nullfd).unwrap(); | |
232 | } | |
233 | // Signal the parent process that we are done with the setup and it can | |
234 | // terminate. | |
235 | nix::unistd::write(pipe, &[0u8])?; | |
236 | nix::unistd::close(pipe).unwrap(); | |
237 | } | |
238 | ||
45f9b32e SR |
239 | Ok(()) |
240 | }; | |
241 | ||
242 | let options = OsStr::new("ro,default_permissions"); | |
243 | ||
244 | // handle SIGINT and SIGTERM | |
245 | let mut interrupt_int = signal(SignalKind::interrupt())?; | |
246 | let mut interrupt_term = signal(SignalKind::terminate())?; | |
247 | let mut interrupt = futures::future::select(interrupt_int.next(), interrupt_term.next()); | |
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(); | |
255 | let reader: proxmox_backup::pxar::fuse::Reader = | |
256 | Arc::new(BufferedDynamicReadAt::new(reader)); | |
257 | let decoder = proxmox_backup::pxar::fuse::Accessor::new(reader, archive_size).await?; | |
258 | ||
259 | let session = proxmox_backup::pxar::fuse::Session::mount( | |
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()); | |
279 | let reader = AsyncIndexReader::new(index, chunk_reader); | |
280 | ||
2d7d6e61 SR |
281 | let name = &format!("{}:{}/{}", repo.to_string(), path, archive_name); |
282 | let name_escaped = tools::systemd::escape_unit(name, false); | |
283 | ||
284 | let mut session = tools::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! { | |
294 | res = session_fut => { | |
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 => { | |
2deee0e0 | 341 | tools::fuse_loop::cleanup_unused_run_files(None); |
2d7d6e61 SR |
342 | let mut any = false; |
343 | for (backing, loopdev) in tools::fuse_loop::find_all_mappings()? { | |
344 | let name = tools::systemd::unescape_unit(&backing)?; | |
345 | println!("{}:\t{}", loopdev.unwrap_or("(unmapped)".to_owned()), name); | |
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 SR |
360 | if name.starts_with("/dev/loop") { |
361 | tools::fuse_loop::unmap_loopdev(name)?; | |
362 | } else { | |
363 | let name = tools::systemd::escape_unit(&name, false); | |
364 | tools::fuse_loop::unmap_name(name)?; | |
365 | } | |
45f9b32e SR |
366 | |
367 | Ok(Value::Null) | |
368 | } |