Skip to content

Commit fd72d1a

Browse files
Jonathan Woollett-Lightwearyzen
authored andcommitted
refactor: Simplify build_microvm_from_requests
Simplifies `build_microvm_from_requests` by removing generic `Fn` arguments which where not needed. Signed-off-by: Jonathan Woollett-Light <jcawl@amazon.co.uk>
1 parent fa1e2ab commit fd72d1a

File tree

4 files changed

+33
-95
lines changed

4 files changed

+33
-95
lines changed

src/api_server/src/lib.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,12 @@ pub use micro_http::{
2424
use seccompiler::BpfProgramRef;
2525
use serde_json::json;
2626
use utils::eventfd::EventFd;
27-
use vmm::rpc_interface::{VmmAction, VmmActionError, VmmData};
27+
use vmm::rpc_interface::{ApiRequest, ApiResponse, VmmAction, VmmData};
2828
use vmm::vmm_config::snapshot::SnapshotType;
2929

3030
use crate::parsed_request::{ParsedRequest, RequestAction};
3131
use crate::Error::ServerCreation;
3232

33-
/// Shorthand type for a request containing a boxed VmmAction.
34-
pub type ApiRequest = Box<VmmAction>;
35-
/// Shorthand type for a response containing a boxed Result.
36-
pub type ApiResponse = Box<std::result::Result<VmmData, VmmActionError>>;
37-
3833
/// Errors thrown when binding the API server to the socket path.
3934
#[derive(Debug)]
4035
pub enum Error {

src/firecracker/src/api_server_adapter.rs

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,16 @@ use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
99
use std::sync::{Arc, Mutex};
1010
use std::thread;
1111

12-
use api_server::{ApiRequest, ApiResponse, ApiServer, ServerError};
12+
use api_server::{ApiServer, ServerError};
1313
use event_manager::{EventOps, Events, MutEventSubscriber, SubscriberOps};
1414
use logger::{error, warn, ProcessTimeReporter};
1515
use seccompiler::BpfThreadMap;
1616
use utils::epoll::EventSet;
1717
use utils::eventfd::EventFd;
1818
use vmm::resources::VmResources;
19-
use vmm::rpc_interface::{PrebootApiController, RuntimeApiController, VmmAction};
19+
use vmm::rpc_interface::{
20+
ApiRequest, ApiResponse, PrebootApiController, RuntimeApiController, VmmAction,
21+
};
2022
use vmm::vmm_config::instance_info::InstanceInfo;
2123
use vmm::{EventManager, FcExitCode, Vmm};
2224

@@ -201,24 +203,9 @@ pub(crate) fn run_with_api(
201203
seccomp_filters,
202204
&mut event_manager,
203205
instance_info,
204-
|| {
205-
let req = from_api
206-
.recv()
207-
.expect("The channel's sending half was disconnected. Cannot receive data.");
208-
209-
// Also consume the API event along with the message. It is safe to unwrap()
210-
// because this event_fd is blocking.
211-
api_event_fd
212-
.read()
213-
.expect("VMM: Failed to read the API event_fd");
214-
215-
*req
216-
},
217-
|response| {
218-
to_api
219-
.send(Box::new(response))
220-
.expect("one-shot channel closed")
221-
},
206+
&from_api,
207+
&to_api,
208+
&api_event_fd,
222209
boot_timer_enabled,
223210
mmds_size_limit,
224211
metadata_json,

src/vmm/src/rpc_interface.rs

Lines changed: 23 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,11 @@ pub enum LoadSnapshotError {
309309
ResumeMicrovm(#[from] VmmError),
310310
}
311311

312+
/// Shorthand type for a request containing a boxed VmmAction.
313+
pub type ApiRequest = Box<VmmAction>;
314+
/// Shorthand type for a response containing a boxed Result.
315+
pub type ApiResponse = Box<std::result::Result<VmmData, VmmActionError>>;
316+
312317
impl<'a> PrebootApiController<'a> {
313318
/// Constructor for the PrebootApiController.
314319
pub fn new(
@@ -329,25 +334,20 @@ impl<'a> PrebootApiController<'a> {
329334
}
330335

331336
/// Default implementation for the function that builds and starts a microVM.
332-
/// It takes two closures `recv_req` and `respond` as params which abstract away
333-
/// the message transport.
334337
///
335338
/// Returns a populated `VmResources` object and a running `Vmm` object.
336339
#[allow(clippy::too_many_arguments)]
337-
pub fn build_microvm_from_requests<F, G>(
340+
pub fn build_microvm_from_requests(
338341
seccomp_filters: &BpfThreadMap,
339342
event_manager: &mut EventManager,
340343
instance_info: InstanceInfo,
341-
recv_req: F,
342-
respond: G,
344+
from_api: &std::sync::mpsc::Receiver<ApiRequest>,
345+
to_api: &std::sync::mpsc::Sender<ApiResponse>,
346+
api_event_fd: &utils::eventfd::EventFd,
343347
boot_timer_enabled: bool,
344348
mmds_size_limit: usize,
345349
metadata_json: Option<&str>,
346-
) -> Result<(VmResources, Arc<Mutex<Vmm>>), FcExitCode>
347-
where
348-
F: Fn() -> VmmAction,
349-
G: Fn(Result<VmmData, VmmActionError>),
350-
{
350+
) -> Result<(VmResources, Arc<Mutex<Vmm>>), FcExitCode> {
351351
let mut vm_resources = VmResources::default();
352352
// Silence false clippy warning. Clippy suggests using
353353
// VmResources { boot_timer: boot_timer_enabled, ..Default::default() }; but this will
@@ -386,11 +386,21 @@ impl<'a> PrebootApiController<'a> {
386386
// The loop breaks when a microVM is successfully started, and a running Vmm is built.
387387
while preboot_controller.built_vmm.is_none() {
388388
// Get request
389-
let req = recv_req();
389+
let req = from_api
390+
.recv()
391+
.expect("The channel's sending half was disconnected. Cannot receive data.");
392+
393+
// Also consume the API event along with the message. It is safe to unwrap()
394+
// because this event_fd is blocking.
395+
api_event_fd
396+
.read()
397+
.expect("VMM: Failed to read the API event_fd");
398+
390399
// Process the request.
391-
let res = preboot_controller.handle_preboot_request(req);
400+
let res = preboot_controller.handle_preboot_request(*req);
401+
392402
// Send back the response.
393-
respond(res);
403+
to_api.send(Box::new(res)).expect("one-shot channel closed");
394404

395405
// If any fatal errors were encountered, break the loop.
396406
if let Some(exit_code) = preboot_controller.fatal_error {
@@ -1827,60 +1837,6 @@ mod tests {
18271837
);
18281838
}
18291839

1830-
#[test]
1831-
fn test_build_microvm_from_requests() {
1832-
// Use atomics to be able to use them non-mutably in closures below.
1833-
use std::sync::atomic::{AtomicUsize, Ordering};
1834-
1835-
let cmd_step = AtomicUsize::new(0);
1836-
let commands = || {
1837-
cmd_step.fetch_add(1, Ordering::SeqCst);
1838-
match cmd_step.load(Ordering::SeqCst) {
1839-
1 => VmmAction::FlushMetrics,
1840-
2 => VmmAction::Pause,
1841-
3 => VmmAction::Resume,
1842-
4 => VmmAction::StartMicroVm,
1843-
_ => unreachable!(),
1844-
}
1845-
};
1846-
1847-
let resp_step = AtomicUsize::new(0);
1848-
let expected_resp = |resp: Result<VmmData, VmmActionError>| {
1849-
resp_step.fetch_add(1, Ordering::SeqCst);
1850-
let expect = match resp_step.load(Ordering::SeqCst) {
1851-
1 => Err(VmmActionError::OperationNotSupportedPreBoot),
1852-
2 => Err(VmmActionError::OperationNotSupportedPreBoot),
1853-
3 => Err(VmmActionError::OperationNotSupportedPreBoot),
1854-
4 => Ok(VmmData::Empty),
1855-
_ => unreachable!(),
1856-
};
1857-
assert_eq!(resp, expect);
1858-
};
1859-
1860-
let (vm_res, _vmm) = PrebootApiController::build_microvm_from_requests(
1861-
&BpfThreadMap::new(),
1862-
&mut EventManager::new().unwrap(),
1863-
InstanceInfo::default(),
1864-
commands,
1865-
expected_resp,
1866-
false,
1867-
HTTP_MAX_PAYLOAD_SIZE,
1868-
Some(r#""magic""#),
1869-
)
1870-
.unwrap();
1871-
1872-
assert_eq!(
1873-
vm_res
1874-
.mmds
1875-
.as_ref()
1876-
.unwrap()
1877-
.lock()
1878-
.unwrap()
1879-
.data_store_value(),
1880-
Value::String("magic".to_string())
1881-
);
1882-
}
1883-
18841840
fn check_runtime_request<F>(request: VmmAction, check_success: F)
18851841
where
18861842
F: FnOnce(Result<VmmData, VmmActionError>, &MockVmm),

tests/integration_tests/build/test_coverage.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ def is_on_skylake():
2525
# Checkout the cpuid crate. In the future other
2626
# differences may appear.
2727
if utils.is_io_uring_supported():
28-
COVERAGE_DICT = {"Intel": 82.64, "AMD": 81.89, "ARM": 81.18}
28+
COVERAGE_DICT = {"Intel": 82.44, "AMD": 81.68, "ARM": 80.95}
2929
else:
30-
COVERAGE_DICT = {"Intel": 79.95, "AMD": 79.11, "ARM": 78.23}
30+
COVERAGE_DICT = {"Intel": 79.76, "AMD": 78.90, "ARM": 78.01}
3131

3232
PROC_MODEL = proc.proc_type()
3333

0 commit comments

Comments
 (0)