agent: avoid unwrap() in function do_remove_container()

Avoid unwrap() in function do_remove_container(), and also make
implmementation symmetric for both timeout and non-timeout cases.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
This commit is contained in:
Jiang Liu 2023-08-08 10:11:16 +08:00
parent 84badd89d7
commit 71a9f67781

View File

@ -289,45 +289,38 @@ impl AgentService {
if req.timeout == 0 { if req.timeout == 0 {
let mut sandbox = self.sandbox.lock().await; let mut sandbox = self.sandbox.lock().await;
sandbox.bind_watcher.remove_container(&cid).await; sandbox.bind_watcher.remove_container(&cid).await;
sandbox sandbox
.get_container(&cid) .get_container(&cid)
.ok_or_else(|| anyhow!("Invalid container id"))? .ok_or_else(|| anyhow!("Invalid container id"))?
.destroy() .destroy()
.await?; .await?;
remove_container_resources(&mut sandbox, &cid)?; remove_container_resources(&mut sandbox, &cid)?;
return Ok(()); return Ok(());
} }
// timeout != 0 // timeout != 0
let s = self.sandbox.clone(); let s = self.sandbox.clone();
let cid2 = cid.clone(); let cid2 = cid.clone();
let (tx, rx) = tokio::sync::oneshot::channel::<i32>();
let handle = tokio::spawn(async move { let handle = tokio::spawn(async move {
let mut sandbox = s.lock().await; let mut sandbox = s.lock().await;
if let Some(ctr) = sandbox.get_container(&cid2) {
ctr.destroy().await.unwrap();
sandbox.bind_watcher.remove_container(&cid2).await; sandbox.bind_watcher.remove_container(&cid2).await;
tx.send(1).unwrap(); match sandbox.get_container(&cid2) {
}; Some(ctr) => ctr.destroy().await,
None => Err(anyhow!("Invalid container id")),
}
}); });
if tokio::time::timeout(Duration::from_secs(req.timeout.into()), rx) let to = Duration::from_secs(req.timeout.into());
.await match tokio::time::timeout(to, handle).await {
.is_err() Ok(res) => {
{ res??;
return Err(anyhow!(nix::Error::ETIME));
}
handle.await?;
let mut sandbox = self.sandbox.lock().await; let mut sandbox = self.sandbox.lock().await;
remove_container_resources(&mut sandbox, &cid) remove_container_resources(&mut sandbox, &cid)
} }
Err(_e) => Err(anyhow!(nix::Error::ETIME)),
}
}
#[instrument] #[instrument]
async fn do_exec_process(&self, req: protocols::agent::ExecProcessRequest) -> Result<()> { async fn do_exec_process(&self, req: protocols::agent::ExecProcessRequest) -> Result<()> {