Started on Virt Manager.

This is a new service to manage crosvm instances running VMs. It
provides an AIDL interface which other services can call to start a VM
with some given configuration.

Bug: 171278952
Test: mm
Change-Id: Ie5b10d5f48da430aaeb66af9f2ee082f143472ec
diff --git a/virtmanager/.gitignore b/virtmanager/.gitignore
new file mode 100644
index 0000000..96ef6c0
--- /dev/null
+++ b/virtmanager/.gitignore
@@ -0,0 +1,2 @@
+/target
+Cargo.lock
diff --git a/virtmanager/Android.bp b/virtmanager/Android.bp
new file mode 100644
index 0000000..04b7d8b
--- /dev/null
+++ b/virtmanager/Android.bp
@@ -0,0 +1,14 @@
+rust_binary {
+    name: "virtmanager",
+    crate_name: "virtmanager",
+    srcs: ["src/main.rs"],
+    edition: "2018",
+    rustlibs: [
+        "android.system.virtmanager-rust",
+        "libenv_logger",
+        "liblog_rust",
+        "libserde_json",
+        "libserde",
+        "libanyhow",
+    ],
+}
diff --git a/virtmanager/aidl/Android.bp b/virtmanager/aidl/Android.bp
new file mode 100644
index 0000000..e46bd27
--- /dev/null
+++ b/virtmanager/aidl/Android.bp
@@ -0,0 +1,17 @@
+aidl_interface {
+    name: "android.system.virtmanager",
+    srcs: ["**/*.aidl"],
+    // TODO(qwandor): Consider changing this to false, unless we have a Java wrapper.
+    unstable: true,
+    backend: {
+        java: {
+            sdk_version: "module_current",
+        },
+        cpp: {
+            enabled: true,
+        },
+        rust: {
+            enabled: true,
+        },
+    },
+}
diff --git a/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl b/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl
new file mode 100644
index 0000000..ade8717
--- /dev/null
+++ b/virtmanager/aidl/android/system/virtmanager/IVirtManager.aidl
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.system.virtmanager;
+
+import android.system.virtmanager.IVirtualMachine;
+
+interface IVirtManager {
+        /** Start the VM with the given config file, and return a handle to it. */
+        IVirtualMachine startVm(String configPath);
+}
diff --git a/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl b/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl
new file mode 100644
index 0000000..5f408f8
--- /dev/null
+++ b/virtmanager/aidl/android/system/virtmanager/IVirtualMachine.aidl
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.system.virtmanager;
+
+interface IVirtualMachine {
+        /** Get the CID allocated to the VM. */
+        int getCid();
+}
diff --git a/virtmanager/src/main.rs b/virtmanager/src/main.rs
new file mode 100644
index 0000000..7b0423b
--- /dev/null
+++ b/virtmanager/src/main.rs
@@ -0,0 +1,185 @@
+// Copyright 2021, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Android Virt Manager
+
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::{
+    BnVirtManager, IVirtManager,
+};
+use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
+    BnVirtualMachine, IVirtualMachine,
+};
+use android_system_virtmanager::binder::{self, add_service, Interface, StatusCode};
+use anyhow::{Context, Error};
+use log::{debug, error, info};
+use serde::{Deserialize, Serialize};
+use std::fs::File;
+use std::io::{self, BufReader};
+use std::process::{Child, Command};
+use std::sync::{Arc, Mutex};
+
+/// The first CID to assign to a guest VM managed by the Virt Manager. CIDs lower than this are
+/// reserved for the host or other usage.
+const FIRST_GUEST_CID: Cid = 10;
+
+const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
+
+/// The unique ID of a VM used (together with a port number) for vsock communication.
+type Cid = u32;
+
+/// Configuration for a particular VM to be started.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+struct VmConfig {
+    kernel: String,
+    initrd: Option<String>,
+    params: Option<String>,
+}
+
+fn main() {
+    env_logger::init();
+    let state = Arc::new(Mutex::new(State::new()));
+    let virt_manager = VirtManager::new(state);
+    let virt_manager = BnVirtManager::new_binder(virt_manager);
+    add_service(BINDER_SERVICE_IDENTIFIER, virt_manager.as_binder()).unwrap();
+    info!("Registered Binder service, joining threadpool.");
+    binder::ProcessState::join_thread_pool();
+}
+
+#[derive(Debug)]
+struct VirtManager {
+    state: Arc<Mutex<State>>,
+}
+
+impl VirtManager {
+    fn new(state: Arc<Mutex<State>>) -> Self {
+        VirtManager { state }
+    }
+}
+
+impl Interface for VirtManager {}
+
+impl IVirtManager for VirtManager {
+    /// Create and start a new VM with the given configuration, assigning it the next available CID.
+    ///
+    /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
+    fn startVm(&self, config_path: &str) -> binder::Result<Box<dyn IVirtualMachine>> {
+        let state = &mut *self.state.lock().unwrap();
+        let cid = state.next_cid;
+        let child = start_vm(config_path, cid)?;
+        // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
+        state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
+        Ok(VirtualMachine::create(Arc::new(VmInstance::new(child, cid))))
+    }
+}
+
+/// Implementation of the AIDL IVirtualMachine interface. Used as a handle to a VM.
+#[derive(Debug)]
+struct VirtualMachine {
+    instance: Arc<VmInstance>,
+}
+
+impl VirtualMachine {
+    fn create(instance: Arc<VmInstance>) -> Box<dyn IVirtualMachine> {
+        let binder = VirtualMachine { instance };
+        Box::new(BnVirtualMachine::new_binder(binder))
+    }
+}
+
+impl Interface for VirtualMachine {}
+
+impl IVirtualMachine for VirtualMachine {
+    fn getCid(&self) -> binder::Result<i32> {
+        Ok(self.instance.cid as i32)
+    }
+}
+
+/// Information about a particular instance of a VM which is running.
+#[derive(Debug)]
+struct VmInstance {
+    /// The crosvm child process.
+    child: Child,
+    /// The CID assigned to the VM for vsock communication.
+    cid: Cid,
+}
+
+impl VmInstance {
+    /// Create a new `VmInstance` with a single reference for the given process.
+    fn new(child: Child, cid: Cid) -> VmInstance {
+        VmInstance { child, cid }
+    }
+}
+
+impl Drop for VmInstance {
+    fn drop(&mut self) {
+        debug!("Dropping {:?}", self);
+        // TODO: Talk to crosvm to shutdown cleanly.
+        if let Err(e) = self.child.kill() {
+            error!("Error killing crosvm instance: {}", e);
+        }
+        // We need to wait on the process after killing it to avoid zombies.
+        match self.child.wait() {
+            Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
+            Ok(status) => info!("Crosvm exited with status {}", status),
+        }
+    }
+}
+
+/// The mutable state of the Virt Manager. There should only be one instance of this struct.
+#[derive(Debug)]
+struct State {
+    next_cid: Cid,
+}
+
+impl State {
+    fn new() -> Self {
+        State { next_cid: FIRST_GUEST_CID }
+    }
+}
+
+/// Start a new VM instance from the given VM config filename. This assumes the VM is not already
+/// running.
+fn start_vm(config_path: &str, cid: Cid) -> binder::Result<Child> {
+    let config = load_vm_config(config_path).map_err(|e| {
+        error!("Failed to load VM config {}: {:?}", config_path, e);
+        StatusCode::BAD_VALUE
+    })?;
+    Ok(run_vm(&config, cid).map_err(|e| {
+        error!("Failed to start VM {}: {:?}", config_path, e);
+        StatusCode::UNKNOWN_ERROR
+    })?)
+}
+
+/// Load the configuration for the VM with the given ID from a JSON file.
+fn load_vm_config(path: &str) -> Result<VmConfig, Error> {
+    let file = File::open(path).with_context(|| format!("Failed to open {}", path))?;
+    let buffered = BufReader::new(file);
+    Ok(serde_json::from_reader(buffered)?)
+}
+
+/// Start an instance of `crosvm` to manage a new VM.
+fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, io::Error> {
+    let mut command = Command::new("crosvm");
+    // TODO(qwandor): Remove --disable-sandbox.
+    command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
+    if let Some(initrd) = &config.initrd {
+        command.arg("--initrd").arg(initrd);
+    }
+    if let Some(params) = &config.params {
+        command.arg("--params").arg(params);
+    }
+    command.arg(&config.kernel);
+    info!("Running {:?}", command);
+    // TODO: Monitor child process, and remove from VM map if it dies.
+    command.spawn()
+}