Path: blob/main/e2e_tests/guest_under_test/rootfs/delegate/src/main.rs
5394 views
// Copyright 2020 The ChromiumOS Authors1// Use of this source code is governed by a BSD-style license that can be2// found in the LICENSE file.34/// Very crude interactive console to allow the test host to run shell commands5/// in the guest and receive the output.6mod wire_format;78use std::fs::File;9use std::io;10use std::io::prelude::*;11#[cfg(any(target_os = "android", target_os = "linux"))]12use std::os::unix::process::ExitStatusExt;13use std::path::Path;14use std::process::Command;15use std::str;1617use serde_json::Deserializer;1819use crate::wire_format::DelegateMessage;20use crate::wire_format::GuestToHostMessage;21use crate::wire_format::HostToGuestMessage;22use crate::wire_format::ProgramExit;2324/// Device file to read from and write to.25const CONSOLE_FILE: &str = "/dev/ttyS1";2627fn listen(28input: &mut dyn Iterator<Item = Result<DelegateMessage, serde_json::Error>>,29mut output: Box<dyn io::Write>,30) -> io::Result<()> {31output.write_all(32serde_json::to_string_pretty(&DelegateMessage::GuestToHost(GuestToHostMessage::Ready))33.unwrap()34.as_bytes(),35)?;36loop {37if let Some(command) = input.next() {38match command?.assume_host_to_guest() {39HostToGuestMessage::Exit => {40break;41}42HostToGuestMessage::RunCommand {43command: command_string,44} => {45println!("-> {}", &command_string);46let result = Command::new("/bin/sh")47.args(["-c", &command_string])48.output()49.unwrap();50let command_result = GuestToHostMessage::ProgramExit(ProgramExit {51stdout: String::from_utf8_lossy(&result.stdout).into_owned(),52stderr: String::from_utf8_lossy(&result.stderr).into_owned(),53exit_status: match result.status.code() {54Some(code) => wire_format::ExitStatus::Code(code),55#[cfg(any(target_os = "android", target_os = "linux"))]56None => match result.status.signal() {57Some(signal) => wire_format::ExitStatus::Signal(signal),58None => wire_format::ExitStatus::None,59},60#[cfg(not(unix))]61_ => wire_format::ExitStatus::None,62},63});64println!(65"<- {}",66serde_json::to_string_pretty(&command_result).unwrap()67);68output.write_all(69serde_json::to_string_pretty(&DelegateMessage::GuestToHost(command_result))70.unwrap()71.as_bytes(),72)?;73}74}75}76}77Ok(())78}7980fn main() {81let path = Path::new(CONSOLE_FILE);8283let mut command_stream =84Deserializer::from_reader(File::open(path).unwrap()).into_iter::<DelegateMessage>();8586listen(&mut command_stream, Box::new(File::create(path).unwrap())).unwrap();87}888990