runtime-rs: introduce a new function generate_vhost_vsock_cid.

Introduce a new function generate_vhost_vsock_cid to generate
a guest CID and set guest CID for vsock fd.
Also this commit wouldn't introduce functional change and it's
just splited from the previous VsockDevice::new().

Fixes: #8474

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
This commit is contained in:
alex.lyn 2023-11-27 15:06:58 +08:00
parent 231b9dfd9d
commit eb90962b27

View File

@ -121,6 +121,21 @@ const CID_RETRY_COUNT: u32 = 50;
impl VsockDevice { impl VsockDevice {
pub async fn new(id: String) -> Result<Self> { pub async fn new(id: String) -> Result<Self> {
let (guest_cid, vhost_fd) = generate_vhost_vsock_cid()
.await
.context("generate vhost vsock cid failed")?;
Ok(Self {
id,
config: VsockConfig {
guest_cid,
vhost_fd,
},
})
}
}
pub async fn generate_vhost_vsock_cid() -> Result<(u32, File)> {
let vhost_fd = OpenOptions::new() let vhost_fd = OpenOptions::new()
.read(true) .read(true)
.write(true) .write(true)
@ -140,27 +155,19 @@ impl VsockDevice {
let guest_cid = let guest_cid =
unsafe { vhost_vsock_set_guest_cid(vhost_fd.as_raw_fd(), &(rand_cid as u64)) }; unsafe { vhost_vsock_set_guest_cid(vhost_fd.as_raw_fd(), &(rand_cid as u64)) };
match guest_cid { match guest_cid {
Ok(_) => { Ok(_) => return Ok((rand_cid, vhost_fd)),
return Ok(VsockDevice {
id,
config: VsockConfig {
guest_cid: rand_cid,
vhost_fd,
},
});
}
Err(nix::Error::EADDRINUSE) => { Err(nix::Error::EADDRINUSE) => {
// The CID is already in use. Try another one. // The CID is already in use. Try another one.
continue;
} }
Err(err) => { Err(err) => {
return Err(err).context("failed to set guest CID"); return Err(err).context("failed to set guest CID");
} }
} };
} }
anyhow::bail!( anyhow::bail!(
"failed to find a free vsock context ID after {} attempts", "failed to find a free vsock context ID after {} attempts",
CID_RETRY_COUNT CID_RETRY_COUNT
); );
}
} }