vmm: Simplify snapshot/restore path handling

Extend the existing url_to_path() to take the URL string and then use
that to simplify the snapshot/restore code paths.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
This commit is contained in:
Rob Bradford
2021-03-12 10:46:36 +00:00
committed by Sebastien Boeuf
parent ebcbab739e
commit cc78a597cd
3 changed files with 50 additions and 88 deletions
+22 -43
View File
@@ -7,61 +7,40 @@ use anyhow::anyhow;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use url::Url;
use vm_migration::{MigratableError, Snapshot};
pub const VM_SNAPSHOT_FILE: &str = "vm.json";
pub fn url_to_path(url: &Url) -> std::result::Result<PathBuf, MigratableError> {
match url.scheme() {
"file" => url
.to_file_path()
.map_err(|_| {
MigratableError::MigrateSend(anyhow!(
"Could not convert file URL to a file path: {}",
url.as_str()
))
})
.and_then(|path| {
if !path.is_dir() {
return Err(MigratableError::MigrateSend(anyhow!(
"Destination is not a directory"
)));
}
Ok(path)
}),
pub fn url_to_path(url: &str) -> std::result::Result<PathBuf, MigratableError> {
let path: PathBuf = url
.strip_prefix("file://")
.ok_or_else(|| {
MigratableError::MigrateSend(anyhow!("Could not extract path from URL: {}", url))
})
.map(|s| s.into())?;
_ => Err(MigratableError::MigrateSend(anyhow!(
"URL scheme is not file: {}",
url.scheme()
))),
if !path.is_dir() {
return Err(MigratableError::MigrateSend(anyhow!(
"Destination is not a directory"
)));
}
Ok(path)
}
pub fn recv_vm_snapshot(source_url: &str) -> std::result::Result<Snapshot, MigratableError> {
let url = Url::parse(source_url).map_err(|e| {
MigratableError::MigrateSend(anyhow!("Could not parse destination URL: {}", e))
})?;
let mut vm_snapshot_path = url_to_path(source_url)?;
match url.scheme() {
"file" => {
let mut vm_snapshot_path = url_to_path(&url)?;
vm_snapshot_path.push(VM_SNAPSHOT_FILE);
vm_snapshot_path.push(VM_SNAPSHOT_FILE);
// Try opening the snapshot file
let vm_snapshot_file =
File::open(vm_snapshot_path).map_err(|e| MigratableError::MigrateSend(e.into()))?;
let vm_snapshot_reader = BufReader::new(vm_snapshot_file);
let vm_snapshot = serde_json::from_reader(vm_snapshot_reader)
.map_err(|e| MigratableError::MigrateReceive(e.into()))?;
// Try opening the snapshot file
let vm_snapshot_file =
File::open(vm_snapshot_path).map_err(|e| MigratableError::MigrateSend(e.into()))?;
let vm_snapshot_reader = BufReader::new(vm_snapshot_file);
let vm_snapshot = serde_json::from_reader(vm_snapshot_reader)
.map_err(|e| MigratableError::MigrateReceive(e.into()))?;
Ok(vm_snapshot)
}
_ => Err(MigratableError::MigrateSend(anyhow!(
"Unsupported VM transport URL scheme: {}",
url.scheme()
))),
}
Ok(vm_snapshot)
}
pub fn get_vm_snapshot(snapshot: &Snapshot) -> std::result::Result<VmSnapshot, MigratableError> {