From 3a73b3b12281811173056bbbc881f2d22b6617b9 Mon Sep 17 00:00:00 2001
From: Wei Gao <gaowei66@huawei.com>
Date: Mon, 14 Dec 2020 01:33:51 -0500
Subject: [PATCH 1/2] machine_manager: remove all qmp features attribute.

Signed-off-by: Wei Gao <gaowei66@huawei.com>
---
 Cargo.toml                       |   3 +-
 device_model/Cargo.toml          |   3 +-
 device_model/src/cpu/mod.rs      |  14 ++--
 device_model/src/micro_vm/mod.rs | 107 ++++++++++++++-----------------
 machine_manager/Cargo.toml       |   3 +-
 machine_manager/src/lib.rs       |   1 -
 machine_manager/src/machine.rs   |   9 +--
 machine_manager/src/socket.rs    |  32 ++-------
 src/main.rs                      |   2 -
 9 files changed, 62 insertions(+), 112 deletions(-)

diff --git a/Cargo.toml b/Cargo.toml
index 7a96d2e..262203e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,8 +29,7 @@ name = "stratovirt"
 path = "src/main.rs"
 
 [features]
-default = ["qmp"]
-qmp = []
+default = []
 
 [package.metadata.rpm.cargo]
 buildflags = ["--release"]
diff --git a/device_model/Cargo.toml b/device_model/Cargo.toml
index 43de30f..b165c8c 100644
--- a/device_model/Cargo.toml
+++ b/device_model/Cargo.toml
@@ -21,6 +21,5 @@ machine_manager = { path = "../machine_manager" }
 boot_loader = { path = "../boot_loader" }
 
 [features]
-default = ["qmp"]
+default = []
 mmio = []
-qmp = []
diff --git a/device_model/src/cpu/mod.rs b/device_model/src/cpu/mod.rs
index 203fea1..83a5ef5 100644
--- a/device_model/src/cpu/mod.rs
+++ b/device_model/src/cpu/mod.rs
@@ -40,7 +40,6 @@ use kvm_ioctls::{VcpuExit, VcpuFd};
 use libc::{c_int, c_void, siginfo_t};
 use vmm_sys_util::signal::{register_signal_handler, Killable};
 
-#[cfg(feature = "qmp")]
 use machine_manager::{qmp::qmp_schema as schema, qmp::QmpChannel};
 
 use self::errors::{ErrorKind, Result};
@@ -453,14 +452,11 @@ impl CPUInterface for CPU {
         *cpu_state.lock().unwrap() = CpuLifecycleState::Stopped;
         self.vm.destroy();
 
-        #[cfg(feature = "qmp")]
-        {
-            let shutdown_msg = schema::SHUTDOWN {
-                guest: true,
-                reason: "guest-shutdown".to_string(),
-            };
-            event!(SHUTDOWN; shutdown_msg);
-        }
+        let shutdown_msg = schema::SHUTDOWN {
+            guest: true,
+            reason: "guest-shutdown".to_string(),
+        };
+        event!(SHUTDOWN; shutdown_msg);
 
         Ok(())
     }
diff --git a/device_model/src/micro_vm/mod.rs b/device_model/src/micro_vm/mod.rs
index 5df63aa..63db895 100644
--- a/device_model/src/micro_vm/mod.rs
+++ b/device_model/src/micro_vm/mod.rs
@@ -61,9 +61,8 @@ use machine_manager::{
         VsockConfig,
     },
     main_loop::MainLoop,
+    qmp::{qmp_schema, QmpChannel, Response},
 };
-#[cfg(feature = "qmp")]
-use machine_manager::{qmp, qmp::qmp_schema as schema, qmp::QmpChannel};
 #[cfg(target_arch = "aarch64")]
 use util::device_tree;
 #[cfg(target_arch = "aarch64")]
