firecracker_sdk/vm/
mod.rs

1use anyhow::Result;
2use tokio::{
3    io::{AsyncReadExt, AsyncWriteExt},
4    net::UnixStream,
5};
6
7pub mod firercracker_process;
8pub mod vm_socket;
9
10#[allow(unused)]
11pub struct VM {
12    stream: UnixStream,
13}
14
15#[allow(unused)]
16impl VM {
17    pub fn new(stream: UnixStream) -> Self {
18        Self { stream }
19    }
20
21    async fn send_raw(&mut self, raw: &[u8]) -> Result<()> {
22        self.stream.write_all(raw).await?;
23        Ok(())
24    }
25
26    async fn read_raw(&mut self, raw: &mut [u8]) -> Result<usize> {
27        Ok(self.stream.read(raw).await?)
28    }
29
30    pub async fn close(mut self) -> Result<()> {
31        self.stream.shutdown().await?;
32        Ok(())
33    }
34}
35
36#[cfg(test)]
37mod tests {
38
39    use anyhow::Result;
40    use tempfile::tempdir;
41    use tokio::{
42        io::{AsyncReadExt, AsyncWriteExt},
43        join,
44        net::UnixListener,
45    };
46
47    use crate::vm::vm_socket::VMSocket;
48
49    #[tokio::test]
50    async fn unix_socket_connect_test() -> Result<()> {
51        let dir = tempdir()?;
52        let socket = dir.path().join("echo.socket");
53        let lis = UnixListener::bind(&socket)?;
54
55        assert!(socket.exists());
56
57        let server = tokio::spawn(async move {
58            let (mut socket, _) = lis.accept().await?;
59            let mut buf = [0u8; 64];
60            let n = socket.read(&mut buf).await?;
61            assert_eq!(&buf[..n], b"ping");
62            socket.write_all(b"pong").await?;
63            Ok::<_, anyhow::Error>(())
64        });
65
66        let mut client = VMSocket::new()?.connect(socket).await?;
67        client.send_raw(b"ping").await?;
68        let mut buf = [0u8; 64];
69        let n = client.read_raw(&mut buf).await?;
70        assert_eq!(&buf[..n], b"pong");
71
72        join!(server).0??;
73
74        dir.close()?;
75        Ok(())
76    }
77}