1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Provides `VhostUserBackend`, a fixture of a vhost-user backend process.

use std::process;
use std::process::Command;
use std::process::Stdio;
use std::thread;
use std::time::Duration;

use anyhow::Result;
use base::test_utils::check_can_sudo;

use crate::utils::find_crosvm_binary;

pub enum CmdType {
    /// `crosvm device` command
    Device,
    /// `crosvm devices` command that is newer and supports sandboxing and multiple device
    /// processes.
    Devices,
}

impl CmdType {
    fn to_subcommand(&self) -> &str {
        match self {
            // `crosvm device`
            CmdType::Device => "device",
            // `crosvm devices`
            CmdType::Devices => "devices",
        }
    }
}

pub struct Config {
    cmd_type: CmdType,
    dev_name: String,
    extra_args: Vec<String>,
}

impl Config {
    pub fn new(cmd_type: CmdType, name: &str) -> Self {
        Config {
            cmd_type,
            dev_name: name.to_string(),
            extra_args: Default::default(),
        }
    }

    /// Uses extra arguments for `crosvm (device|devices)`.
    pub fn extra_args(mut self, args: Vec<String>) -> Self {
        self.extra_args = args;
        self
    }
}

#[derive(Default)]
pub struct VhostUserBackend {
    name: String,
    process: Option<process::Child>,
}

impl VhostUserBackend {
    pub fn new(cfg: Config) -> Result<Self> {
        let cmd = Command::new(find_crosvm_binary());
        Self::new_common(cmd, cfg)
    }

    /// Start up Vhost User Backend `sudo`.
    pub fn new_sudo(cfg: Config) -> Result<Self> {
        check_can_sudo();

        let mut cmd = Command::new("sudo");
        cmd.arg(find_crosvm_binary());
        Self::new_common(cmd, cfg)
    }

    fn new_common(mut cmd: Command, cfg: Config) -> Result<Self> {
        cmd.args([cfg.cmd_type.to_subcommand()]);
        cmd.args(cfg.extra_args);

        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        println!("$ {:?}", cmd);

        let process = Some(cmd.spawn()?);
        // TODO(b/269174700): Wait for the VU socket to be available instead.
        thread::sleep(Duration::from_millis(100));

        Ok(Self {
            name: cfg.dev_name,
            process,
        })
    }
}

impl Drop for VhostUserBackend {
    fn drop(&mut self) {
        let output = self.process.take().unwrap().wait_with_output().unwrap();

        // Print both the crosvm's stdout/stderr to stdout so that they'll be shown when the test
        // is failed.
        println!(
            "VhostUserBackend {} stdout:\n{}",
            self.name,
            std::str::from_utf8(&output.stdout).unwrap()
        );
        println!(
            "VhostUserBackend {} stderr:\n{}",
            self.name,
            std::str::from_utf8(&output.stderr).unwrap()
        );

        if !output.status.success() {
            panic!(
                "VhostUserBackend {} exited illegally: {}",
                self.name, output.status
            );
        }
    }
}