@@ -594,7 +593,6 @@ impl LightMachine {
 impl MachineLifecycle for LightMachine {
     fn pause(&self) -> bool {
         if self.notify_lifecycle(KvmVmState::Running, KvmVmState::Paused) {
-            #[cfg(feature = "qmp")]
             event!(STOP);
 
             true
@@ -608,7 +606,6 @@ impl MachineLifecycle for LightMachine {
             return false;
         }
 
-        #[cfg(feature = "qmp")]
         event!(RESUME);
 
         true
@@ -715,34 +712,32 @@ impl MachineAddressInterface for LightMachine {
 }
 
 impl DeviceInterface for LightMachine {
-    #[cfg(feature = "qmp")]
-    fn query_status(&self) -> qmp::Response {
+    fn query_status(&self) -> Response {
         let vmstate = self.vm_state.deref().0.lock().unwrap();
         let qmp_state = match *vmstate {
-            KvmVmState::Running => schema::StatusInfo {
+            KvmVmState::Running => qmp_schema::StatusInfo {
                 singlestep: false,
                 running: true,
-                status: schema::RunState::running,
+                status: qmp_schema::RunState::running,
             },
-            KvmVmState::Paused => schema::StatusInfo {
+            KvmVmState::Paused => qmp_schema::StatusInfo {
                 singlestep: false,
                 running: true,
-                status: schema::RunState::paused,
+                status: qmp_schema::RunState::paused,
             },
             _ => Default::default(),
         };
 
-        qmp::Response::create_response(serde_json::to_value(&qmp_state).unwrap(), None)
+        Response::create_response(serde_json::to_value(&qmp_state).unwrap(), None)
     }
 
-    #[cfg(feature = "qmp")]
-    fn query_cpus(&self) -> qmp::Response {
+    fn query_cpus(&self) -> Response {
         let mut cpu_vec: Vec<serde_json::Value> = Vec::new();
         for cpu_index in 0..self.cpu_topo.max_cpus {
             if self.cpu_topo.get_mask(cpu_index as usize) == 1 {
                 let thread_id = self.cpus.lock().unwrap()[cpu_index as usize].tid();
                 let (socketid, coreid, threadid) = self.cpu_topo.get_topo(cpu_index as usize);
-                let cpu_instance = schema::CpuInstanceProperties {
+                let cpu_instance = qmp_schema::CpuInstanceProperties {
                     node_id: None,
                     socket_id: Some(socketid as isize),
                     core_id: Some(coreid as isize),
@@ -750,7 +745,7 @@ impl DeviceInterface for LightMachine {
                 };
                 #[cfg(target_arch = "x86_64")]
                 {
-                    let cpu_info = schema::CpuInfo::x86 {
+                    let cpu_info = qmp_schema::CpuInfo::x86 {
                         current: true,
                         qom_path: String::from("/machine/unattached/device[")
                             + &cpu_index.to_string()
@@ -759,13 +754,13 @@ impl DeviceInterface for LightMachine {
                         props: Some(cpu_instance),
                         CPU: cpu_index as isize,
                         thread_id: thread_id as isize,
-                        x86: schema::CpuInfoX86 {},
+                        x86: qmp_schema::CpuInfoX86 {},
                     };
                     cpu_vec.push(serde_json::to_value(cpu_info).unwrap());
                 }
                 #[cfg(target_arch = "aarch64")]
                 {
-                    let cpu_info = schema::CpuInfo::Arm {
+                    let cpu_info = qmp_schema::CpuInfo::Arm {
                         current: true,
                         qom_path: String::from("/machine/unattached/device[")
                             + &cpu_index.to_string()
@@ -774,17 +769,16 @@ impl DeviceInterface for LightMachine {
                         props: Some(cpu_instance),
                         CPU: cpu_index as isize,
                         thread_id: thread_id as isize,
-                        arm: schema::CpuInfoArm {},
+                        arm: qmp_schema::CpuInfoArm {},
                     };
                     cpu_vec.push(serde_json::to_value(cpu_info).unwrap());
                 }
             }
         }
-        qmp::Response::create_response(cpu_vec.into(), None)
+        Response::create_response(cpu_vec.into(), None)
     }
 
-    #[cfg(feature = "qmp")]
-    fn query_hotpluggable_cpus(&self) -> qmp::Response {
+    fn query_hotpluggable_cpus(&self) -> Response {
         let mut hotplug_vec: Vec<serde_json::Value> = Vec::new();
         #[cfg(target_arch = "x86_64")]
         let cpu_type = String::from("host-x86-cpu");
@@ -794,13 +788,13 @@ impl DeviceInterface for LightMachine {
         for cpu_index in 0..self.cpu_topo.max_cpus {
             if self.cpu_topo.get_mask(cpu_index as usize) == 0 {
                 let (socketid, coreid, threadid) = self.cpu_topo.get_topo(cpu_index as usize);
-                let cpu_instance = schema::CpuInstanceProperties {
+                let cpu_instance = qmp_schema::CpuInstanceProperties {
                     node_id: None,
                     socket_id: Some(socketid as isize),
                     core_id: Some(coreid as isize),
                     thread_id: Some(threadid as isize),
                 };
-                let hotpluggable_cpu = schema::HotpluggableCPU {
+                let hotpluggable_cpu = qmp_schema::HotpluggableCPU {
                     type_: cpu_type.clone(),
                     vcpus_count: 1,
                     props: cpu_instance,
@@ -809,13 +803,13 @@ impl DeviceInterface for LightMachine {
                 hotplug_vec.push(serde_json::to_value(hotpluggable_cpu).unwrap());
             } else {
                 let (socketid, coreid, threadid) = self.cpu_topo.get_topo(cpu_index as usize);
-                let cpu_instance = schema::CpuInstanceProperties {
+                let cpu_instance = qmp_schema::CpuInstanceProperties {
                     node_id: None,
                     socket_id: Some(socketid as isize),
                     core_id: Some(coreid as isize),
                     thread_id: Some(threadid as isize),
                 };
-                let hotpluggable_cpu = schema::HotpluggableCPU {
+                let hotpluggable_cpu = qmp_schema::HotpluggableCPU {
                     type_: cpu_type.clone(),
                     vcpus_count: 1,
                     props: cpu_instance,
@@ -828,7 +822,7 @@ impl DeviceInterface for LightMachine {
                 hotplug_vec.push(serde_json::to_value(hotpluggable_cpu).unwrap());
             }
         }
-        qmp::Response::create_response(hotplug_vec.into(), None)
+        Response::create_response(hotplug_vec.into(), None)
     }
 
     fn device_add(
@@ -856,14 +850,11 @@ impl DeviceInterface for LightMachine {
     fn device_del(&self, device_id: String) -> bool {
         match self.bus.del_replaceable_device(&device_id) {
             Ok(path) => {
-                #[cfg(feature = "qmp")]
-                {
-                    let block_del_event = schema::DEVICE_DELETED {
-                        device: Some(device_id),
-                        path,
-                    };
-                    event!(DEVICE_DELETED; block_del_event);
-                }
+                let block_del_event = qmp_schema::DEVICE_DELETED {
+                    device: Some(device_id),
+                    path,
+                };
+                event!(DEVICE_DELETED; block_del_event);
 
                 true
             }
@@ -874,8 +865,8 @@ impl DeviceInterface for LightMachine {
     fn blockdev_add(
         &self,
         node_name: String,
-        file: schema::FileOptions,
-        cache: Option<schema::CacheOptions>,
+        file: qmp_schema::FileOptions,
+        cache: Option<qmp_schema::CacheOptions>,
         read_only: Option<bool>,
     ) -> bool {
         let read_only = if let Some(ro) = read_only { ro } else { false };
@@ -920,25 +911,21 @@ impl DeviceInterface for LightMachine {
                 String::from(&fds)
             };
 
-            #[cfg(feature = "qmp")]
-            {
-                if let Some(fd_num) = QmpChannel::get_fd(&netdev_fd) {
-                    config.tap_fd = Some(fd_num);
-                } else {
-                    // try to convert string to RawFd
-                    let fd_num = match netdev_fd.parse::<i32>() {
-                        Ok(fd) => fd,
-                        _ => {
-                            error!(
-                                "Add netdev error: failed to convert {} to RawFd.",
-                                netdev_fd
-                            );
-                            return false;
-                        }
-                    };
-
-                    config.tap_fd = Some(fd_num);
-                }
+            if let Some(fd_num) = QmpChannel::get_fd(&netdev_fd) {
+                config.tap_fd = Some(fd_num);
+            } else {
+                // try to convert string to RawFd
+                let fd_num = match netdev_fd.parse::<i32>() {
+                    Ok(fd) => fd,
+                    _ => {
+                        error!(
+                            "Add netdev error: failed to convert {} to RawFd.",
+                            netdev_fd
+                        );
+                        return false;
+                    }
+                };
+                config.tap_fd = Some(fd_num);
             }
         } else if let Some(if_name) = if_name {
             config.host_dev_name = if_name;
@@ -949,14 +936,14 @@ impl DeviceInterface for LightMachine {
             .is_ok()
     }
 
-    #[cfg(feature = "qmp")]
-    fn getfd(&self, fd_name: String, if_fd: Option<RawFd>) -> qmp::Response {
+    fn getfd(&self, fd_name: String, if_fd: Option<RawFd>) -> Response {
         if let Some(fd) = if_fd {
             QmpChannel::set_fd(fd_name, fd);
-            qmp::Response::create_empty_response()
+            Response::create_empty_response()
         } else {
-            let err_resp = schema::QmpErrorClass::GenericError("Invalid SCM message".to_string());
-            qmp::Response::create_error_response(err_resp, None).unwrap()
+            let err_resp =
+                qmp_schema::QmpErrorClass::GenericError("Invalid SCM message".to_string());
+            Response::create_error_response(err_resp, None).unwrap()
         }
     }
 }
diff --git a/machine_manager/Cargo.toml b/machine_manager/Cargo.toml
index 79fe9de..0f543c6 100644
--- a/machine_manager/Cargo.toml
+++ b/machine_manager/Cargo.toml
@@ -17,6 +17,5 @@ error-chain = "0.12.4"
 vmm-sys-util = "0.6.1"
 
 [features]
-default = ["qmp"]
-qmp = []
+default = []
 
diff --git a/machine_manager/src/lib.rs b/machine_manager/src/lib.rs
index 43c0c00..c7a174c 100644
--- a/machine_manager/src/lib.rs
+++ b/machine_manager/src/lib.rs
@@ -31,7 +31,6 @@ pub mod cmdline;
 pub mod config;
 pub mod machine;
 pub mod main_loop;
-#[cfg(feature = "qmp")]
 pub mod qmp;
 pub mod socket;
 
diff --git a/machine_manager/src/machine.rs b/machine_manager/src/machine.rs
index 2703c8d..2c2a9ee 100644
--- a/machine_manager/src/machine.rs
+++ b/machine_manager/src/machine.rs
@@ -14,11 +14,8 @@ extern crate util;
 
 use std::os::unix::io::RawFd;
 
-#[cfg(feature = "qmp")]
-use crate::qmp::Response;
-
-#[cfg(feature = "qmp")]
 use crate::qmp::qmp_schema::{CacheOptions, FileOptions};
+use crate::qmp::Response;
 
 /// State for KVM VM.
 #[derive(PartialEq, Copy, Clone)]
@@ -127,15 +124,12 @@ pub trait MachineAddressInterface {
 /// Including some query, setting and operation.
 pub trait DeviceInterface {
     /// Query vm running state.
-    #[cfg(feature = "qmp")]
     fn query_status(&self) -> Response;
 
     /// Query each cpu's the topology info.
-    #[cfg(feature = "qmp")]
     fn query_cpus(&self) -> Response;
 
     /// Query each `hotpluggable_cpus`'s topology info and hotplug message.
-    #[cfg(feature = "qmp")]
     fn query_hotpluggable_cpus(&self) -> Response;
 
     /// Add a device with configuration.
@@ -163,7 +157,6 @@ pub trait DeviceInterface {
     fn netdev_add(&self, id: String, if_name: Option<String>, fds: Option<String>) -> bool;
 
     /// Receive a file descriptor via SCM rights and assign it a name.
-    #[cfg(feature = "qmp")]
     fn getfd(&self, fd_name: String, if_fd: Option<RawFd>) -> Response;
 }
 
diff --git a/machine_manager/src/socket.rs b/machine_manager/src/socket.rs
index ed20ff8..b6eeae1 100644
--- a/machine_manager/src/socket.rs
+++ b/machine_manager/src/socket.rs
@@ -22,7 +22,6 @@ use vmm_sys_util::epoll::EventSet;
 
 use super::errors::Result;
 use crate::machine::MachineExternalInterface;
-#[cfg(feature = "qmp")]
 use crate::{
     qmp::qmp_schema::QmpEvent,
     qmp::{QmpChannel, QmpGreeting, Response},
@@ -97,11 +96,8 @@ impl Socket {
             }
         }
 
-        #[cfg(feature = "qmp")]
-        {
-            QmpChannel::bind_writer(SocketRWHandler::new(self.get_stream_fd()));
-            self.send_response(true);
-        }
+        QmpChannel::bind_writer(SocketRWHandler::new(self.get_stream_fd()));
+        self.send_response(true);
     }
 
     /// Accept a new incoming connection unix stream from unix listener.
@@ -154,7 +150,6 @@ impl Socket {
     /// # Arguments
     ///
     /// * `event` - The `QmpEvent` will be sent to client.
-    #[cfg(feature = "qmp")]
     pub fn send_event(&self, event: &QmpEvent) {
         if self.is_connected() {
             let mut handler = self.get_socket_handler();
@@ -169,7 +164,6 @@ impl Socket {
     /// # Arguments
     ///
     /// * `is_greeting` - Whether sending greeting response or not.
-    #[cfg(feature = "qmp")]
     pub fn send_response(&self, is_greeting: bool) {
         if self.is_connected() {
             let mut handler = self.get_socket_handler();
@@ -198,20 +192,9 @@ impl Socket {
                     let socket_mutexed = shared_socket.lock().unwrap();
                     let stream_fd = socket_mutexed.get_stream_fd();
 
-                    #[cfg(feature = "qmp")]
-                    {
-                        let performer = &socket_mutexed.performer.as_ref().unwrap();
-
-                        if let Err(e) = crate::qmp::handle_qmp(stream_fd, performer) {
-                            error!("{}", e);
-                        }
-                    }
-
-                    #[cfg(not(feature = "qmp"))]
-                    {
-                        if let Err(e) = SocketRWHandler::new(stream_fd).read_fd() {
-                            error!("{}", e);
-                        }
+                    let performer = &socket_mutexed.performer.as_ref().unwrap();
+                    if let Err(e) = crate::qmp::handle_qmp(stream_fd, performer) {
+                        error!("{}", e);
                     }
                 }
                 if event & EventSet::HANG_UP == EventSet::HANG_UP {
@@ -219,10 +202,7 @@ impl Socket {
                     let stream_fd = socket_mutexed.get_stream_fd();
                     let listener_fd = socket_mutexed.get_listener_fd();
 
-                    #[cfg(feature = "qmp")]
-                    {
-                        QmpChannel::unbind();
-                    }
+                    QmpChannel::unbind();
 
                     Some(vec![EventNotifier::new(
                         NotifierOperation::Delete,
diff --git a/src/main.rs b/src/main.rs
index dd2b260..e2540c9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -24,7 +24,6 @@ use vmm_sys_util::terminal::Terminal;
 
 use device_model::{register_seccomp, LightMachine};
 use machine_manager::config::VmConfig;
-#[cfg(feature = "qmp")]
 use machine_manager::qmp::QmpChannel;
 use machine_manager::socket::Socket;
 use machine_manager::{
@@ -114,7 +113,6 @@ fn real_main(cmd_args: &arg_parser::ArgMatches) -> Result<()> {
             .chain_err(|| "Failed to set terminal to raw mode.")?;
     }
 
-    #[cfg(feature = "qmp")]
     QmpChannel::object_init();
     MainLoop::object_init();
 
-- 
2.27.0

