xref: /cloud-hypervisor/vmm/src/migration.rs (revision 5e52729453cb62edbe4fb3a4aa24f8cca31e667e)
1 // Copyright © 2020 Intel Corporation
2 //
3 // SPDX-License-Identifier: Apache-2.0
4 
5 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
6 use crate::coredump::GuestDebuggableError;
7 use crate::{config::VmConfig, vm::VmSnapshot};
8 use anyhow::anyhow;
9 use std::fs::File;
10 use std::io::BufReader;
11 use std::path::PathBuf;
12 use vm_migration::{MigratableError, Snapshot};
13 
14 pub const SNAPSHOT_STATE_FILE: &str = "state.json";
15 pub const SNAPSHOT_CONFIG_FILE: &str = "config.json";
16 
17 pub fn url_to_path(url: &str) -> std::result::Result<PathBuf, MigratableError> {
18     let path: PathBuf = url
19         .strip_prefix("file://")
20         .ok_or_else(|| {
21             MigratableError::MigrateSend(anyhow!("Could not extract path from URL: {}", url))
22         })
23         .map(|s| s.into())?;
24 
25     if !path.is_dir() {
26         return Err(MigratableError::MigrateSend(anyhow!(
27             "Destination is not a directory"
28         )));
29     }
30 
31     Ok(path)
32 }
33 
34 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
35 pub fn url_to_file(url: &str) -> std::result::Result<PathBuf, GuestDebuggableError> {
36     let file: PathBuf = url
37         .strip_prefix("file://")
38         .ok_or_else(|| {
39             GuestDebuggableError::Coredump(anyhow!("Could not extract file from URL: {}", url))
40         })
41         .map(|s| s.into())?;
42 
43     Ok(file)
44 }
45 
46 pub fn recv_vm_config(source_url: &str) -> std::result::Result<VmConfig, MigratableError> {
47     let mut vm_config_path = url_to_path(source_url)?;
48 
49     vm_config_path.push(SNAPSHOT_CONFIG_FILE);
50 
51     // Try opening the snapshot file
52     let vm_config_file =
53         File::open(vm_config_path).map_err(|e| MigratableError::MigrateSend(e.into()))?;
54     let vm_config_reader = BufReader::new(vm_config_file);
55     serde_json::from_reader(vm_config_reader).map_err(|e| MigratableError::MigrateReceive(e.into()))
56 }
57 
58 pub fn recv_vm_state(source_url: &str) -> std::result::Result<Snapshot, MigratableError> {
59     let mut vm_state_path = url_to_path(source_url)?;
60 
61     vm_state_path.push(SNAPSHOT_STATE_FILE);
62 
63     // Try opening the snapshot file
64     let vm_state_file =
65         File::open(vm_state_path).map_err(|e| MigratableError::MigrateSend(e.into()))?;
66     let vm_state_reader = BufReader::new(vm_state_file);
67     serde_json::from_reader(vm_state_reader).map_err(|e| MigratableError::MigrateReceive(e.into()))
68 }
69 
70 pub fn get_vm_snapshot(snapshot: &Snapshot) -> std::result::Result<VmSnapshot, MigratableError> {
71     if let Some(snapshot_data) = snapshot.snapshot_data.as_ref() {
72         return snapshot_data.to_state();
73     }
74 
75     Err(MigratableError::Restore(anyhow!(
76         "Could not find VM config snapshot section"
77     )))
78 }
79