vmm: speed up JSON load when reading snap files

We found that it's slow to load JSON when reading snap files. As
described in [1], using from_slice instead of from_reader can fix
this.

Also, fix the error type being returned.

1. https://github.com/serde-rs/json/issues/160

Signed-off-by: Yi Wang <foxywang@tencent.com>
This commit is contained in:
Yi Wang 2023-11-14 15:41:18 +08:00 committed by Bo Chen
parent 0eade51306
commit a69d8c63b3

View File

@ -7,7 +7,7 @@ use crate::coredump::GuestDebuggableError;
use crate::{config::VmConfig, vm::VmSnapshot};
use anyhow::anyhow;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
use std::path::PathBuf;
use vm_migration::{MigratableError, Snapshot};
@ -49,10 +49,14 @@ pub fn recv_vm_config(source_url: &str) -> std::result::Result<VmConfig, Migrata
vm_config_path.push(SNAPSHOT_CONFIG_FILE);
// Try opening the snapshot file
let vm_config_file =
File::open(vm_config_path).map_err(|e| MigratableError::MigrateSend(e.into()))?;
let vm_config_reader = BufReader::new(vm_config_file);
serde_json::from_reader(vm_config_reader).map_err(|e| MigratableError::MigrateReceive(e.into()))
let mut vm_config_file =
File::open(vm_config_path).map_err(|e| MigratableError::MigrateReceive(e.into()))?;
let mut bytes = Vec::new();
vm_config_file
.read_to_end(&mut bytes)
.map_err(|e| MigratableError::MigrateReceive(e.into()))?;
serde_json::from_slice(&bytes).map_err(|e| MigratableError::MigrateReceive(e.into()))
}
pub fn recv_vm_state(source_url: &str) -> std::result::Result<Snapshot, MigratableError> {
@ -61,10 +65,14 @@ pub fn recv_vm_state(source_url: &str) -> std::result::Result<Snapshot, Migratab
vm_state_path.push(SNAPSHOT_STATE_FILE);
// Try opening the snapshot file
let vm_state_file =
File::open(vm_state_path).map_err(|e| MigratableError::MigrateSend(e.into()))?;
let vm_state_reader = BufReader::new(vm_state_file);
serde_json::from_reader(vm_state_reader).map_err(|e| MigratableError::MigrateReceive(e.into()))
let mut vm_state_file =
File::open(vm_state_path).map_err(|e| MigratableError::MigrateReceive(e.into()))?;
let mut bytes = Vec::new();
vm_state_file
.read_to_end(&mut bytes)
.map_err(|e| MigratableError::MigrateReceive(e.into()))?;
serde_json::from_slice(&bytes).map_err(|e| MigratableError::MigrateReceive(e.into()))
}
pub fn get_vm_snapshot(snapshot: &Snapshot) -> std::result::Result<VmSnapshot, MigratableError> {