1 use std
::path
::PathBuf
;
3 use std
::os
::unix
::io
::RawFd
;
6 use std
::collections
::HashMap
;
7 use std
::hash
::BuildHasher
;
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}
;
14 use futures
::future
::FutureExt
;
15 use futures
::stream
::{StreamExt, TryStreamExt}
;
17 use proxmox
::{sortable, identity}
;
18 use proxmox
::api
::{ApiHandler, ApiMethod, RpcEnvironment, schema::*, cli::*}
;
21 use proxmox_backup
::tools
;
22 use proxmox_backup
::backup
::{
28 BufferedDynamicReader
,
32 use proxmox_backup
::client
::*;
36 extract_repository_from_value
,
37 complete_pxar_archive_name
,
38 complete_img_archive_name
,
39 complete_group_or_snapshot
,
43 api_datastore_latest_snapshot
,
44 BufferedDynamicReadAt
,
48 const API_METHOD_MOUNT
: ApiMethod
= ApiMethod
::new(
49 &ApiHandler
::Sync(&mount
),
51 "Mount pxar archive.",
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()),
58 ("verbose", true, &BooleanSchema
::new("Verbose output and stay in foreground.").default(false).schema()),
64 const API_METHOD_MAP
: ApiMethod
= ApiMethod
::new(
65 &ApiHandler
::Sync(&mount
),
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!",
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()),
80 const API_METHOD_UNMAP
: ApiMethod
= ApiMethod
::new(
81 &ApiHandler
::Sync(&unmap
),
83 "Unmap a loop device mapped with 'map' and release all resources.",
85 ("name", true, &StringSchema
::new(
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.")
93 pub fn mount_cmd_def() -> CliCommand
{
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
)
103 pub fn map_cmd_def() -> CliCommand
{
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
)
109 .completion_cb("archive-name", complete_img_archive_name
)
112 pub fn unmap_cmd_def() -> CliCommand
{
114 CliCommand
::new(&API_METHOD_UNMAP
)
115 .arg_param(&["name"])
116 .completion_cb("name", complete_mapping_names
)
119 fn complete_mapping_names
<S
: BuildHasher
>(_arg
: &str, _param
: &HashMap
<String
, String
, S
>)
122 match tools
::fuse_loop
::find_all_mappings() {
123 Ok(mappings
) => mappings
124 .filter_map(|(name
, _
)| {
125 tools
::systemd
::unescape_unit(&name
).ok()
134 _rpcenv
: &mut dyn RpcEnvironment
,
135 ) -> Result
<Value
, Error
> {
137 let verbose
= param
["verbose"].as_bool().unwrap_or(false);
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
));
144 // Process should be deamonized.
145 // Make sure to fork before the async runtime is instantiated to avoid troubles.
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();
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)))
159 Err(_
) => bail
!("failed to daemonize process"),
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")?
;
166 let client
= connect(repo
.host(), repo
.port(), repo
.user())?
;
168 let target
= param
["target"].as_str();
170 record_repository(&repo
);
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?
177 let snapshot
: BackupDir
= path
.parse()?
;
178 (snapshot
.group().backup_type().to_owned(), snapshot
.group().backup_id().to_owned(), snapshot
.backup_time())
181 let keyfile
= param
["keyfile"].as_str().map(PathBuf
::from
);
182 let crypt_config
= match keyfile
{
185 let (key
, _
) = load_and_decrypt_key(&path
, &crate::key
::get_encryption_key_password
)?
;
186 Some(Arc
::new(CryptConfig
::new(key
)?
))
190 let server_archive_name
= if archive_name
.ends_with(".pxar") {
191 if let None
= target
{
192 bail
!("use the 'mount' command to mount pxar archives");
194 format
!("{}.didx", archive_name
)
195 } else if archive_name
.ends_with(".img") {
196 if let Some(_
) = target
{
197 bail
!("use the 'map' command to map drive images");
199 format
!("{}.fidx", archive_name
)
201 bail
!("Can only mount/map pxar archives and drive images.");
204 let client
= BackupReader
::start(
206 crypt_config
.clone(),
214 let (manifest
, _
) = client
.download_manifest().await?
;
216 let file_info
= manifest
.lookup_file_info(&server_archive_name
)?
;
218 let daemonize
= || -> Result
<(), Error
> {
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(
224 nix
::fcntl
::OFlag
::O_RDWR
,
225 nix
::sys
::stat
::Mode
::empty(),
227 nix
::unistd
::dup2(nullfd
, 0).unwrap();
228 nix
::unistd
::dup2(nullfd
, 1).unwrap();
229 nix
::unistd
::dup2(nullfd
, 2).unwrap();
231 nix
::unistd
::close(nullfd
).unwrap();
233 // Signal the parent process that we are done with the setup and it can
235 nix
::unistd
::write(pipe
, &[0u8])?
;
236 nix
::unistd
::close(pipe
).unwrap();
242 let options
= OsStr
::new("ro,default_permissions");
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());
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?
;
259 let session
= proxmox_backup
::pxar
::fuse
::Session
::mount(
263 Path
::new(target
.unwrap()),
265 .map_err(|err
| format_err
!("pxar mount failed: {}", err
))?
;
270 res
= session
.fuse() => res?
,
272 // exit on interrupted
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
);
281 let name
= &format
!("{}:{}/{}", repo
.to_string(), path
, archive_name
);
282 let name_escaped
= tools
::systemd
::escape_unit(name
, false);
284 let mut session
= tools
::fuse_loop
::FuseLoopSession
::map_loop(size
, reader
, &name_escaped
, options
).await?
;
285 let loopdev
= session
.loopdev_path
.clone();
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();
292 // poll until loop file is mapped (or errors)
294 res
= session_fut
=> {
295 bail
!("FUSE session unexpectedly ended before loop file mapping");
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
;
309 // daemonize only now to be able to print mapped loopdev or startup errors
310 println
!("Image '{}' mapped on {}", name
, loopdev
);
313 // continue polling until complete or interrupted (which also happens on unmap)
315 res
= session_fut
=> res?
,
317 // exit on interrupted
318 abort_send
.try_send(()).map_err(|err
|
319 format_err
!("error while sending abort signal - {}", err
))?
;
324 println
!("Image unmapped");
326 bail
!("unknown archive file extension (expected .pxar or .img)");
335 _rpcenv
: &mut dyn RpcEnvironment
,
336 ) -> Result
<Value
, Error
> {
338 let mut name
= match param
["name"].as_str() {
339 Some(name
) => name
.to_owned(),
341 tools
::fuse_loop
::cleanup_unused_run_files(None
);
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
);
349 println
!("Nothing mapped.");
351 return Ok(Value
::Null
);
355 // allow loop device number alone
356 if let Ok(num
) = name
.parse
::<u8>() {
357 name
= format
!("/dev/loop{}", num
);
360 if name
.starts_with("/dev/loop") {
361 tools
::fuse_loop
::unmap_loopdev(name
)?
;
363 let name
= tools
::systemd
::escape_unit(&name
, false);
364 tools
::fuse_loop
::unmap_name(name
)?
;