Skip to content

Commit c98217f

Browse files
committed
Implement Container::{start,pause,resume,delete}
Note that `Container::delete()` consumes `self` to statically guarantee that we cannot delete a container twice.
1 parent daecb45 commit c98217f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/container.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,38 @@ impl Container {
101101
})
102102
}
103103

104+
/// Start the container, if it isn't already running.
105+
pub async fn start(&self) -> anyhow::Result<()> {
106+
let mut pause_cmd = Command::new(RUNTIME_BIN);
107+
pause_cmd.args(&["start", &self.name]);
108+
exec_command(&mut pause_cmd).await?;
109+
Ok(())
110+
}
111+
112+
/// Pause the container's execution, if it currently running.
113+
pub async fn pause(&self) -> anyhow::Result<()> {
114+
let mut pause_cmd = Command::new(RUNTIME_BIN);
115+
pause_cmd.args(&["pause", &self.name]);
116+
exec_command(&mut pause_cmd).await?;
117+
Ok(())
118+
}
119+
120+
/// Resume the container's execution, if it currently paused.
121+
pub async fn resume(&self) -> anyhow::Result<()> {
122+
let mut resume_cmd = Command::new(RUNTIME_BIN);
123+
resume_cmd.args(&["resume", &self.name]);
124+
exec_command(&mut resume_cmd).await?;
125+
Ok(())
126+
}
127+
128+
/// Delete the container immediately.
129+
pub async fn delete(self) -> anyhow::Result<()> {
130+
let mut delete_cmd = Command::new(RUNTIME_BIN);
131+
delete_cmd.args(&["delete", "--force", &self.name]);
132+
exec_command(&mut delete_cmd).await?;
133+
Ok(())
134+
}
135+
104136
/// Returns the name of the container.
105137
pub fn name(&self) -> &str {
106138
&self.name
@@ -117,3 +149,13 @@ impl Drop for Container {
117149
unsafe { libc::kill(self.pid, libc::SIGKILL) };
118150
}
119151
}
152+
153+
async fn exec_command(cmd: &mut Command) -> anyhow::Result<()> {
154+
let output = cmd.output().await?;
155+
if !output.status.success() {
156+
let stderr = std::str::from_utf8(&output.stderr)?;
157+
return Err(anyhow!("`{:?}` returned: [{}]", cmd, stderr));
158+
}
159+
160+
Ok(())
161+
}

0 commit comments

Comments
 (0)