Skip to content

Commit

Permalink
task: support exec into vm
Browse files Browse the repository at this point in the history
Signed-off-by: Zhang Tianyang <burning9699@gmail.com>
  • Loading branch information
Burning1020 committed Aug 14, 2024
1 parent e826a96 commit 8c119d3
Showing 1 changed file with 52 additions and 6 deletions.
58 changes: 52 additions & 6 deletions vmm/task/src/sandbox_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.

use std::{
ops::Add,
process::Stdio,
sync::Arc,
time::{Duration, SystemTime},
};
Expand All @@ -24,6 +25,7 @@ use async_trait::async_trait;
use containerd_sandbox::PodSandboxConfig;
use containerd_shim::{
error::Result,
io_error, other, other_error,
protos::{protobuf::MessageDyn, topics::TASK_OOM_EVENT_TOPIC},
util::convert_to_any,
Error, TtrpcContext, TtrpcResult,
Expand All @@ -33,7 +35,10 @@ use nix::{
sys::time::{TimeSpec, TimeValLike},
time::{clock_gettime, clock_settime, ClockId},
};
use tokio::sync::{mpsc::Receiver, Mutex};
use tokio::{
io::AsyncWriteExt,
sync::{mpsc::Receiver, Mutex},
};
use vmm_common::{
api,
api::{
Expand Down Expand Up @@ -139,12 +144,13 @@ impl api::sandbox_ttrpc::SandboxService for SandboxService {
async fn exec_vm_process(
&self,
_ctx: &TtrpcContext,
_req: ExecVMProcessRequest,
req: ExecVMProcessRequest,
) -> TtrpcResult<ExecVMProcessResponse> {
Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(
::ttrpc::Code::NOT_FOUND,
"/grpc.SandboxService/ExecVMProcess is not supported".to_string(),
)))
let out = do_execute_cmd(&req.command, req.stdin.as_slice()).await?;

let mut resp = ExecVMProcessResponse::new();
resp.out = out;
Ok(resp)
}

async fn sync_clock(
Expand Down Expand Up @@ -194,3 +200,43 @@ impl api::sandbox_ttrpc::SandboxService for SandboxService {
Err(ttrpc::Error::Others("internal".to_string()))
}
}

async fn do_execute_cmd(cmd_args: &str, stdin: &[u8]) -> Result<String> {
let mut cmd = tokio::process::Command::new("/bin/bash");
cmd.arg("-c");
cmd.arg(cmd_args);
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
if stdin.len() > 0 {
cmd.stdin(Stdio::piped());
}

let mut child = cmd
.spawn()
.map_err(io_error!(e, "spawn exec vm process failed:"))?;
if stdin.len() > 0 {
let cmd_in = child.stdin.as_mut().ok_or(other!("no stdin for command"))?;
cmd_in
.write_all(stdin)
.await
.map_err(io_error!(e, "failed to write vm process stdin:"))?;
}

let output = child
.wait_with_output()
.await
.map_err(io_error!(e, "failed to combined process output:"))?;
return if output.status.success() {
let raw_output =
String::from_utf8(output.stdout).map_err(other_error!(e, "failed to convert"))?;
Ok(raw_output)
} else {
let err_msg =
String::from_utf8(output.stderr).map_err(other_error!(e, "failed to convert"))?;
Err(other!(
"cmd {} failed with status {:?} and error message {}",
cmd_args,
output.status,
err_msg
))
};
}

0 comments on commit 8c119d3

Please sign in to comment.