patches and low-level development discussion
 help / color / mirror / code / Atom feed
blob abe1742764ee61e84c37d69f98056f3190443361 4374 bytes (raw)
name: tools/start-vmm/ch.rs 	 # note: path name is non-authoritative(*)

  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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
 
// SPDX-License-Identifier: EUPL-1.2+
// SPDX-FileCopyrightText: 2022-2024 Alyssa Ross <hi@alyssa.is>

use std::convert::TryFrom;
use std::ffi::OsStr;
use std::fs::File;
use std::io::Write;
use std::mem::take;
use std::num::NonZeroI32;
use std::os::unix::prelude::*;
use std::path::Path;
use std::process::{Command, Stdio};
use std::string::FromUtf8Error;

use miniserde::{Serialize, json};

use crate::net::MacAddress;
use crate::s6::notify_readiness;

// Trivially safe.
const EPERM: NonZeroI32 = NonZeroI32::new(1).unwrap();
const EPROTO: NonZeroI32 = NonZeroI32::new(71).unwrap();

#[derive(Serialize)]
pub struct ConsoleConfig {
    pub mode: &'static str,
    pub file: Option<String>,
}

#[derive(Serialize)]
pub struct DiskConfig {
    pub path: String,
    pub readonly: bool,
}

#[derive(Serialize)]
pub struct FsConfig {
    pub socket: String,
    pub tag: &'static str,
}

#[derive(Serialize)]
pub struct GpuConfig {
    pub socket: String,
}

#[derive(Serialize)]
pub struct NetConfig {
    pub fd: RawFd,
    pub id: String,
    pub mac: MacAddress,
}

#[derive(Serialize)]
pub struct MemoryConfig {
    pub size: i64,
    pub shared: bool,
}

#[derive(Serialize)]
pub struct PayloadConfig {
    pub kernel: String,
    pub cmdline: &'static str,
}

#[derive(Serialize)]
pub struct VsockConfig {
    pub cid: u32,
    pub socket: String,
}

#[derive(Serialize)]
pub struct LandlockConfig {
    pub path: &'static str,
    pub access: &'static str,
}

#[derive(Serialize)]
pub struct VmConfig {
    pub console: ConsoleConfig,
    pub disks: Vec<DiskConfig>,
    pub fs: [FsConfig; 1],
    pub gpu: Vec<GpuConfig>,
    pub memory: MemoryConfig,
    pub net: Vec<NetConfig>,
    pub payload: PayloadConfig,
    pub serial: ConsoleConfig,
    pub vsock: VsockConfig,
    pub landlock_enable: bool,
    pub landlock_rules: Vec<LandlockConfig>,
}

fn command(vm_dir: &Path, s: impl AsRef<OsStr>) -> Command {
    let mut command = Command::new("ch-remote");
    command.stdin(Stdio::null());
    command.arg("--api-socket");
    command.arg(vm_dir.join("vmm"));
    command.arg(s);
    command
}

pub fn create_vm(vm_dir: &Path, ready_fd: File, mut config: VmConfig) -> Result<(), String> {
    // Net devices can't be created from file descriptors in vm.create.
    // https://github.com/cloud-hypervisor/cloud-hypervisor/issues/5523
    let nets = take(&mut config.net);

    let mut ch_remote = command(vm_dir, "create")
        .args(["--", "-"])
        .stdin(Stdio::piped())
        .spawn()
        .map_err(|e| format!("failed to start ch-remote: {e}"))?;

    let json = json::to_string(&config);
    write!(ch_remote.stdin.as_ref().unwrap(), "{json}")
        .map_err(|e| format!("writing to ch-remote's stdin: {e}"))?;

    let status = ch_remote
        .wait()
        .map_err(|e| format!("waiting for ch-remote: {e}"))?;
    if !status.success() {
        if let Some(code) = status.code() {
            return Err(format!("ch-remote exited {code}"));
        } else {
            let signal = status.signal().unwrap();
            return Err(format!("ch-remote killed by signal {signal}"));
        }
    }

    notify_readiness(ready_fd)?;

    for net in nets {
        add_net(vm_dir, &net).map_err(|e| format!("failed to add net: {e}"))?;
    }

    Ok(())
}

pub fn add_net(vm_dir: &Path, net: &NetConfig) -> Result<(), NonZeroI32> {
    let mut ch_remote = command(vm_dir, "add-net")
        .arg(format!("fd={},id={},mac={}", net.fd, net.id, net.mac))
        .stdout(Stdio::piped())
        .spawn()
        .or(Err(EPERM))?;

    if let Ok(ch_remote_status) = ch_remote.wait()
        && ch_remote_status.success()
    {
        return Ok(());
    }

    Err(EPROTO)
}

#[repr(C)]
pub struct NetConfigC {
    pub fd: RawFd,
    pub id: [u8; 18],
    pub mac: MacAddress,
}

impl<'a> TryFrom<&'a NetConfigC> for NetConfig {
    type Error = FromUtf8Error;

    fn try_from(c: &'a NetConfigC) -> Result<NetConfig, Self::Error> {
        let nul_index = c.id.iter().position(|&c| c == 0).unwrap_or(c.id.len());
        Ok(NetConfig {
            fd: c.fd,
            id: String::from_utf8(c.id[..nul_index].to_vec())?,
            mac: c.mac,
        })
    }
}

impl TryFrom<NetConfigC> for NetConfig {
    type Error = FromUtf8Error;

    fn try_from(c: NetConfigC) -> Result<NetConfig, Self::Error> {
        Self::try_from(&c)
    }
}

debug log:

solving abe1742 ...
found abe1742 in https://spectrum-os.org/git/spectrum

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://spectrum-os.org/git/doc
	https://spectrum-os.org/git/mktuntap
	https://spectrum-os.org/git/spectrum
	https://spectrum-os.org/git/ucspi-vsock

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).