diff --git a/Cargo.lock b/Cargo.lock index 28ca8cb0857b..796dcc51910f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -104,6 +104,7 @@ dependencies = [ name = "api_server" version = "0.1.0" dependencies = [ + "displaydoc", "libc", "logger", "micro_http", @@ -382,6 +383,7 @@ name = "cpu-template-helper" version = "1.5.0-dev" dependencies = [ "clap", + "displaydoc", "libc", "serde", "serde_json", @@ -475,6 +477,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f18f717c5c7c2e3483feb64cccebd077245ad6d19007c2db0fd341d38595353c" +[[package]] +name = "displaydoc" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + [[package]] name = "dumbo" version = "0.1.0" @@ -542,6 +555,7 @@ version = "1.5.0-dev" dependencies = [ "api_server", "cargo_toml", + "displaydoc", "event-manager", "libc", "logger", @@ -775,6 +789,7 @@ dependencies = [ name = "logger" version = "0.1.0" dependencies = [ + "displaydoc", "lazy_static", "libc", "log", @@ -820,6 +835,7 @@ dependencies = [ "base64", "bincode", "derive_more", + "displaydoc", "dumbo", "logger", "micro_http", @@ -1003,6 +1019,7 @@ dependencies = [ name = "rebase-snap" version = "1.5.0-dev" dependencies = [ + "displaydoc", "libc", "thiserror", "utils", @@ -1096,6 +1113,7 @@ name = "seccompiler" version = "1.5.0-dev" dependencies = [ "bincode", + "displaydoc", "libc", "serde", "serde_json", @@ -1163,6 +1181,7 @@ name = "snapshot" version = "0.1.0" dependencies = [ "criterion", + "displaydoc", "libc", "thiserror", "versionize", @@ -1175,6 +1194,7 @@ version = "1.5.0" dependencies = [ "clap", "clap-num", + "displaydoc", "libc", "snapshot", "thiserror", @@ -1359,6 +1379,7 @@ name = "utils" version = "0.1.0" dependencies = [ "derive_more", + "displaydoc", "libc", "net_gen", "serde", @@ -1450,6 +1471,7 @@ dependencies = [ "criterion", "derive_more", "device_tree", + "displaydoc", "dumbo", "event-manager", "kvm-bindings", diff --git a/src/api_server/Cargo.toml b/src/api_server/Cargo.toml index cd29a75c58ef..167b5ce6ae6f 100644 --- a/src/api_server/Cargo.toml +++ b/src/api_server/Cargo.toml @@ -14,6 +14,7 @@ serde = { version = "1.0.136", features = ["derive"] } serde_derive = "1.0.136" serde_json = "1.0.78" thiserror = "1.0.32" +displaydoc = "0.2.4" logger = { path = "../logger" } micro_http = { git = "https://github.com/firecracker-microvm/micro-http", rev = "4b18a04" } diff --git a/src/cpu-template-helper/Cargo.toml b/src/cpu-template-helper/Cargo.toml index b964beb37db7..b6a246602140 100644 --- a/src/cpu-template-helper/Cargo.toml +++ b/src/cpu-template-helper/Cargo.toml @@ -13,6 +13,7 @@ bench = false [dependencies] clap = { version = "4.4.4", features = ["derive", "string"] } +displaydoc = "0.2.4" libc = "0.2.148" serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.107" diff --git a/src/cpu-template-helper/src/fingerprint/compare.rs b/src/cpu-template-helper/src/fingerprint/compare.rs index 2140f14e9f24..74c7ffcdba67 100644 --- a/src/cpu-template-helper/src/fingerprint/compare.rs +++ b/src/cpu-template-helper/src/fingerprint/compare.rs @@ -5,13 +5,11 @@ use serde::Serialize; use crate::fingerprint::{Fingerprint, FingerprintField}; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum FingerprintCompareError { - /// Difference detected between source and target. - #[error("Difference detected between source and target:\n{0}")] + /// Difference detected between source and target:\n{0} DiffDetected(String), - /// Failed to serialize/deserialize JSON. - #[error("Failed to serialize/deserialize JSON: {0}")] + /// Failed to serialize/deserialize JSON: {0} Serde(#[from] serde_json::Error), } diff --git a/src/cpu-template-helper/src/fingerprint/dump.rs b/src/cpu-template-helper/src/fingerprint/dump.rs index 6563d1e1a9ac..ae75cbe82ed6 100644 --- a/src/cpu-template-helper/src/fingerprint/dump.rs +++ b/src/cpu-template-helper/src/fingerprint/dump.rs @@ -8,19 +8,15 @@ use vmm::Vmm; use crate::fingerprint::Fingerprint; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum FingerprintDumpError { - /// Failed to dump CPU configuration. - #[error("Failed to dump CPU config: {0}")] + /// Failed to dump CPU config: {0} DumpCpuConfig(#[from] crate::template::dump::DumpError), - /// Failed to read sysfs file. - #[error("Failed to read {0}: {1}")] + /// Failed to read {0}: {1} ReadSysfsFile(String, std::io::Error), - /// Failed to get kernel version. - #[error("Failed to get kernel version: {0}")] + /// Failed to get kernel version: {0} GetKernelVersion(std::io::Error), - /// Shell command failed. - #[error("`{0}` failed: {1}")] + /// `{0}` failed: {1} ShellCommand(String, String), } diff --git a/src/cpu-template-helper/src/main.rs b/src/cpu-template-helper/src/main.rs index d694aecb7fe5..9f4f73e73cdb 100644 --- a/src/cpu-template-helper/src/main.rs +++ b/src/cpu-template-helper/src/main.rs @@ -13,25 +13,25 @@ mod fingerprint; mod template; mod utils; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum HelperError { - #[error("Failed to operate file: {0}")] + /// Failed to operate file: {0} FileIo(#[from] std::io::Error), - #[error("{0}")] + /// {0} FingerprintCompare(#[from] fingerprint::compare::FingerprintCompareError), - #[error("{0}")] + /// {0} FingerprintDump(#[from] fingerprint::dump::FingerprintDumpError), - #[error("CPU template is not specified: {0}")] + /// CPU template is not specified: {0} NoCpuTemplate(#[from] GetCpuTemplateError), - #[error("Failed to serialize/deserialize JSON file: {0}")] + /// Failed to serialize/deserialize JSON file: {0} Serde(#[from] serde_json::Error), - #[error("{0}")] + /// {0} Utils(#[from] UtilsError), - #[error("{0}")] + /// {0} TemplateDump(#[from] template::dump::DumpError), - #[error("{0}")] + /// {0} TemplateStrip(#[from] template::strip::StripError), - #[error("{0}")] + /// {0} TemplateVerify(#[from] template::verify::VerifyError), } diff --git a/src/cpu-template-helper/src/template/dump/mod.rs b/src/cpu-template-helper/src/template/dump/mod.rs index 882d2a933d68..6697f39e01d1 100644 --- a/src/cpu-template-helper/src/template/dump/mod.rs +++ b/src/cpu-template-helper/src/template/dump/mod.rs @@ -16,10 +16,9 @@ use crate::template::dump::aarch64::config_to_template; #[cfg(target_arch = "x86_64")] use crate::template::dump::x86_64::config_to_template; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum DumpError { - /// Failed to dump CPU configuration. - #[error("Failed to dump CPU config: {0}")] + /// Failed to dump CPU config: {0} DumpCpuConfig(#[from] DumpCpuConfigError), } diff --git a/src/cpu-template-helper/src/template/strip/mod.rs b/src/cpu-template-helper/src/template/strip/mod.rs index 0b128f1a1a74..1777d1d571b4 100644 --- a/src/cpu-template-helper/src/template/strip/mod.rs +++ b/src/cpu-template-helper/src/template/strip/mod.rs @@ -18,10 +18,9 @@ mod x86_64; #[cfg(target_arch = "x86_64")] pub use x86_64::strip; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum StripError { /// The number of inputs should be two or more. - #[error("The number of inputs should be two or more.")] NumberOfInputs, } diff --git a/src/cpu-template-helper/src/template/verify/mod.rs b/src/cpu-template-helper/src/template/verify/mod.rs index 7ae5b9e910e9..8c8c279f9e66 100644 --- a/src/cpu-template-helper/src/template/verify/mod.rs +++ b/src/cpu-template-helper/src/template/verify/mod.rs @@ -18,11 +18,12 @@ mod x86_64; pub use x86_64::verify; #[rustfmt::skip] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum VerifyError { - #[error("{0} not found in CPU configuration.")] + /// {0} not found in CPU configuration. KeyNotFound(String), - #[error("Value for {0} mismatched.\n{1}")] + #[rustfmt::skip] + #[doc = "Value for {0} mismatched.\n{1}"] ValueMismatched(String, String), } diff --git a/src/cpu-template-helper/src/utils/mod.rs b/src/cpu-template-helper/src/utils/mod.rs index dbde959f1153..08a8000a99e3 100644 --- a/src/cpu-template-helper/src/utils/mod.rs +++ b/src/cpu-template-helper/src/utils/mod.rs @@ -58,13 +58,11 @@ impl DiffString for V { } } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum UtilsError { - /// Failed to create VmResources. - #[error("Failed to create VmResources: {0}")] + /// Failed to create VmResources: {0} CreateVmResources(vmm::resources::ResourcesError), - /// Failed to build microVM. - #[error("Failed to build microVM: {0}")] + /// Failed to build microVM: {0} BuildMicroVm(#[from] StartMicrovmError), } diff --git a/src/firecracker/Cargo.toml b/src/firecracker/Cargo.toml index 4eb1baf34740..cb07a440b43f 100644 --- a/src/firecracker/Cargo.toml +++ b/src/firecracker/Cargo.toml @@ -13,6 +13,7 @@ name = "firecracker" bench = false [dependencies] +displaydoc = "0.2.4" event-manager = "0.3.0" libc = "0.2.148" serde_json = "1.0.107" diff --git a/src/firecracker/src/api_server_adapter.rs b/src/firecracker/src/api_server_adapter.rs index f91d06cb0416..5d9106a1712b 100644 --- a/src/firecracker/src/api_server_adapter.rs +++ b/src/firecracker/src/api_server_adapter.rs @@ -22,17 +22,17 @@ use vmm::rpc_interface::{ use vmm::vmm_config::instance_info::InstanceInfo; use vmm::{EventManager, FcExitCode, Vmm}; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum ApiServerError { - #[error("MicroVMStopped without an error: {0:?}")] + /// MicroVMStopped without an error: {0:?} MicroVMStoppedWithoutError(FcExitCode), - #[error("MicroVMStopped with an error: {0:?}")] + /// MicroVMStopped with an error: {0:?} MicroVMStoppedWithError(FcExitCode), - #[error("Failed to open the API socket at: {0}. Check that it is not already used.")] + /// Failed to open the API socket at: {0}. Check that it is not already used. FailedToBindSocket(String), - #[error("Failed to bind and run the HTTP server: {0}")] + /// Failed to bind and run the HTTP server: {0} FailedToBindAndRunHttpServer(ServerError), - #[error("Failed to build MicroVM from Json: {0}")] + /// Failed to build MicroVM from Json: {0} BuildFromJson(crate::BuildFromJsonError), } diff --git a/src/firecracker/src/main.rs b/src/firecracker/src/main.rs index 31f05517fbb3..cbeab38a1994 100644 --- a/src/firecracker/src/main.rs +++ b/src/firecracker/src/main.rs @@ -39,37 +39,37 @@ const DEFAULT_INSTANCE_ID: &str = "anonymous-instance"; const FIRECRACKER_VERSION: &str = env!("FIRECRACKER_VERSION"); const MMDS_CONTENT_ARG: &str = "metadata"; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum MainError { - #[error("Failed to register signal handlers: {0}")] + /// Failed to register signal handlers: {0} RegisterSignalHandlers(#[source] utils::errno::Error), - #[error("Arguments parsing error: {0} \n\nFor more information try --help.")] + /// Arguments parsing error: {0} \n\nFor more information try --help. ParseArguments(#[from] utils::arg_parser::Error), - #[error("When printing Snapshot Data format: {0}")] + /// When printing Snapshot Data format: {0} PrintSnapshotDataFormat(#[from] SnapshotVersionError), - #[error("Invalid value for logger level: {0}.Possible values: [Error, Warning, Info, Debug]")] + /// Invalid value for logger level: {0}.Possible values: [Error, Warning, Info, Debug] InvalidLogLevel(LoggerConfigError), - #[error("Could not initialize logger: {0}")] + /// Could not initialize logger: {0} LoggerInitialization(LoggerConfigError), - #[error("Could not initialize metrics: {0:?}")] + /// Could not initialize metrics: {0:?} MetricsInitialization(MetricsConfigError), - #[error("Seccomp error: {0}")] + /// Seccomp error: {0} SeccompFilter(FilterError), - #[error("Failed to resize fd table: {0}")] + /// Failed to resize fd table: {0} ResizeFdtable(ResizeFdTableError), - #[error("RunWithApiError error: {0}")] + /// RunWithApiError error: {0} RunWithApi(ApiServerError), - #[error("RunWithoutApiError error: {0}")] + /// RunWithoutApiError error: {0} RunWithoutApiError(RunWithoutApiError), } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum ResizeFdTableError { - #[error("Failed to get RLIMIT_NOFILE")] + /// Failed to get RLIMIT_NOFILE GetRlimit, - #[error("Failed to call dup2 to resize fdtable")] + /// Failed to call dup2 to resize fdtable Dup2(io::Error), - #[error("Failed to close dup2'd file descriptor")] + /// Failed to close dup2'd file descriptor Close(io::Error), } @@ -524,13 +524,13 @@ fn print_supported_snapshot_versions() { } } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum SnapshotVersionError { - #[error("Unable to open snapshot state file: {0}")] + /// Unable to open snapshot state file: {0} OpenSnapshot(io::Error), - #[error("Invalid data format version of snapshot file: {0}")] + /// Invalid data format version of snapshot file: {0} SnapshotVersion(SnapshotError), - #[error("Cannot translate snapshot data version {0} to Firecracker microVM version")] + /// Cannot translate snapshot data version {0} to Firecracker microVM version FirecrackerVersion(u16), } @@ -551,11 +551,11 @@ fn print_snapshot_data_format(snapshot_path: &str) -> Result<(), SnapshotVersion Ok(()) } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum BuildFromJsonError { - #[error("Configuration for VMM from one single json failed: {0}")] + /// Configuration for VMM from one single json failed: {0} ParseFromJson(vmm::resources::ResourcesError), - #[error("Could not Start MicroVM from one single json: {0}")] + /// Could not Start MicroVM from one single json: {0} StartMicroVM(StartMicrovmError), } @@ -586,11 +586,11 @@ fn build_microvm_from_json( Ok((vm_resources, vmm)) } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum RunWithoutApiError { - #[error("MicroVMStopped without an error: {0:?}")] + /// MicroVMStopped without an error: {0:?} Shutdown(FcExitCode), - #[error("Failed to build MicroVM from Json: {0}")] + /// Failed to build MicroVM from Json: {0} BuildMicroVMFromJson(BuildFromJsonError), } diff --git a/src/firecracker/src/seccomp.rs b/src/firecracker/src/seccomp.rs index 735632bfc9e0..a4af005ba817 100644 --- a/src/firecracker/src/seccomp.rs +++ b/src/firecracker/src/seccomp.rs @@ -17,19 +17,15 @@ const THREAD_CATEGORIES: [&str; 3] = ["vmm", "api", "vcpu"]; const DESERIALIZATION_BYTES_LIMIT: Option = Some(100_000); /// Error retrieving seccomp filters. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum FilterError { - /// Filter deserialitaion error. - #[error("Filter deserialization failed: {0}")] + /// Filter deserialization failed: {0} Deserialization(DeserializationError), - /// Invalid thread categories. - #[error("Invalid thread categories: {0}")] + /// Invalid thread categories: {0} ThreadCategories(String), - /// Missing Thread Category. - #[error("Missing thread category: {0}")] + /// Missing thread category: {0} MissingThreadCategory(String), - /// File open error. - #[error("Filter file open error: {0}")] + /// Filter file open error: {0} FileOpen(std::io::Error), } diff --git a/src/logger/Cargo.toml b/src/logger/Cargo.toml index 908a508b9313..0c136e706448 100644 --- a/src/logger/Cargo.toml +++ b/src/logger/Cargo.toml @@ -15,5 +15,6 @@ log = { version = "0.4.14", features = ["std"] } serde = { version = "1.0.136", features = ["derive", "rc"] } serde_json = "1.0.78" thiserror = "1.0.32" +displaydoc = "0.2.4" vm-superio = "0.7.0" utils = { path = "../utils" } diff --git a/src/logger/src/init.rs b/src/logger/src/init.rs index 2207fd93683c..d27906bed40e 100644 --- a/src/logger/src/init.rs +++ b/src/logger/src/init.rs @@ -4,11 +4,11 @@ use std::sync::atomic::{AtomicUsize, Ordering}; /// Errors associated with the `Init` struct. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum Error { - #[error("The component is already initialized.")] + /// The component is already initialized. AlreadyInitialized, - #[error("The component is initializing. Can't perform the requested action right now.")] + /// The component is initializing. Can't perform the requested action right now. InitializationInProgress, } diff --git a/src/logger/src/logger.rs b/src/logger/src/logger.rs index df82ea545c9e..bc3145e9dcd8 100644 --- a/src/logger/src/logger.rs +++ b/src/logger/src/logger.rs @@ -402,10 +402,9 @@ impl Logger { } /// Describes the errors which may occur while handling logging scenarios. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum LoggerError { - /// Initialization Error. - #[error("Logger initialization failure: {0}")] + /// Logger initialization failure: {0} Init(init::Error), } diff --git a/src/logger/src/metrics.rs b/src/logger/src/metrics.rs index 0a3884935d5f..294115991fe9 100644 --- a/src/logger/src/metrics.rs +++ b/src/logger/src/metrics.rs @@ -178,19 +178,15 @@ impl Deref for Metrics { } /// Describes the errors which may occur while handling metrics scenarios. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum MetricsError { - /// First attempt at initialization failed. - #[error("{0}")] + /// {0} NeverInitialized(String), - /// The metrics system does not allow reinitialization. - #[error("Reinitialization of metrics not allowed.")] + /// Reinitialization of metrics not allowed. AlreadyInitialized, - /// Error in the serialization of metrics instance. - #[error("{0}")] + /// {0} Serde(String), - /// Writing the specified buffer failed. - #[error("Failed to write metrics: {0}")] + /// Failed to write metrics: {0} Write(std::io::Error), } diff --git a/src/mmds/Cargo.toml b/src/mmds/Cargo.toml index 1ba824823566..00ec9ff93249 100644 --- a/src/mmds/Cargo.toml +++ b/src/mmds/Cargo.toml @@ -16,6 +16,7 @@ derive_more = { version = "0.99.17", default-features = false, features = ["from serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.78" thiserror = "1.0.32" +displaydoc = "0.2.4" versionize = "0.1.10" versionize_derive = "0.1.5" diff --git a/src/mmds/src/data_store.rs b/src/mmds/src/data_store.rs index bc94c0144460..60e6bb074384 100644 --- a/src/mmds/src/data_store.rs +++ b/src/mmds/src/data_store.rs @@ -43,17 +43,17 @@ pub enum OutputFormat { Imds, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum Error { - #[error("The MMDS patch request doesn't fit.")] + /// The MMDS patch request doesn't fit. DataStoreLimitExceeded, - #[error("The MMDS resource does not exist.")] + /// The MMDS resource does not exist. NotFound, - #[error("The MMDS data store is not initialized.")] + /// The MMDS data store is not initialized. NotInitialized, - #[error("Token Authority error: {0}")] + /// Token Authority error: {0} TokenAuthority(#[from] TokenError), - #[error("Cannot retrieve value. The value has an unsupported type.")] + /// Cannot retrieve value. The value has an unsupported type. UnsupportedValueType, } diff --git a/src/mmds/src/lib.rs b/src/mmds/src/lib.rs index 3c7b9e3f5c93..b64c3e8bf37f 100644 --- a/src/mmds/src/lib.rs +++ b/src/mmds/src/lib.rs @@ -19,22 +19,20 @@ use crate::data_store::{Error as MmdsError, Mmds, MmdsVersion, OutputFormat}; use crate::token::PATH_TO_TOKEN; use crate::token_headers::REJECTED_HEADER; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum Error { - #[error("MMDS token not valid.")] + /// MMDS token not valid. InvalidToken, - #[error("Invalid URI.")] + /// Invalid URI. InvalidURI, - #[error("Not allowed HTTP method.")] + /// Not allowed HTTP method. MethodNotAllowed, - #[error("No MMDS token provided. Use `X-metadata-token` header to specify the session token.")] + /// No MMDS token provided. Use `X-metadata-token` header to specify the session token. NoTokenProvided, - #[error( - "Token time to live value not found. Use `X-metadata-token-ttl-seconds` header to specify \ - the token's lifetime." - )] + #[rustfmt::skip] + #[doc = "Token time to live value not found. Use `X-metadata-token-ttl-seconds` header to specify the token's lifetime."] NoTtlProvided, - #[error("Resource not found: {0}.")] + /// Resource not found: {0}. ResourceNotFound(String), } diff --git a/src/mmds/src/token.rs b/src/mmds/src/token.rs index e8d0ca3e6b2c..619bf46a2e06 100644 --- a/src/mmds/src/token.rs +++ b/src/mmds/src/token.rs @@ -44,30 +44,20 @@ const TOKEN_LENGTH_LIMIT: usize = 70; /// too much memory when deserializing tokens. const DESERIALIZATION_BYTES_LIMIT: usize = std::mem::size_of::(); -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum Error { - #[error("Failed to extract entropy from /dev/urandom entropy pool: {0}.")] - /// Failed to extract entropy from pool. + /// Failed to extract entropy from /dev/urandom entropy pool: {0}. EntropyPool(#[from] io::Error), - /// Failed to extract expiry from token sequence. - #[error("Failed to extract expiry value from token.")] + /// Failed to extract expiry value from token. ExpiryExtraction, - /// Token authority has invalid state. - #[error("Invalid token authority state.")] + /// Invalid token authority state. InvalidState, - /// Time to live value for token is invalid. - #[error( - "Invalid time to live value provided for token: {0}. Please provide a value between {} \ - and {}.", - MIN_TOKEN_TTL_SECONDS, - MAX_TOKEN_TTL_SECONDS - )] + #[rustfmt::skip] + #[doc= "Invalid time to live value provided for token: {0}. Please provide a value between {MIN_TOKEN_TTL_SECONDS:} and {MAX_TOKEN_TTL_SECONDS:}."] InvalidTtlValue(u32), - /// Token serialization failed. - #[error("Bincode serialization failed: {0}.")] + /// Bincode serialization failed: {0}. Serialization(#[from] BincodeError), /// Failed to encrypt token. - #[error("Failed to encrypt token.")] TokenEncryption, } diff --git a/src/rebase-snap/Cargo.toml b/src/rebase-snap/Cargo.toml index 1b310dab31e0..74ea0265adb7 100644 --- a/src/rebase-snap/Cargo.toml +++ b/src/rebase-snap/Cargo.toml @@ -11,6 +11,7 @@ name = "rebase-snap" bench = false [dependencies] +displaydoc = "0.2.4" libc = "0.2.148" thiserror = "1.0.48" diff --git a/src/rebase-snap/src/main.rs b/src/rebase-snap/src/main.rs index 6e631abcc8b6..5bd11e4b3ca0 100644 --- a/src/rebase-snap/src/main.rs +++ b/src/rebase-snap/src/main.rs @@ -13,31 +13,31 @@ const REBASE_SNAP_VERSION: &str = env!("FIRECRACKER_VERSION"); const BASE_FILE: &str = "base-file"; const DIFF_FILE: &str = "diff-file"; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum FileError { - #[error("Invalid base file: {0:?}")] + /// Invalid base file: {0:?} InvalidBaseFile(std::io::Error), - #[error("Invalid diff file: {0:?}")] + /// Invalid diff file: {0:?} InvalidDiffFile(std::io::Error), - #[error("Failed to seek data: {0:?}")] + /// Failed to seek data: {0:?} SeekData(std::io::Error), - #[error("Failed to seek hole: {0:?}")] + /// Failed to seek hole: {0:?} SeekHole(std::io::Error), - #[error("Failed to seek: {0:?}")] + /// Failed to seek: {0:?} Seek(std::io::Error), - #[error("Failed to send the file: {0:?}")] + /// Failed to send the file: {0:?} SendFile(std::io::Error), - #[error("Failed to get metadata: {0:?}")] + /// Failed to get metadata: {0:?} Metadata(std::io::Error), } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum RebaseSnapError { - #[error("Arguments parsing error: {0} \n\nFor more information try --help.")] + /// Arguments parsing error: {0} \n\nFor more information try --help. ArgParse(ArgError), - #[error("Error parsing the cmd line args: {0}")] + /// Error parsing the cmd line args: {0} SnapFile(FileError), - #[error("Error merging the files: {0}")] + /// Error merging the files: {0} RebaseFiles(FileError), } diff --git a/src/seccompiler/Cargo.toml b/src/seccompiler/Cargo.toml index c5b96cfb1df6..be968352cf56 100644 --- a/src/seccompiler/Cargo.toml +++ b/src/seccompiler/Cargo.toml @@ -18,6 +18,7 @@ bench = false [dependencies] bincode = "1.2.1" +displaydoc = "0.2.4" libc = "0.2.148" serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.107" diff --git a/src/seccompiler/src/backend.rs b/src/seccompiler/src/backend.rs index e2cd3b75b065..c5ea255236b6 100644 --- a/src/seccompiler/src/backend.rs +++ b/src/seccompiler/src/backend.rs @@ -95,22 +95,17 @@ impl<'de> Deserialize<'de> for Comment { } /// Seccomp filter errors. -#[derive(Debug, PartialEq, thiserror::Error)] +#[derive(Debug, PartialEq, thiserror::Error, displaydoc::Display)] pub(crate) enum FilterError { - /// Attempting to add an empty vector of rules to the rule chain of a syscall. - #[error("The seccomp rules vector is empty.")] + /// The seccomp rules vector is empty. EmptyRulesVector, - /// Filter exceeds the maximum number of instructions that a BPF program can have. - #[error("The seccomp filter contains too many BPF instructions.")] + /// The seccomp filter contains too many BPF instructions. FilterTooLarge, - /// Argument number that exceeds the maximum value. - #[error("The seccomp rule contains an invalid argument number.")] + /// The seccomp rule contains an invalid argument number. InvalidArgumentNumber, - /// Error related to the target arch. - #[error("{0:?}")] + /// {0:?} Arch(TargetArchError), - /// Conflicting rules in filter. - #[error("Syscall {0} has conflicting rules.")] + /// Syscall {0} has conflicting rules. ConflictingRules(i64), } @@ -125,10 +120,9 @@ pub(crate) enum TargetArch { } /// Errors related to target arch. -#[derive(Debug, PartialEq, thiserror::Error)] +#[derive(Debug, PartialEq, thiserror::Error, displaydoc::Display)] pub(crate) enum TargetArchError { - /// Invalid string. - #[error("Invalid target arch string: {0}")] + /// Invalid target arch string: {0} InvalidString(String), } diff --git a/src/seccompiler/src/compiler.rs b/src/seccompiler/src/compiler.rs index c4f0682620b2..58c9b85b40a8 100644 --- a/src/seccompiler/src/compiler.rs +++ b/src/seccompiler/src/compiler.rs @@ -32,16 +32,13 @@ use crate::common::BpfProgram; use crate::syscall_table::SyscallTable; /// Errors compiling Filters into BPF. -#[derive(Debug, PartialEq, thiserror::Error)] +#[derive(Debug, PartialEq, thiserror::Error, displaydoc::Display)] pub(crate) enum CompilationError { - /// Filter and default actions are equal. - #[error("`filter_action` and `default_action` are equal.")] + /// `filter_action` and `default_action` are equal. IdenticalActions, - /// Error from the SeccompFilter. - #[error("{0}")] + /// {0} Filter(#[from] FilterError), - /// Invalid syscall name for the given arch. - #[error("Invalid syscall name: {0} for given arch: {1:?}.")] + /// Invalid syscall name: {0} for given arch: {1:?}. SyscallName(String, TargetArch), } diff --git a/src/seccompiler/src/lib.rs b/src/seccompiler/src/lib.rs index dcaf0dec373c..d2dfb310ac3d 100644 --- a/src/seccompiler/src/lib.rs +++ b/src/seccompiler/src/lib.rs @@ -33,21 +33,18 @@ struct sock_fprog { pub type BpfProgramRef<'a> = &'a [sock_filter]; /// Binary filter deserialization errors. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum DeserializationError { - /// Error when doing bincode deserialization. - #[error("Bincode deserialization failed: {0}")] + /// Bincode deserialization failed: {0} Bincode(BincodeError), } /// Filter installation errors. -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum InstallationError { - /// Filter exceeds the maximum number of instructions that a BPF program can have. - #[error("Filter length exceeds the maximum size of {BPF_MAX_LEN} instructions ")] + /// Filter length exceeds the maximum size of {BPF_MAX_LEN:} instructions FilterTooLarge, - /// Error returned by `prctl`. - #[error("`prctl` syscall failed with error code: {0}")] + /// prctl` syscall failed with error code: {0} Prctl(i32), } diff --git a/src/seccompiler/src/seccompiler_bin.rs b/src/seccompiler/src/seccompiler_bin.rs index 9908a090927e..76a0ceed1521 100644 --- a/src/seccompiler/src/seccompiler_bin.rs +++ b/src/seccompiler/src/seccompiler_bin.rs @@ -159,13 +159,13 @@ fn compile(args: &Arguments) -> Result<(), SeccompError> { Ok(()) } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum SeccompilerError { - #[error("Argument Parsing Error: {0}")] + /// Argument Parsing Error: {0} ArgParsing(ArgParserError), - #[error("{0} \n\nFor more information try --help.")] + /// {0} \n\nFor more information try --help. InvalidArgumentValue(SeccompError), - #[error("{0}")] + /// {0} Error(SeccompError), } diff --git a/src/snapshot-editor/Cargo.toml b/src/snapshot-editor/Cargo.toml index de51ac46527b..3df26d88aaa6 100644 --- a/src/snapshot-editor/Cargo.toml +++ b/src/snapshot-editor/Cargo.toml @@ -13,6 +13,7 @@ bench = false [dependencies] clap = { version = "4.4.4", features = ["derive", "string"] } clap-num = "1.0.2" +displaydoc = "0.2.4" libc = "0.2.148" snapshot = { path = "../snapshot" } thiserror = "1.0.48" diff --git a/src/snapshot-editor/src/edit_memory.rs b/src/snapshot-editor/src/edit_memory.rs index c4675aa5feca..642ce31bcbba 100644 --- a/src/snapshot-editor/src/edit_memory.rs +++ b/src/snapshot-editor/src/edit_memory.rs @@ -9,21 +9,21 @@ use std::path::PathBuf; use clap::Subcommand; use fc_utils::seek_hole::SeekHole; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum EditMemoryError { - #[error("Could not open memory file: {0}")] + /// Could not open memory file: {0} OpenMemoryFile(std::io::Error), - #[error("Could not open diff file: {0}")] + /// Could not open diff file: {0} OpenDiffFile(std::io::Error), - #[error("Failed to seek data in diff file: {0}")] + /// Failed to seek data in diff file: {0} SeekDataDiff(std::io::Error), - #[error("Failed to seek hole in diff file: {0}")] + /// Failed to seek hole in diff file: {0} SeekHoleDiff(std::io::Error), - #[error("Failed to get metadata for diff file: {0}")] + /// Failed to get metadata for diff file: {0} MetadataDiff(std::io::Error), - #[error("Failed to seek in memory file: {0}")] + /// Failed to seek in memory file: {0} SeekMemory(std::io::Error), - #[error("Failed to send the file: {0:?}")] + /// Failed to send the file: {0:?} SendFile(std::io::Error), } diff --git a/src/snapshot-editor/src/edit_vmstate.rs b/src/snapshot-editor/src/edit_vmstate.rs index 43170dab32a9..1d35cc197604 100644 --- a/src/snapshot-editor/src/edit_vmstate.rs +++ b/src/snapshot-editor/src/edit_vmstate.rs @@ -10,9 +10,9 @@ use vmm::persist::MicrovmState; use crate::utils::{open_vmstate, save_vmstate, UtilsError}; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum EditVmStateError { - #[error("{0}")] + /// {0} Utils(#[from] UtilsError), } diff --git a/src/snapshot-editor/src/info.rs b/src/snapshot-editor/src/info.rs index 299f9a0da673..a39adbc335ea 100644 --- a/src/snapshot-editor/src/info.rs +++ b/src/snapshot-editor/src/info.rs @@ -9,11 +9,11 @@ use vmm::version_map::FC_VERSION_TO_SNAP_VERSION; use crate::utils::*; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum InfoVmStateError { - #[error("Cannot translate snapshot data version {0} to Firecracker microVM version")] + /// Cannot translate snapshot data version {0} to Firecracker microVM version InvalidVersion(u16), - #[error("{0}")] + /// {0} Utils(#[from] UtilsError), } diff --git a/src/snapshot-editor/src/main.rs b/src/snapshot-editor/src/main.rs index de508c4ced0a..d4ee1321b79d 100644 --- a/src/snapshot-editor/src/main.rs +++ b/src/snapshot-editor/src/main.rs @@ -14,14 +14,14 @@ use edit_memory::{edit_memory_command, EditMemoryError, EditMemorySubCommand}; use edit_vmstate::{edit_vmstate_command, EditVmStateError, EditVmStateSubCommand}; use info::{info_vmstate_command, InfoVmStateError, InfoVmStateSubCommand}; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] enum SnapEditorError { - #[error("Error during editing memory file: {0}")] + /// Error during editing memory file: {0} EditMemory(#[from] EditMemoryError), #[cfg(target_arch = "aarch64")] - #[error("Error during editing vmstate file: {0}")] + /// Error during editing vmstate file: {0} EditVmState(#[from] EditVmStateError), - #[error("Error during getting info from a vmstate file: {0}")] + /// Error during getting info from a vmstate file: {0} InfoVmState(#[from] InfoVmStateError), } diff --git a/src/snapshot-editor/src/utils.rs b/src/snapshot-editor/src/utils.rs index 864fec3777dd..e0b285d28a9d 100644 --- a/src/snapshot-editor/src/utils.rs +++ b/src/snapshot-editor/src/utils.rs @@ -10,17 +10,17 @@ use vmm::version_map::VERSION_MAP; // Some errors are only used in aarch64 code #[allow(unused)] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum UtilsError { - #[error("Can not open snapshot file: {0}")] + /// Can not open snapshot file: {0} VmStateFileOpen(std::io::Error), - #[error("Can not retrieve metadata for snapshot file: {0}")] + /// Can not retrieve metadata for snapshot file: {0} VmStateFileMeta(std::io::Error), - #[error("Can not load snapshot: {0}")] + /// Can not load snapshot: {0} VmStateLoad(snapshot::Error), - #[error("Can not open output file: {0}")] + /// Can not open output file: {0} OutputFileOpen(std::io::Error), - #[error("Can not save snapshot: {0}")] + /// Can not save snapshot: {0} VmStateSave(snapshot::Error), } diff --git a/src/snapshot/Cargo.toml b/src/snapshot/Cargo.toml index 058efa139d8f..ffd73d5a280a 100644 --- a/src/snapshot/Cargo.toml +++ b/src/snapshot/Cargo.toml @@ -14,6 +14,7 @@ libc = "0.2.117" versionize = "0.1.10" versionize_derive = "0.1.5" thiserror = "1.0.32" +displaydoc = "0.2.4" [dev-dependencies] criterion = { version = "0.5.0", default-features = false } diff --git a/src/snapshot/src/lib.rs b/src/snapshot/src/lib.rs index b4990fa3ec34..8b394c4a4acd 100644 --- a/src/snapshot/src/lib.rs +++ b/src/snapshot/src/lib.rs @@ -44,28 +44,21 @@ const BASE_MAGIC_ID: u64 = 0x0710_1984_8664_0000u64; const BASE_MAGIC_ID: u64 = 0x0710_1984_AAAA_0000u64; /// Error definitions for the Snapshot API. -#[derive(Debug, thiserror::Error, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq)] pub enum Error { - /// CRC64 validation failed. - #[error("CRC64 validation failed: {0}")] + /// CRC64 validation failed: {0} Crc64(u64), - /// Invalid data version. - #[error("Invalid data version: {0}")] + /// Invalid data version: {0} InvalidDataVersion(u16), - /// Invalid format version. - #[error("Invalid format version: {0}")] + /// Invalid format version: {0} InvalidFormatVersion(u16), - /// Magic value does not match arch. - #[error("Magic value does not match arch: {0}")] + /// Magic value does not match arch: {0} InvalidMagic(u64), /// Snapshot file is smaller than CRC length. - #[error("Snapshot file is smaller than CRC length.")] InvalidSnapshotSize, - /// An IO error occurred. - #[error("An IO error occurred: {0}")] + /// An IO error occurred: {0} Io(i32), - /// A versioned serialization/deserialization error occurred. - #[error("A versioned serialization/deserialization error occurred: {0}")] + /// A versioned serialization/deserialization error occurred: {0} Versionize(versionize::VersionizeError), } diff --git a/src/utils/Cargo.toml b/src/utils/Cargo.toml index 024389ac5b9e..c00d850b37ea 100644 --- a/src/utils/Cargo.toml +++ b/src/utils/Cargo.toml @@ -13,6 +13,7 @@ derive_more = { version = "0.99.17", default-features = false, features = ["from libc = "0.2.147" serde = { version = "1.0.165", features = ["derive"] } thiserror = "1.0.32" +displaydoc = "0.2.4" versionize = "0.1.10" versionize_derive = "0.1.5" vmm-sys-util = "0.11.0" diff --git a/src/utils/src/arg_parser.rs b/src/utils/src/arg_parser.rs index 3a736e048c62..a414c6d390b5 100644 --- a/src/utils/src/arg_parser.rs +++ b/src/utils/src/arg_parser.rs @@ -12,22 +12,17 @@ const HELP_ARG: &str = "--help"; const VERSION_ARG: &str = "--version"; /// Errors associated with parsing and validating arguments. -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum Error { - /// The argument B cannot be used together with argument A. - #[error("Argument '{1}' cannot be used together with argument '{0}'.")] + /// Argument '{1}' cannot be used together with argument '{0}'. ForbiddenArgument(String, String), - /// The required argument was not provided. - #[error("Argument '{0}' required, but not found.")] + /// Argument '{0}' required, but not found. MissingArgument(String), - /// A value for the argument was not provided. - #[error("The argument '{0}' requires a value, but none was supplied.")] + /// The argument '{0}' requires a value, but none was supplied. MissingValue(String), - /// The provided argument was not expected. - #[error("Found argument '{0}' which wasn't expected, or isn't valid in this context.")] + /// Found argument '{0}' which wasn't expected, or isn't valid in this context. UnexpectedArgument(String), - /// The argument was provided more than once. - #[error("The argument '{0}' was provided more than once.")] + /// The argument '{0}' was provided more than once. DuplicateArgument(String), } diff --git a/src/utils/src/validators.rs b/src/utils/src/validators.rs index 3f956b66e933..3befd5d770b1 100644 --- a/src/utils/src/validators.rs +++ b/src/utils/src/validators.rs @@ -6,11 +6,11 @@ const MAX_INSTANCE_ID_LEN: usize = 64; const MIN_INSTANCE_ID_LEN: usize = 1; -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum Error { - #[error("Invalid char ({0}) at position {1}")] + /// Invalid char ({0}) at position {1} InvalidChar(char, usize), // (char, position) - #[error("Invalid len ({0}); the length must be between {1} and {2}")] + /// Invalid len ({0}); the length must be between {1} and {2} InvalidLen(usize, usize, usize), // (length, min, max) } diff --git a/src/vmm/Cargo.toml b/src/vmm/Cargo.toml index 94a4a59c59c2..f6184735e013 100644 --- a/src/vmm/Cargo.toml +++ b/src/vmm/Cargo.toml @@ -23,6 +23,7 @@ semver = { version = "1.0.17", features = ["serde"] } serde_json = "1.0.78" timerfd = "1.5.0" thiserror = "1.0.32" +displaydoc = "0.2.4" userfaultfd = "0.6.0" versionize = "0.1.10" versionize_derive = "0.1.5" diff --git a/src/vmm/src/arch/aarch64/cache_info.rs b/src/vmm/src/arch/aarch64/cache_info.rs index 8d61b63a8d3f..2b4e2f5f82d2 100644 --- a/src/vmm/src/arch/aarch64/cache_info.rs +++ b/src/vmm/src/arch/aarch64/cache_info.rs @@ -9,17 +9,17 @@ use log::warn; // Based on https://elixir.free-electrons.com/linux/v4.9.62/source/arch/arm64/kernel/cacheinfo.c#L29. const MAX_CACHE_LEVEL: u8 = 7; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub(crate) enum CacheInfoError { - #[error("Failed to read cache information: {0}")] + /// Failed to read cache information: {0} FailedToReadCacheInfo(#[from] io::Error), - #[error("Invalid cache configuration found for {0}: {1}")] + /// Invalid cache configuration found for {0}: {1} InvalidCacheAttr(String, String), - #[error("Cannot read cache level.")] + /// Cannot read cache level. MissingCacheLevel, - #[error("Cannot read cache type.")] + /// Cannot read cache type. MissingCacheType, - #[error("{0}")] + /// {0} MissingOptionalAttr(String, CacheEntry), } diff --git a/src/vmm/src/arch/aarch64/gic/mod.rs b/src/vmm/src/arch/aarch64/gic/mod.rs index 0e70dacefd8b..979285b2b41d 100644 --- a/src/vmm/src/arch/aarch64/gic/mod.rs +++ b/src/vmm/src/arch/aarch64/gic/mod.rs @@ -42,21 +42,15 @@ impl GIC { } /// Errors thrown while setting up the GIC. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum GicError { - /// Error while calling KVM ioctl for setting up the global interrupt controller. - #[error("Error while calling KVM ioctl for setting up the global interrupt controller: {0}")] + /// Error while calling KVM ioctl for setting up the global interrupt controller: {0} CreateGIC(kvm_ioctls::Error), - /// Error while setting or getting device attributes for the GIC. - #[error("Error while setting or getting device attributes for the GIC: {0}, {1}, {2}")] + /// Error while setting or getting device attributes for the GIC: {0}, {1}, {2} DeviceAttribute(kvm_ioctls::Error, bool, u32), - /// The number of vCPUs in the GicState doesn't match the number of vCPUs on the system - #[error( - "The number of vCPUs in the GicState doesn't match the number of vCPUs on the system." - )] + /// The number of vCPUs in the GicState doesn't match the number of vCPUs on the system. InconsistentVcpuCount, - /// The VgicSysRegsState is invalid - #[error("The VgicSysRegsState is invalid.")] + /// The VgicSysRegsState is invalid. InvalidVgicSysRegState, } diff --git a/src/vmm/src/arch/aarch64/vcpu.rs b/src/vmm/src/arch/aarch64/vcpu.rs index d9ab10b886fc..1183a506cc83 100644 --- a/src/vmm/src/arch/aarch64/vcpu.rs +++ b/src/vmm/src/arch/aarch64/vcpu.rs @@ -15,28 +15,21 @@ use super::get_fdt_addr; use super::regs::*; /// Errors thrown while setting aarch64 registers. -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum VcpuError { - /// Failed to get a register value. - #[error("Failed to get register {0}: {1}")] + /// Failed to get register {0}: {1} GetOneReg(u64, kvm_ioctls::Error), - /// Failed to set a register value. - #[error("Failed to set register {0}: {1}")] + /// Failed to set register {0}: {1} SetOneReg(u64, kvm_ioctls::Error), - /// Failed to get the register list. - #[error("Failed to retrieve list of registers: {0}")] + /// Failed to retrieve list of registers: {0} GetRegList(kvm_ioctls::Error), - /// Failed to get multiprocessor state. - #[error("Failed to get multiprocessor state: {0}")] + /// Failed to get multiprocessor state: {0} GetMp(kvm_ioctls::Error), - /// Failed to Set multiprocessor state. - #[error("Failed to set multiprocessor state: {0}")] + /// Failed to set multiprocessor state: {0} SetMp(kvm_ioctls::Error), - /// A FamStructWrapper operation has failed. - #[error("Failed FamStructWrapper operation: {0:?}")] + /// Failed FamStructWrapper operation: {0:?} Fam(utils::fam::Error), - /// Failed to get midr_el1 from host. - #[error("{0}")] + /// {0} GetMidrEl1(String), } diff --git a/src/vmm/src/arch/x86_64/interrupts.rs b/src/vmm/src/arch/x86_64/interrupts.rs index ea42ce8cb440..238c0f952afa 100644 --- a/src/vmm/src/arch/x86_64/interrupts.rs +++ b/src/vmm/src/arch/x86_64/interrupts.rs @@ -10,13 +10,11 @@ use kvm_ioctls::VcpuFd; use utils::byte_order; /// Errors thrown while configuring the LAPIC. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum InterruptError { - /// Failure in getting the LAPIC configuration. - #[error("Failure in getting the LAPIC configuration: {0}")] + /// Failure in getting the LAPIC configuration: {0} GetLapic(kvm_ioctls::Error), - /// Failure in setting the LAPIC configuration. - #[error("Failure in setting the LAPIC configuration: {0}")] + /// Failure in setting the LAPIC configuration: {0} SetLapic(kvm_ioctls::Error), } diff --git a/src/vmm/src/arch/x86_64/msr.rs b/src/vmm/src/arch/x86_64/msr.rs index 7550f6d6801d..c2eee6f1523f 100644 --- a/src/vmm/src/arch/x86_64/msr.rs +++ b/src/vmm/src/arch/x86_64/msr.rs @@ -13,23 +13,18 @@ use crate::arch_gen::x86::perf_event::*; use crate::cpu_config::x86_64::cpuid::common::{get_vendor_id_from_host, GetCpuidError}; use crate::cpu_config::x86_64::cpuid::VENDOR_ID_AMD; -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] /// MSR related errors. pub enum MsrError { - /// Failed to create [`vmm_sys_util::fam::FamStructWrapper`] for MSRs. - #[error("Failed to create `vmm_sys_util::fam::FamStructWrapper` for MSRs")] + /// Failed to create `vmm_sys_util::fam::FamStructWrapper` for MSRs Fam(#[from] utils::fam::Error), - /// Failed to get MSR index list. - #[error("Failed to get MSR index list: {0}")] + /// Failed to get MSR index list: {0} GetMsrIndexList(kvm_ioctls::Error), - /// Invalid vendor. - #[error("Invalid CPU vendor: {0}")] + /// Invalid CPU vendor: {0} InvalidVendor(#[from] GetCpuidError), - /// Failed to set MSRs. - #[error("Failed to set MSRs: {0}")] + /// Failed to set MSRs: {0} SetMsrs(kvm_ioctls::Error), /// Not all given MSRs were set. - #[error("Not all given MSRs were set.")] SetMsrsIncomplete, } diff --git a/src/vmm/src/arch/x86_64/regs.rs b/src/vmm/src/arch/x86_64/regs.rs index 41d37389ef73..60ffec6566a0 100644 --- a/src/vmm/src/arch/x86_64/regs.rs +++ b/src/vmm/src/arch/x86_64/regs.rs @@ -19,34 +19,25 @@ const PDPTE_START: u64 = 0xa000; const PDE_START: u64 = 0xb000; /// Errors thrown while setting up x86_64 registers. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum RegsError { - /// Failed to get SREGs for this CPU. - #[error("Failed to get SREGs for this CPU: {0}")] + /// Failed to get SREGs for this CPU: {0} GetStatusRegisters(kvm_ioctls::Error), - /// Failed to set base registers for this CPU. - #[error("Failed to set base registers for this CPU: {0}")] + /// Failed to set base registers for this CPU: {0} SetBaseRegisters(kvm_ioctls::Error), - /// Failed to configure the FPU. - #[error("Failed to configure the FPU: {0}")] + /// Failed to configure the FPU: {0} SetFPURegisters(kvm_ioctls::Error), - /// Failed to set SREGs for this CPU. - #[error("Failed to set SREGs for this CPU: {0}")] + /// Failed to set SREGs for this CPU: {0} SetStatusRegisters(kvm_ioctls::Error), /// Writing the GDT to RAM failed. - #[error("Writing the GDT to RAM failed.")] WriteGDT, - /// Writing the IDT to RAM failed. - #[error("Writing the IDT to RAM failed")] + /// Writing the IDT to RAM failed WriteIDT, - /// Writing PDPTE to RAM failed. - #[error("WritePDPTEAddress")] + /// WritePDPTEAddress WritePDPTEAddress, - /// Writing PDE to RAM failed. - #[error("WritePDEAddress")] + /// WritePDEAddress WritePDEAddress, - /// Writing PML4 to RAM failed. - #[error("WritePML4Address")] + /// WritePML4Address WritePML4Address, } @@ -109,19 +100,15 @@ pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64) -> Result<(), SetupRegistersError } /// Error type for [`setup_sregs`]. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum SetupSpecialRegistersError { - /// Failed to get special registers - #[error("Failed to get special registers: {0}")] + /// Failed to get special registers: {0} GetSpecialRegisters(utils::errno::Error), - /// Failed to configure segments and special registers - #[error("Failed to configure segments and special registers: {0}")] + /// Failed to configure segments and special registers: {0} ConfigureSegmentsAndSpecialRegisters(RegsError), - /// Failed to setup page tables - #[error("Failed to setup page tables: {0}")] + /// Failed to setup page tables: {0} SetupPageTables(RegsError), - /// Failed to set special registers - #[error("Failed to set special registers: {0}")] + /// Failed to set special registers: {0} SetSpecialRegisters(utils::errno::Error), } diff --git a/src/vmm/src/builder.rs b/src/vmm/src/builder.rs index a54d563d2245..3abc134eb51d 100644 --- a/src/vmm/src/builder.rs +++ b/src/vmm/src/builder.rs @@ -379,54 +379,39 @@ pub fn build_and_boot_microvm( } /// Error type for [`build_microvm_from_snapshot`]. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum BuildMicrovmFromSnapshotError { - /// Failed to create microVM and vCPUs. - #[error("Failed to create microVM and vCPUs: {0}")] + /// Failed to create microVM and vCPUs: {0} CreateMicrovmAndVcpus(#[from] StartMicrovmError), /// Only 255 vCPU state are supported, but {0} states where given. - #[error("Only 255 vCPU state are supported, but {0} states where given.")] TooManyVCPUs(usize), - /// Could not access KVM. - #[error("Could not access KVM: {0}")] + /// Could not access KVM: {0} KvmAccess(#[from] utils::errno::Error), /// Error configuring the TSC, frequency not present in the given snapshot. - #[error("Error configuring the TSC, frequency not present in the given snapshot.")] TscFrequencyNotPresent, - /// Could not get TSC to check if TSC scaling was required with the snapshot. #[cfg(target_arch = "x86_64")] - #[error("Could not get TSC to check if TSC scaling was required with the snapshot: {0}")] + /// Could not get TSC to check if TSC scaling was required with the snapshot: {0} GetTsc(#[from] crate::vstate::vcpu::GetTscError), - /// Could not set TSC scaling within the snapshot. #[cfg(target_arch = "x86_64")] - #[error("Could not set TSC scaling within the snapshot: {0}")] + /// Could not set TSC scaling within the snapshot: {0} SetTsc(#[from] crate::vstate::vcpu::SetTscError), - /// Failed to restore microVM state. - #[error("Failed to restore microVM state: {0}")] + /// Failed to restore microVM state: {0} RestoreState(#[from] crate::vstate::vm::RestoreStateError), - /// Failed to update microVM configuration. - #[error("Failed to update microVM configuration: {0}")] + /// Failed to update microVM configuration: {0} VmUpdateConfig(#[from] VmConfigError), - /// Failed to restore MMIO device. - #[error("Failed to restore MMIO device: {0}")] + /// Failed to restore MMIO device: {0} RestoreMmioDevice(#[from] MicrovmStateError), - /// Failed to emulate MMIO serial. - #[error("Failed to emulate MMIO serial: {0}")] + /// Failed to emulate MMIO serial: {0} EmulateSerialInit(#[from] crate::EmulateSerialInitError), /// Failed to start vCPUs as no vCPU seccomp filter found. - #[error("Failed to start vCPUs as no vCPU seccomp filter found.")] MissingVcpuSeccompFilters, - /// Failed to start vCPUs. - #[error("Failed to start vCPUs: {0}")] + /// Failed to start vCPUs: {0} StartVcpus(#[from] crate::StartVcpusError), - /// Failed to restore vCPUs. - #[error("Failed to restore vCPUs: {0}")] + /// Failed to restore vCPUs: {0} RestoreVcpus(#[from] RestoreVcpusError), /// Failed to apply VMM secccomp filter as none found. - #[error("Failed to apply VMM secccomp filter as none found.")] MissingVmmSeccompFilters, - /// Failed to apply VMM secccomp filter. - #[error("Failed to apply VMM secccomp filter: {0}")] + /// Failed to apply VMM secccomp filter: {0} SeccompFiltersInternal(#[from] seccompiler::InstallationError), } diff --git a/src/vmm/src/cpu_config/templates.rs b/src/vmm/src/cpu_config/templates.rs index 7c2f66f90ff0..e9bd7103cb10 100644 --- a/src/vmm/src/cpu_config/templates.rs +++ b/src/vmm/src/cpu_config/templates.rs @@ -29,20 +29,16 @@ use versionize::{VersionMap, Versionize, VersionizeError, VersionizeResult}; use versionize_derive::Versionize; /// Error for GetCpuTemplate trait. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum GetCpuTemplateError { #[cfg(target_arch = "x86_64")] - /// Failed to get CPU vendor information. - #[error("Failed to get CPU vendor information: {0}")] + /// Failed to get CPU vendor information: {0} GetCpuVendor(crate::cpu_config::x86_64::cpuid::common::GetCpuidError), - /// CPU Vendor mismatched between the actual CPU and CPU template. - #[error("CPU vendor mismatched between actual CPU and CPU template.")] + /// CPU vendor mismatched between actual CPU and CPU template. CpuVendorMismatched, - /// Invalid static CPU template. - #[error("Invalid static CPU template: {0}")] + /// Invalid static CPU template: {0} InvalidStaticCpuTemplate(StaticCpuTemplate), - /// Invalid CPU model. - #[error("The current CPU model is not permitted to apply the CPU template.")] + /// The current CPU model is not permitted to apply the CPU template. InvalidCpuModel, } diff --git a/src/vmm/src/cpu_config/x86_64/cpuid/amd/normalize.rs b/src/vmm/src/cpu_config/x86_64/cpuid/amd/normalize.rs index db79acd884c0..65f1c682bc8a 100644 --- a/src/vmm/src/cpu_config/x86_64/cpuid/amd/normalize.rs +++ b/src/vmm/src/cpu_config/x86_64/cpuid/amd/normalize.rs @@ -12,90 +12,69 @@ use crate::cpu_config::x86_64::cpuid::{ /// Error type for [`AmdCpuid::normalize`]. #[allow(clippy::module_name_repetitions)] -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum NormalizeCpuidError { - /// Provided `cpu_bits` is >=8. - #[error("Provided `cpu_bits` is >=8: {0}.")] + /// Provided `cpu_bits` is >=8: {0}. CpuBits(u8), - /// Failed to passthrough cache topology. - #[error("Failed to passthrough cache topology: {0}")] + /// Failed to passthrough cache topology: {0} PassthroughCacheTopology(#[from] PassthroughCacheTopologyError), /// Missing leaf 0x7 / subleaf 0. - #[error("Missing leaf 0x7 / subleaf 0.")] MissingLeaf0x7Subleaf0, /// Missing leaf 0x80000000. - #[error("Missing leaf 0x80000000.")] MissingLeaf0x80000000, /// Missing leaf 0x80000001. - #[error("Missing leaf 0x80000001.")] MissingLeaf0x80000001, - /// Failed to set feature entry leaf. - #[error("Failed to set feature entry leaf: {0}")] + /// Failed to set feature entry leaf: {0} FeatureEntry(#[from] FeatureEntryError), - /// Failed to set extended cache topology leaf. - #[error("Failed to set extended cache topology leaf: {0}")] + /// Failed to set extended cache topology leaf: {0} ExtendedCacheTopology(#[from] ExtendedCacheTopologyError), - /// Failed to set extended APIC ID leaf. - #[error("Failed to set extended APIC ID leaf: {0}")] + /// Failed to set extended APIC ID leaf: {0} ExtendedApicId(#[from] ExtendedApicIdError), - /// Failed to set brand string. - #[error("Failed to set brand string: {0}")] + /// Failed to set brand string: {0} BrandString(MissingBrandStringLeaves), } /// Error type for setting cache topology section of [`AmdCpuid::normalize`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum PassthroughCacheTopologyError { - /// Failed to get the host vendor id. - #[error("Failed to get the host vendor id: {0}")] + /// Failed to get the host vendor id: {0} NoVendorId(GetCpuidError), /// The host vendor id does not match AMD. - #[error("The host vendor id does not match AMD.")] BadVendorId, } /// Error type for setting leaf 0x80000008 section of [`AmdCpuid::normalize`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum FeatureEntryError { /// Missing leaf 0x80000008. - #[error("Missing leaf 0x80000008.")] MissingLeaf0x80000008, /// Failed to set `nt` (number of physical threads) due to overflow. - #[error("Failed to set `nt` (number of physical threads) due to overflow.")] NumberOfPhysicalThreadsOverflow, /// Failed to set `nt` (number of physical threads). - #[error("Failed to set `nt` (number of physical threads).")] NumberOfPhysicalThreads(CheckedAssignError), } /// Error type for setting leaf 0x8000001d section of [`AmdCpuid::normalize`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum ExtendedCacheTopologyError { /// Missing leaf 0x8000001d. - #[error("Missing leaf 0x8000001d.")] MissingLeaf0x8000001d, /// Failed to set `num_sharing_cache` due to overflow. - #[error("Failed to set `num_sharing_cache` due to overflow.")] NumSharingCacheOverflow, - /// Failed to set `num_sharing_cache`. - #[error("Failed to set `num_sharing_cache`: {0}")] + /// Failed to set `num_sharing_cache`: {0} NumSharingCache(CheckedAssignError), } /// Error type for setting leaf 0x8000001e section of [`AmdCpuid::normalize`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum ExtendedApicIdError { - /// Missing leaf 0x8000001d. - #[error("Missing leaf 0x8000001e.")] + /// Missing leaf 0x8000001e. MissingLeaf0x8000001e, - /// Failed to set `extended_apic_id`. - #[error("Failed to set `extended_apic_id`: {0}")] + /// Failed to set `extended_apic_id`: {0} ExtendedApicId(CheckedAssignError), - /// Failed to set `compute_unit_id`. - #[error("Failed to set `compute_unit_id`: {0}")] + /// Failed to set `compute_unit_id`: {0} ComputeUnitId(CheckedAssignError), - /// Failed to set `threads_per_compute_unit`. - #[error("Failed to set `threads_per_compute_unit`: {0}")] + /// Failed to set `threads_per_compute_unit`: {0} ThreadPerComputeUnit(CheckedAssignError), } diff --git a/src/vmm/src/cpu_config/x86_64/cpuid/common.rs b/src/vmm/src/cpu_config/x86_64/cpuid/common.rs index 8f2ac15ee107..7d47bd653f5e 100644 --- a/src/vmm/src/cpu_config/x86_64/cpuid/common.rs +++ b/src/vmm/src/cpu_config/x86_64/cpuid/common.rs @@ -3,13 +3,11 @@ #![allow(clippy::restriction)] /// Error type for [`get_cpuid`]. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum GetCpuidError { - /// Invalid leaf. - #[error("Un-supported leaf: {0}")] + /// Un-supported leaf: {0} UnsupportedLeaf(u32), - /// Invalid subleaf. - #[error("Invalid subleaf: {0}")] + /// Invalid subleaf: {0} InvalidSubleaf(u32), } diff --git a/src/vmm/src/cpu_config/x86_64/cpuid/intel/normalize.rs b/src/vmm/src/cpu_config/x86_64/cpuid/intel/normalize.rs index c4d6ddd95c21..019a2573efb5 100644 --- a/src/vmm/src/cpu_config/x86_64/cpuid/intel/normalize.rs +++ b/src/vmm/src/cpu_config/x86_64/cpuid/intel/normalize.rs @@ -10,59 +10,37 @@ use crate::cpu_config::x86_64::cpuid::{ }; /// Error type for [`IntelCpuid::normalize`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum NormalizeCpuidError { - /// Failed to set deterministic cache leaf. - #[error("Failed to set deterministic cache leaf: {0}")] + /// Failed to set deterministic cache leaf: {0} DeterministicCache(#[from] DeterministicCacheError), /// Leaf 0x6 is missing from CPUID. - #[error("Leaf 0x6 is missing from CPUID.")] MissingLeaf6, /// Leaf 0x7 / subleaf 0 is missing from CPUID. - #[error("Leaf 0x7 / subleaf 0 is missing from CPUID.")] MissingLeaf7, /// Leaf 0xA is missing from CPUID. - #[error("Leaf 0xA is missing from CPUID.")] MissingLeafA, - /// Failed to get brand string. - #[error("Failed to get brand string: {0}")] + /// Failed to get brand string: {0} GetBrandString(DefaultBrandStringError), - /// Failed to set brand string. - #[error("Failed to set brand string: {0}")] + /// Failed to set brand string: {0} ApplyBrandString(MissingBrandStringLeaves), } /// Error type for setting leaf 4 section of `IntelCpuid::normalize`. +// `displaydoc::Display` does not support multi-line comments, `rustfmt` will format these comments +// across multiple lines, so we skip formatting here. This can be removed when +// https://github.com/yaahc/displaydoc/issues/44 is resolved. +#[rustfmt::skip] #[allow(clippy::enum_variant_names)] -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum DeterministicCacheError { - /// Failed to set `Maximum number of addressable IDs for logical processors sharing this - /// cache` due to underflow in cpu count. - #[error( - "Failed to set `Maximum number of addressable IDs for logical processors sharing this \ - cache` due to underflow in cpu count." - )] + /// Failed to set `Maximum number of addressable IDs for logical processors sharing this cache` due to underflow in cpu count. MaxCpusPerCoreUnderflow, - /// Failed to set `Maximum number of addressable IDs for logical processors sharing this - /// cache`. - #[error( - "Failed to set `Maximum number of addressable IDs for logical processors sharing this \ - cache`: {0}" - )] + /// Failed to set `Maximum number of addressable IDs for logical processors sharing this cache`: {0}. MaxCpusPerCore(CheckedAssignError), - /// Failed to set `Maximum number of addressable IDs for processor cores in the physical - /// package` due to underflow in cores - #[error( - "Failed to set `Maximum number of addressable IDs for processor cores in the physical \ - package` due to underflow in cores." - )] + /// Failed to set `Maximum number of addressable IDs for processor cores in the physical package` due to underflow in cores. MaxCorePerPackageUnderflow, - /// Failed to set `Maximum number of addressable IDs for processor cores in the physical - /// package`. - #[error( - "Failed to set `Maximum number of addressable IDs for processor cores in the physical \ - package`: {0}" - )] + /// Failed to set `Maximum number of addressable IDs for processor cores in the physical package`: {0}. MaxCorePerPackage(CheckedAssignError), } @@ -250,16 +228,13 @@ impl super::IntelCpuid { } /// Error type for [`IntelCpuid::default_brand_string`]. -#[derive(Debug, Eq, PartialEq, thiserror::Error)] +#[derive(Debug, Eq, PartialEq, thiserror::Error, displaydoc::Display)] pub enum DefaultBrandStringError { - /// Missing frequency. - #[error("Missing frequency: {0:?}.")] + /// Missing frequency: {0:?}. MissingFrequency([u8; BRAND_STRING_LENGTH]), - /// Missing space. - #[error("Missing space: {0:?}.")] + /// Missing space: {0:?}. MissingSpace([u8; BRAND_STRING_LENGTH]), /// Insufficient space in brand string. - #[error("Insufficient space in brand string.")] Overflow, } diff --git a/src/vmm/src/cpu_config/x86_64/cpuid/mod.rs b/src/vmm/src/cpu_config/x86_64/cpuid/mod.rs index 69131171c136..0d776eb6fa64 100644 --- a/src/vmm/src/cpu_config/x86_64/cpuid/mod.rs +++ b/src/vmm/src/cpu_config/x86_64/cpuid/mod.rs @@ -292,24 +292,19 @@ impl CpuidTrait for kvm_bindings::CpuId { pub struct MissingBrandStringLeaves; /// Error type for [`Cpuid::kvm_get_supported_cpuid`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum KvmGetSupportedCpuidError { - /// Could not access KVM. - #[error("Could not access KVM: {0}")] + /// Could not access KVM: {0} KvmAccess(#[from] utils::errno::Error), } /// Error type for conversion from `kvm_bindings::CpuId` to `Cpuid`. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum CpuidTryFromKvmCpuid { /// Leaf 0 not found in the given `kvm_bindings::CpuId`. - #[error("Leaf 0 not found in the given `kvm_bindings::CpuId`.")] MissingLeaf0, - /// Unsupported CPUID manufacturer id. - #[error( - "Unsupported CPUID manufacturer id: \"{0:?}\" (only 'GenuineIntel' and 'AuthenticAMD' are \ - supported)." - )] + #[rustfmt::skip] + #[doc = "Unsupported CPUID manufacturer id: \"{0:?}\" (only 'GenuineIntel' and 'AuthenticAMD' are supported)."] UnsupportedVendor([u8; 12]), } diff --git a/src/vmm/src/cpu_config/x86_64/cpuid/normalize.rs b/src/vmm/src/cpu_config/x86_64/cpuid/normalize.rs index fb3de1d585ff..cebd34f319e4 100644 --- a/src/vmm/src/cpu_config/x86_64/cpuid/normalize.rs +++ b/src/vmm/src/cpu_config/x86_64/cpuid/normalize.rs @@ -7,102 +7,77 @@ use crate::cpu_config::x86_64::cpuid::{ /// Error type for [`Cpuid::normalize`]. #[allow(clippy::module_name_repetitions)] -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum NormalizeCpuidError { - /// Provided `cpu_bits` is >=8. - #[error("Provided `cpu_bits` is >=8: {0}.")] + /// Provided `cpu_bits` is >=8: {0}. CpuBits(u8), - /// Failed to apply modifications to Intel CPUID. - #[error("Failed to apply modifications to Intel CPUID: {0}")] + /// Failed to apply modifications to Intel CPUID: {0} Intel(#[from] crate::cpu_config::x86_64::cpuid::intel::NormalizeCpuidError), - /// Failed to apply modifications to AMD CPUID. - #[error("Failed to apply modifications to AMD CPUID: {0}")] + /// Failed to apply modifications to AMD CPUID: {0} Amd(#[from] crate::cpu_config::x86_64::cpuid::amd::NormalizeCpuidError), - /// Failed to set feature information leaf. - #[error("Failed to set feature information leaf: {0}")] + /// Failed to set feature information leaf: {0} FeatureInformation(#[from] FeatureInformationError), - /// Failed to set extended topology leaf. - #[error("Failed to set extended topology leaf: {0}")] + /// Failed to set extended topology leaf: {0} ExtendedTopology(#[from] ExtendedTopologyError), - /// Failed to set extended cache features leaf. - #[error("Failed to set extended cache features leaf: {0}")] + /// Failed to set extended cache features leaf: {0} ExtendedCacheFeatures(#[from] ExtendedCacheFeaturesError), - /// Failed to set vendor ID in leaf 0x0. - #[error("Failed to set vendor ID in leaf 0x0: {0}")] + /// Failed to set vendor ID in leaf 0x0: {0} VendorId(#[from] VendorIdError), } /// Error type for setting leaf 0 section. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum VendorIdError { /// Leaf 0x0 is missing from CPUID. - #[error("Leaf 0x0 is missing from CPUID.")] MissingLeaf0, } /// Error type for setting leaf 1 section of `IntelCpuid::normalize`. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum FeatureInformationError { /// Leaf 0x1 is missing from CPUID. - #[error("Leaf 0x1 is missing from CPUID.")] MissingLeaf1, - /// Failed to set `Initial APIC ID`. - #[error("Failed to set `Initial APIC ID`: {0}")] + /// Failed to set `Initial APIC ID`: {0} InitialApicId(CheckedAssignError), - /// Failed to set `CLFLUSH line size`. - #[error("Failed to set `CLFLUSH line size`: {0}")] + /// Failed to set `CLFLUSH line size`: {0} Clflush(CheckedAssignError), - /// Failed to get max CPUs per package. - #[error("Failed to get max CPUs per package: {0}")] + /// Failed to get max CPUs per package: {0} GetMaxCpusPerPackage(GetMaxCpusPerPackageError), - /// Failed to set max CPUs per package. - #[error("Failed to set max CPUs per package: {0}")] + /// Failed to set max CPUs per package: {0} SetMaxCpusPerPackage(CheckedAssignError), } /// Error type for `get_max_cpus_per_package`. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum GetMaxCpusPerPackageError { - /// Failed to get max CPUs per package as `cpu_count == 0`. - #[error("Failed to get max CPUs per package as `cpu_count == 0`")] + /// Failed to get max CPUs per package as `cpu_count == 0` Underflow, - /// Failed to get max CPUs per package as `cpu_count > 128`. - #[error("Failed to get max CPUs per package as `cpu_count > 128`")] + /// Failed to get max CPUs per package as `cpu_count > 128` Overflow, } /// Error type for setting leaf b section of `IntelCpuid::normalize`. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum ExtendedTopologyError { - /// Failed to set `Number of bits to shift right on x2APIC ID to get a unique topology ID of - /// the next level type`. - #[error( - "Failed to set `Number of bits to shift right on x2APIC ID to get a unique topology ID of \ - the next level type`: {0}" - )] + #[rustfmt::skip] + #[doc = "Failed to set `Number of bits to shift right on x2APIC ID to get a unique topology ID of the next level type`: {0}"] ApicId(CheckedAssignError), - /// Failed to set `Number of logical processors at this level type`. - #[error("Failed to set `Number of logical processors at this level type`: {0}")] + /// Failed to set `Number of logical processors at this level type`: {0} LogicalProcessors(CheckedAssignError), - /// Failed to set `Level Type`. - #[error("Failed to set `Level Type`: {0}")] + /// Failed to set `Level Type`: {0} LevelType(CheckedAssignError), - /// Failed to set `Level Number`. - #[error("Failed to set `Level Number`: {0}")] + /// Failed to set `Level Number`: {0} LevelNumber(CheckedAssignError), - /// Failed to set all leaves, as more than `u32::MAX` sub-leaves are present. - #[error("Failed to set all leaves, as more than `u32::MAX` sub-leaves are present: {0}")] + /// Failed to set all leaves, as more than `u32::MAX` sub-leaves are present: {0} Overflow(>::Error), } /// Error type for setting leaf 0x80000006 of Cpuid::normalize(). -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum ExtendedCacheFeaturesError { /// Leaf 0x80000005 is missing from CPUID. - #[error("Leaf 0x80000005 is missing from CPUID.")] MissingLeaf0x80000005, /// Leaf 0x80000006 is missing from CPUID. - #[error("Leaf 0x80000006 is missing from CPUID.")] MissingLeaf0x80000006, } diff --git a/src/vmm/src/cpu_config/x86_64/mod.rs b/src/vmm/src/cpu_config/x86_64/mod.rs index 19522bfea622..13824880bbbb 100644 --- a/src/vmm/src/cpu_config/x86_64/mod.rs +++ b/src/vmm/src/cpu_config/x86_64/mod.rs @@ -17,19 +17,15 @@ use super::templates::CustomCpuTemplate; use crate::cpu_config::x86_64::cpuid::{Cpuid, CpuidKey}; /// Errors thrown while configuring templates. -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum CpuConfigurationError { - /// Failure in processing the CPUID in template for x86_64 CPU configuration. - #[error("Template changes a CPUID entry not supported by KVM: Leaf: {0:0x}, Subleaf: {1:0x}")] + /// Template changes a CPUID entry not supported by KVM: Leaf: {0:0x}, Subleaf: {1:0x} CpuidFeatureNotSupported(u32, u32), - /// Failure in processing the MSRs in template for x86_64 CPU configuration. - #[error("Template changes an MSR entry not supported by KVM: Register Address: {0:0x}")] + /// Template changes an MSR entry not supported by KVM: Register Address: {0:0x} MsrNotSupported(u32), - /// Can create cpuid from raw. - #[error("Can create cpuid from raw: {0}")] + /// Can create cpuid from raw: {0} CpuidFromKvmCpuid(crate::cpu_config::x86_64::cpuid::CpuidTryFromKvmCpuid), - /// KVM vcpu ioctls failed. - #[error("KVM vcpu ioctl failed: {0}")] + /// KVM vcpu ioctl failed: {0} VcpuIoctl(crate::vstate::vcpu::KvmVcpuError), } diff --git a/src/vmm/src/device_manager/legacy.rs b/src/vmm/src/device_manager/legacy.rs index b4aae3aac4a1..0430d92e4f8f 100644 --- a/src/vmm/src/device_manager/legacy.rs +++ b/src/vmm/src/device_manager/legacy.rs @@ -19,13 +19,11 @@ use crate::devices::legacy::serial::SerialOut; use crate::devices::legacy::{EventFdTrigger, SerialDevice, SerialEventsWrapper}; /// Errors corresponding to the `PortIODeviceManager`. -#[derive(Debug, derive_more::From, thiserror::Error)] +#[derive(Debug, derive_more::From, thiserror::Error, displaydoc::Display)] pub enum LegacyDeviceError { - /// Cannot add legacy device to Bus. - #[error("Failed to add legacy device to Bus: {0}")] + /// Failed to add legacy device to Bus: {0} BusError(crate::devices::BusError), - /// Cannot create EventFd. - #[error("Failed to create EventFd: {0}")] + /// Failed to create EventFd: {0} EventFd(std::io::Error), } diff --git a/src/vmm/src/device_manager/mmio.rs b/src/vmm/src/device_manager/mmio.rs index 952ed783c13d..b43535d2048f 100644 --- a/src/vmm/src/device_manager/mmio.rs +++ b/src/vmm/src/device_manager/mmio.rs @@ -32,34 +32,25 @@ use crate::devices::virtio::{ use crate::devices::BusDevice; /// Errors for MMIO device manager. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum MmioError { - /// Allocation logic error. - #[error("Failed to allocate requested resource: {0}")] + /// Failed to allocate requested resource: {0} Allocator(vm_allocator::Error), - /// Failed to insert device on the bus. - #[error("Failed to insert device on the bus: {0}")] + /// Failed to insert device on the bus: {0} BusInsert(crate::devices::BusError), - /// Appending to kernel command line failed. - #[error("Failed to allocate requested resourc: {0}")] + /// Failed to allocate requested resourc: {0} Cmdline(linux_loader::cmdline::Error), - /// The device couldn't be found on the bus. - #[error("Failed to find the device on the bus.")] + /// Failed to find the device on the bus. DeviceNotFound, - /// Incorrect device type. - #[error("Invalid device type found on the MMIO bus.")] + /// Invalid device type found on the MMIO bus. InvalidDeviceType, - /// Internal device error. - #[error("{0}")] + /// {0} InternalDeviceError(String), - /// Invalid configuration attempted. - #[error("Invalid MMIO IRQ configuration.")] + /// Invalid MMIO IRQ configuration. InvalidIrqConfig, - /// Registering an IO Event failed. - #[error("Failed to register IO event: {0}")] + /// Failed to register IO event: {0} RegisterIoEvent(kvm_ioctls::Error), - /// Registering an IRQ FD failed. - #[error("Failed to register irqfd: {0}")] + /// Failed to register irqfd: {0} RegisterIrqFd(kvm_ioctls::Error), } diff --git a/src/vmm/src/devices/bus.rs b/src/vmm/src/devices/bus.rs index b5d91545d2b7..b646b57ff41f 100644 --- a/src/vmm/src/devices/bus.rs +++ b/src/vmm/src/devices/bus.rs @@ -12,10 +12,9 @@ use std::collections::btree_map::BTreeMap; use std::sync::{Arc, Mutex}; /// Errors triggered during bus operations. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum BusError { - /// The insertion failed because the new device overlapped with an old device. - #[error("New device overlaps with an old device.")] + /// New device overlaps with an old device. Overlap, } diff --git a/src/vmm/src/devices/legacy/i8042.rs b/src/vmm/src/devices/legacy/i8042.rs index 2524386ef0ea..28f17f53d4ce 100644 --- a/src/vmm/src/devices/legacy/i8042.rs +++ b/src/vmm/src/devices/legacy/i8042.rs @@ -13,16 +13,13 @@ use logger::{IncMetric, METRICS}; use utils::eventfd::EventFd; /// Errors thrown by the i8042 device. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum I8042Error { - /// Internal i8042 buffer is full. - #[error("i8042 internal buffer full.")] + /// i8042 internal buffer full. InternalBufferFull, - /// Failure in triggering the keyboard interrupt. - #[error("Keyboard interrupt disabled by guest driver.")] + /// Keyboard interrupt disabled by guest driver. KbdInterruptDisabled, - /// Failure in triggering the keyboard interrupt (guest disabled). - #[error("Could not trigger keyboard interrupt: {0}.")] + /// Could not trigger keyboard interrupt: {0}. KbdInterruptFailure(io::Error), } diff --git a/src/vmm/src/devices/virtio/iovec.rs b/src/vmm/src/devices/virtio/iovec.rs index 1267412b3e27..90fdc98b8c9b 100644 --- a/src/vmm/src/devices/virtio/iovec.rs +++ b/src/vmm/src/devices/virtio/iovec.rs @@ -6,16 +6,13 @@ use utils::vm_memory::{Bitmap, GuestMemory, GuestMemoryMmap}; use crate::devices::virtio::DescriptorChain; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum IoVecError { - /// We found a write-only descriptor where read-only was expected - #[error("Tried to create an `IoVec` from a write-only descriptor chain")] + /// Tried to create an `IoVec` from a write-only descriptor chain WriteOnlyDescriptor, - /// We found a read-only descriptor where write-only was expected - #[error("Tried to create an 'IoVecMut` from a read-only descriptor chain")] + /// Tried to create an 'IoVecMut` from a read-only descriptor chain ReadOnlyDescriptor, - /// An error happened with guest memory handling - #[error("Guest memory error: {0}")] + /// Guest memory error: {0} GuestMemory(#[from] utils::vm_memory::GuestMemoryError), } diff --git a/src/vmm/src/devices/virtio/net/mod.rs b/src/vmm/src/devices/virtio/net/mod.rs index 5c17440b21eb..f5605e8591ac 100644 --- a/src/vmm/src/devices/virtio/net/mod.rs +++ b/src/vmm/src/devices/virtio/net/mod.rs @@ -38,24 +38,18 @@ pub enum NetQueue { } /// Errors the network device can trigger. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum NetError { - /// Open tap device failed - #[error("Open tap device failed: {0}")] + /// Open tap device failed: {0} TapOpen(TapError), - /// Setting tap interface offload flags failed - #[error("Setting tap interface offload flags failed: {0}")] + /// Setting tap interface offload flags failed: {0} TapSetOffload(TapError), - /// Setting vnet header size failed - #[error("Setting vnet header size failed: {0}")] + /// Setting vnet header size failed: {0} TapSetVnetHdrSize(TapError), - /// EventFd error - #[error("EventFd error: {0}")] + /// EventFd error: {0} EventFd(io::Error), - /// IO error - #[error("IO error: {0}")] + /// IO error: {0} IO(io::Error), /// The VNET header is missing from the frame - #[error("The VNET header is missing from the frame")] VnetHeaderMissing, } diff --git a/src/vmm/src/devices/virtio/net/tap.rs b/src/vmm/src/devices/virtio/net/tap.rs index 23ab26466938..3d59c0f26c70 100644 --- a/src/vmm/src/devices/virtio/net/tap.rs +++ b/src/vmm/src/devices/virtio/net/tap.rs @@ -24,25 +24,18 @@ use crate::devices::virtio::net::test_utils::Mocks; const IFACE_NAME_MAX_LEN: usize = 16; /// List of errors the tap implementation can throw. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum TapError { - /// Couldn't open /dev/net/tun - #[error("Couldn't open /dev/net/tun: {0}")] + /// Couldn't open /dev/net/tun: {0} OpenTun(IoError), /// Invalid interface name - #[error("Invalid interface name")] InvalidIfname, - /// Error while creating ifreq structure - #[error( - "Error while creating ifreq structure: {0}. Invalid TUN/TAP Backend provided by {1}. \ - Check our documentation on setting up the network devices." - )] + #[rustfmt::skip] + #[doc = "Error while creating ifreq structure: {0}. Invalid TUN/TAP Backend provided by {1}. Check our documentation on setting up the network devices."] IfreqExecuteError(IoError, String), - /// Error while setting the offload flags - #[error("Error while setting the offload flags: {0}")] + /// Error while setting the offload flags: {0} SetOffloadFlags(IoError), - /// Error while setting size of the vnet header - #[error("Error while setting size of the vnet header: {0}")] + /// Error while setting size of the vnet header: {0} SetSizeOfVnetHdr(IoError), } diff --git a/src/vmm/src/devices/virtio/queue.rs b/src/vmm/src/devices/virtio/queue.rs index 4642d003f563..2d9c1851d428 100644 --- a/src/vmm/src/devices/virtio/queue.rs +++ b/src/vmm/src/devices/virtio/queue.rs @@ -28,13 +28,11 @@ pub(super) const FIRECRACKER_MAX_QUEUE_SIZE: u16 = 256; // The Virtio Spec 1.0 defines the alignment of VirtIO descriptor is 16 bytes, // which fulfills the explicit constraint of GuestMemoryMmap::read_obj_from_addr(). -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum QueueError { - /// Descriptor index out of bounds. - #[error("Descriptor index out of bounds: {0}.")] + /// Descriptor index out of bounds: {0}. DescIndexOutOfBounds(u16), - /// Attempted an invalid write into the used ring. - #[error("Failed to write value into the virtio queue used ring: {0}")] + /// Failed to write value into the virtio queue used ring: {0} UsedRing(#[from] GuestMemoryError), } diff --git a/src/vmm/src/devices/virtio/rng/device.rs b/src/vmm/src/devices/virtio/rng/device.rs index f522bc2f735c..19d45ed5637c 100644 --- a/src/vmm/src/devices/virtio/rng/device.rs +++ b/src/vmm/src/devices/virtio/rng/device.rs @@ -22,13 +22,13 @@ use crate::rate_limiter::{RateLimiter, TokenType}; pub const ENTROPY_DEV_ID: &str = "rng"; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum EntropyError { - #[error("Error while handling an Event file descriptor: {0}")] + /// Error while handling an Event file descriptor: {0} EventFd(#[from] io::Error), - #[error("Bad guest memory buffer: {0}")] + /// Bad guest memory buffer: {0} GuestMemory(#[from] GuestMemoryError), - #[error("Could not get random bytes: {0}")] + /// Could not get random bytes: {0} Random(#[from] aws_lc_rs::error::Unspecified), } diff --git a/src/vmm/src/devices/virtio/vsock/csm/mod.rs b/src/vmm/src/devices/virtio/vsock/csm/mod.rs index 8237c589e036..91a33d1bece1 100644 --- a/src/vmm/src/devices/virtio/vsock/csm/mod.rs +++ b/src/vmm/src/devices/virtio/vsock/csm/mod.rs @@ -23,16 +23,13 @@ pub mod defs { pub const CONN_SHUTDOWN_TIMEOUT_MS: u64 = 2000; } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum VsockCsmError { - /// Attempted to push data to a full TX buffer. - #[error("Attempted to push data to a full TX buffer")] + /// Attempted to push data to a full TX buffer TxBufFull, - /// An I/O error occurred, when attempting to flush the connection TX buffer. - #[error("An I/O error occurred, when attempting to flush the connection TX buffer: {0}")] + /// An I/O error occurred, when attempting to flush the connection TX buffer: {0} TxBufFlush(std::io::Error), - /// An I/O error occurred, when attempting to write data to the host-side stream. - #[error("An I/O error occurred, when attempting to write data to the host-side stream: {0}")] + /// An I/O error occurred, when attempting to write data to the host-side stream: {0} StreamWrite(std::io::Error), } diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rs index 8e600eff325f..16d21785c7df 100644 --- a/src/vmm/src/lib.rs +++ b/src/vmm/src/lib.rs @@ -187,88 +187,62 @@ pub const HTTP_MAX_PAYLOAD_SIZE: usize = 51200; /// Errors associated with the VMM internal logic. These errors cannot be generated by direct user /// input, but can result from bad configuration of the host (for example if Firecracker doesn't /// have permissions to open the KVM fd). -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum VmmError { #[cfg(target_arch = "aarch64")] - #[error("Invalid cmdline")] /// Invalid command line error. Cmdline, - /// Device manager error. - #[error("{0}")] + /// {0} DeviceManager(device_manager::mmio::MmioError), - /// Cannot fetch the KVM dirty bitmap. - #[error("Error getting the KVM dirty bitmap. {0}")] + /// Error getting the KVM dirty bitmap. {0} DirtyBitmap(kvm_ioctls::Error), - /// Cannot read from an Event file descriptor. - #[error("Event fd error: {0}")] + /// Event fd error: {0} EventFd(io::Error), - /// I8042 Error. - #[error("I8042 error: {0}")] + /// I8042 error: {0} I8042Error(devices::legacy::I8042DeviceError), - /// Cannot access kernel file. - #[error("Cannot access kernel file: {0}")] + /// Cannot access kernel file: {0} KernelFile(io::Error), - /// Cannot add devices to the Legacy I/O Bus. #[cfg(target_arch = "x86_64")] - #[error("Cannot add devices to the legacy I/O Bus. {0}")] + /// Cannot add devices to the legacy I/O Bus. {0} LegacyIOBus(device_manager::legacy::LegacyDeviceError), - /// Internal metrics system error. - #[error("Metrics error: {0}")] + /// Metrics error: {0} Metrics(MetricsError), - /// Cannot add a device to the MMIO Bus. - #[error("Cannot add a device to the MMIO Bus. {0}")] + /// Cannot add a device to the MMIO Bus. {0} RegisterMMIODevice(device_manager::mmio::MmioError), - /// Cannot install seccomp filters. - #[error("Cannot install seccomp filters: {0}")] + /// Cannot install seccomp filters: {0} SeccompFilters(seccompiler::InstallationError), - /// Write to the serial console failed. - #[error("Error writing to the serial console: {0}")] + /// Error writing to the serial console: {0} Serial(io::Error), - /// Cannot create Timer file descriptor. - #[error("Error creating timer fd: {0}")] + /// Error creating timer fd: {0} TimerFd(io::Error), - /// Vcpu configuration error. - #[error("Error configuring the vcpu for boot: {0}")] + /// Error configuring the vcpu for boot: {0} VcpuConfigure(KvmVcpuConfigureError), - /// Vcpu create error. - #[error("Error creating the vcpu: {0}")] + /// Error creating the vcpu: {0} VcpuCreate(vstate::vcpu::VcpuError), - /// Cannot send event to vCPU. - #[error("Cannot send event to vCPU. {0}")] + /// Cannot send event to vCPU. {0} VcpuEvent(vstate::vcpu::VcpuError), - /// Cannot create a vCPU handle. - #[error("Cannot create a vCPU handle. {0}")] + /// Cannot create a vCPU handle. {0} VcpuHandle(vstate::vcpu::VcpuError), - /// Vcpu init error. #[cfg(target_arch = "aarch64")] - #[error("Error initializing the vcpu: {0}")] + /// Error initializing the vcpu: {0} VcpuInit(vstate::vcpu::KvmVcpuError), - /// vCPU start error. - #[error("Failed to start vCPUs")] + /// Failed to start vCPUs VcpuStart(StartVcpusError), - /// vCPU pause failed. - #[error("Failed to pause the vCPUs.")] + /// Failed to pause the vCPUs. VcpuPause, - /// vCPU exit failed. - #[error("Failed to exit the vCPUs.")] + /// Failed to exit the vCPUs. VcpuExit, - /// vCPU resume failed. - #[error("Failed to resume the vCPUs.")] + /// Failed to resume the vCPUs. VcpuResume, - /// Vcpu send message failed. - #[error("Failed to message the vCPUs.")] + /// Failed to message the vCPUs. VcpuMessage, - /// Cannot spawn a new Vcpu thread. - #[error("Cannot spawn Vcpu thread: {0}")] + /// Cannot spawn Vcpu thread: {0} VcpuSpawn(io::Error), - /// Vm error. - #[error("Vm error: {0}")] + /// Vm error: {0} Vm(vstate::vm::VmError), - /// Error thrown by observer object on Vmm initialization. - #[error("Error thrown by observer object on Vmm initialization: {0}")] + /// Error thrown by observer object on Vmm initialization: {0} VmmObserverInit(utils::errno::Error), - /// Error thrown by observer object on Vmm teardown. - #[error("Error thrown by observer object on Vmm teardown: {0}")] + /// Error thrown by observer object on Vmm teardown: {0} VmmObserverTeardown(utils::errno::Error), } @@ -286,47 +260,37 @@ pub(crate) fn mem_size_mib(guest_memory: &GuestMemoryMmap) -> u64 { pub struct EmulateSerialInitError(std::io::Error); /// Error type for [`Vmm::start_vcpus`]. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum StartVcpusError { - /// Vmm observer init error. - #[error("{0}")] + /// {0} VmmObserverInit(#[from] utils::errno::Error), - /// vCPU handle error. - #[error("{0}")] + /// {0} VcpuHandle(#[from] StartThreadedError), } /// Error type for [`Vmm::restore_vcpu_states`] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum RestoreVcpusError { - /// Failed to send event. - #[error("Failed to send event: {0}")] + /// Failed to send event: {0} SendEvent(#[from] VcpuSendEventError), - /// Vcpu is in unexpected state. - #[error("Unexpected vCPU response.")] + /// Unexpected vCPU response. UnexpectedVcpuResponse, - /// Failed to restore vCPU state. - #[error("Failed to restore vCPU state: {0}")] + /// Failed to restore vCPU state: {0} RestoreVcpuState(#[from] vcpu::VcpuError), - /// Not allowed. - #[error("Not allowed: {0}")] + /// Not allowed: {0} NotAllowed(String), } /// Error type for [`Vmm::dump_cpu_config()`] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum DumpCpuConfigError { - /// Failed to send an event to vcpu thread. - #[error("Failed to send event to vcpu thread: {0:?}")] + /// Failed to send event to vcpu thread: {0:?} SendEvent(#[from] VcpuSendEventError), - /// Got an unexpected response from vcpu thread. - #[error("Got unexpected response from vcpu thread.")] + /// Got unexpected response from vcpu thread. UnexpectedResponse, - /// Failed to dump CPU config. - #[error("Failed to dump CPU config: {0}")] + /// Failed to dump CPU config: {0} DumpCpuConfig(#[from] vcpu::VcpuError), - /// Operation not allowed. - #[error("Operation not allowed: {0}")] + /// Operation not allowed: {0} NotAllowed(String), } diff --git a/src/vmm/src/memory_snapshot.rs b/src/vmm/src/memory_snapshot.rs index 76c5a9d87ee2..28e7f5d45903 100644 --- a/src/vmm/src/memory_snapshot.rs +++ b/src/vmm/src/memory_snapshot.rs @@ -63,22 +63,17 @@ where } /// Errors associated with dumping guest memory to file. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum SnapshotMemoryError { - /// Cannot access file. - #[error("Cannot access file: {0:?}")] + /// Cannot access file: {0:?} FileHandle(#[from] std::io::Error), - /// Cannot create memory. - #[error("Cannot create memory: {0:?}")] + /// Cannot create memory: {0:?} CreateMemory(#[from] utils::vm_memory::Error), - /// Cannot create region. - #[error("Cannot create memory region: {0:?}")] + /// Cannot create memory region: {0:?} CreateRegion(#[from] utils::vm_memory::MmapRegionError), - /// Cannot fetch system's page size. - #[error("Cannot fetch system's page size: {0:?}")] + /// Cannot fetch system's page size: {0:?} PageSize(#[from] errno::Error), - /// Cannot dump memory. - #[error("Cannot dump memory: {0:?}")] + /// Cannot dump memory: {0:?} WriteMemory(#[from] GuestMemoryError), } diff --git a/src/vmm/src/persist.rs b/src/vmm/src/persist.rs index 769f4fdd4b23..44fce4df078a 100644 --- a/src/vmm/src/persist.rs +++ b/src/vmm/src/persist.rs @@ -11,7 +11,7 @@ use std::os::unix::net::UnixStream; use std::path::Path; use std::sync::{Arc, Mutex}; -use log::{error, info, warn}; +use log::{info, warn}; use seccompiler::BpfThreadMap; use semver::Version; use serde::Serialize; @@ -156,79 +156,55 @@ pub struct GuestRegionUffdMapping { } /// Errors related to saving and restoring Microvm state. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum MicrovmStateError { - /// Compatibility checks failed. - #[error("Compatibility checks failed: {0}")] + /// Compatibility checks failed: {0} IncompatibleState(String), /// Provided MicroVM state is invalid. - #[error("Provided MicroVM state is invalid.")] InvalidInput, - /// Operation not allowed. - #[error("Operation not allowed: {0}")] + /// Operation not allowed: {0} NotAllowed(String), - /// Failed to restore devices. - #[error("Cannot restore devices: {0:?}")] + /// Cannot restore devices: {0:?} RestoreDevices(DevicePersistError), - /// Failed to restore Vcpu state. - #[error("Cannot restore Vcpu state: {0:?}")] + /// Cannot restore Vcpu state: {0:?} RestoreVcpuState(vstate::vcpu::VcpuError), - /// Failed to restore VM state. - #[error("Cannot restore Vm state: {0:?}")] + /// Cannot restore Vm state: {0:?} RestoreVmState(vstate::vm::VmError), - /// Failed to save Vcpu state. - #[error("Cannot save Vcpu state: {0:?}")] + /// Cannot save Vcpu state: {0:?} SaveVcpuState(vstate::vcpu::VcpuError), - /// Failed to save VM state. - #[error("Cannot save Vm state: {0:?}")] + /// Cannot save Vm state: {0:?} SaveVmState(vstate::vm::VmError), - /// Failed to send event. - #[error("Cannot signal Vcpu: {0:?}")] + /// Cannot signal Vcpu: {0:?} SignalVcpu(VcpuSendEventError), /// Vcpu is in unexpected state. - #[error("Vcpu is in unexpected state.")] UnexpectedVcpuResponse, } /// Errors associated with creating a snapshot. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum CreateSnapshotError { - /// Failed to get dirty bitmap. - #[error("Cannot get dirty bitmap: {0}")] + /// Cannot get dirty bitmap: {0} DirtyBitmap(VmmError), - /// The virtio devices uses a features that is incompatible with older versions of Firecracker. - #[error( - "The virtio devices use a features that is incompatible with older versions of \ - Firecracker: {0}" - )] + #[rustfmt::skip] + #[doc = "The virtio devices use a features that is incompatible with older versions of Firecracker: {0}"] IncompatibleVirtioFeature(&'static str), /// Invalid microVM version format - #[error("Invalid microVM version format")] InvalidVersionFormat, - /// MicroVM version does not support snapshot. - #[error("Cannot translate microVM version to snapshot data version")] + /// Cannot translate microVM version to snapshot data version UnsupportedVersion, - /// Failed to write memory to snapshot. - #[error("Cannot write memory file: {0}")] + /// Cannot write memory file: {0} Memory(memory_snapshot::SnapshotMemoryError), - /// Failed to open memory backing file. - #[error("Cannot perform {0} on the memory backing file: {1}")] + /// Cannot perform {0} on the memory backing file: {1} MemoryBackingFile(&'static str, io::Error), - /// Failed to save MicrovmState. - #[error("Cannot save the microVM state: {0}")] + /// Cannot save the microVM state: {0} MicrovmState(MicrovmStateError), - /// Failed to serialize microVM state. - #[error("Cannot serialize the microVM state: {0}")] + /// Cannot serialize the microVM state: {0} SerializeMicrovmState(snapshot::Error), - /// Failed to open the snapshot backing file. - #[error("Cannot perform {0} on the snapshot backing file: {1}")] + /// Cannot perform {0} on the snapshot backing file: {1} SnapshotBackingFile(&'static str, io::Error), - /// Number of devices exceeds the maximum supported devices for the snapshot data version. #[cfg(target_arch = "x86_64")] - #[error( - "Too many devices attached: {0}. The maximum number allowed for the snapshot data version \ - requested is {FC_V0_23_MAX_DEVICES}." - )] + #[rustfmt::skip] + #[doc = "Too many devices attached: {0}. The maximum number allowed for the snapshot data version requested is {FC_V0_23_MAX_DEVICES:}."] TooManyDevices(usize), } @@ -448,13 +424,11 @@ pub fn validate_cpu_manufacturer_id(microvm_state: &MicrovmState) { } } /// Error type for [`snapshot_state_sanity_check`]. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum SnapShotStateSanityCheckError { /// Invalid vCPU count. - #[error("Invalid vCPU count.")] InvalidVcpuCount, /// No memory region defined. - #[error("No memory region defined.")] NoMemory, } @@ -485,30 +459,24 @@ pub fn snapshot_state_sanity_check( } /// Error type for [`restore_from_snapshot`]. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum RestoreFromSnapshotError { - /// Failed to get snapshot state from file. - #[error("Failed to get snapshot state from file: {0}")] + /// Failed to get snapshot state from file: {0} File(#[from] SnapshotStateFromFileError), - /// Invalid snapshot state. - #[error("Invalid snapshot state: {0}")] + /// Invalid snapshot state: {0} Invalid(#[from] SnapShotStateSanityCheckError), - /// Failed to load guest memory - #[error("Failed to load guest memory: {0}")] + /// Failed to load guest memory: {0} GuestMemory(#[from] RestoreFromSnapshotGuestMemoryError), - /// Failed to build microVM from snapshot. - #[error("Failed to build microVM from snapshot: {0}")] + /// Failed to build microVM from snapshot: {0} Build(#[from] BuildMicrovmFromSnapshotError), } /// Sub-Error type for [`restore_from_snapshot`] to contain either [`GuestMemoryFromFileError`] or /// [`GuestMemoryFromUffdError`] within [`RestoreFromSnapshotError`]. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum RestoreFromSnapshotGuestMemoryError { - /// Error creating guest memory from file. - #[error("Error creating guest memory from file: {0}")] + /// Error creating guest memory from file: {0} File(#[from] GuestMemoryFromFileError), - /// Error creating guest memory from uffd. - #[error("Error creating guest memory from uffd: {0}")] + /// Error creating guest memory from uffd: {0} Uffd(#[from] GuestMemoryFromUffdError), } @@ -560,16 +528,13 @@ pub fn restore_from_snapshot( } /// Error type for [`snapshot_state_from_file`] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum SnapshotStateFromFileError { - /// Failed to open snapshot file. - #[error("Failed to open snapshot file: {0}")] + /// Failed to open snapshot file: {0} Open(std::io::Error), - /// Failed to read snapshot file metadata. - #[error("Failed to read snapshot file metadata: {0}")] + /// Failed to read snapshot file metadata: {0} Meta(std::io::Error), - /// Failed to load snapshot state from file. - #[error("Failed to load snapshot state from file: {0}")] + /// Failed to load snapshot state from file: {0} Load(#[from] snapshot::Error), } @@ -587,13 +552,11 @@ fn snapshot_state_from_file( } /// Error type for [`guest_memory_from_file`]. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum GuestMemoryFromFileError { - /// Failed to load guest memory. - #[error("Failed to load guest memory: {0}")] + /// Failed to load guest memory: {0} File(#[from] std::io::Error), - /// Failed to restore guest memory. - #[error("Failed to restore guest memory: {0}")] + /// Failed to restore guest memory: {0} Restore(#[from] crate::memory_snapshot::SnapshotMemoryError), } @@ -608,22 +571,17 @@ fn guest_memory_from_file( } /// Error type for [`guest_memory_from_uffd`] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum GuestMemoryFromUffdError { - /// Failed to restore guest memory. - #[error("Failed to restore guest memory: {0}")] + /// Failed to restore guest memory: {0} Restore(#[from] crate::memory_snapshot::SnapshotMemoryError), - /// Failed to UFFD object. - #[error("Failed to UFFD object: {0}")] + /// Failed to UFFD object: {0} Create(userfaultfd::Error), - /// Failed to register memory address range with the userfaultfd object. - #[error("Failed to register memory address range with the userfaultfd object: {0}")] + /// Failed to register memory address range with the userfaultfd object: {0} Register(userfaultfd::Error), - /// Failed to connect to UDS Unix stream. - #[error("Failed to connect to UDS Unix stream: {0}")] + /// Failed to connect to UDS Unix stream: {0} Connect(#[from] std::io::Error), - /// Failed to send file descriptor. - #[error("Failed to sends file descriptor: {0}")] + /// Failed to sends file descriptor: {0} Send(#[from] utils::errno::Error), } diff --git a/src/vmm/src/resources.rs b/src/vmm/src/resources.rs index f2212838ab85..351ab02c0e0f 100644 --- a/src/vmm/src/resources.rs +++ b/src/vmm/src/resources.rs @@ -29,46 +29,33 @@ use crate::vmm_config::net::*; use crate::vmm_config::vsock::*; /// Errors encountered when configuring microVM resources. -#[derive(Debug, thiserror::Error, derive_more::From)] +#[derive(Debug, thiserror::Error, displaydoc::Display, derive_more::From)] pub enum ResourcesError { - /// Balloon device configuration error. - #[error("Balloon device error: {0}")] + /// Balloon device error: {0} BalloonDevice(BalloonConfigError), - /// Block device configuration error. - #[error("Block device error: {0}")] + /// Block device error: {0} BlockDevice(DriveError), - /// Boot source configuration error. - #[error("Boot source error: {0}")] + /// Boot source error: {0} BootSource(BootSourceConfigError), - /// File operation error. - #[error("File operation error: {0}")] + /// File operation error: {0} File(std::io::Error), - /// JSON is invalid. - #[error("Invalid JSON: {0}")] + /// Invalid JSON: {0} InvalidJson(serde_json::Error), - /// Logger configuration error. - #[error("Logger error: {0}")] + /// Logger error: {0} Logger(LoggerConfigError), - /// Metrics system configuration error. - #[error("Metrics error: {0}")] + /// Metrics error: {0} Metrics(MetricsConfigError), - /// MMDS error. - #[error("MMDS error: {0}")] + /// MMDS error: {0} Mmds(mmds::data_store::Error), - /// MMDS configuration error. - #[error("MMDS config error: {0}")] + /// MMDS config error: {0} MmdsConfig(MmdsConfigError), - /// Net device configuration error. - #[error("Network device error: {0}")] + /// Network device error: {0} NetDevice(NetworkInterfaceError), - /// microVM vCpus or memory configuration error. - #[error("VM config error: {0}")] + /// VM config error: {0} VmConfig(VmConfigError), - /// Vsock device configuration error. - #[error("Vsock device error: {0}")] + /// Vsock device error: {0} VsockDevice(VsockConfigError), - /// Entropy device configuration error. - #[error("Entropy device error: {0}")] + /// Entropy device error: {0} EntropyDevice(EntropyDeviceError), } diff --git a/src/vmm/src/rpc_interface.rs b/src/vmm/src/rpc_interface.rs index 255aa8242e85..1e50daf9870a 100644 --- a/src/vmm/src/rpc_interface.rs +++ b/src/vmm/src/rpc_interface.rs @@ -133,71 +133,53 @@ pub enum VmmAction { } /// Wrapper for all errors associated with VMM actions. -#[derive(Debug, thiserror::Error, derive_more::From)] +#[derive(Debug, thiserror::Error, displaydoc::Display, derive_more::From)] pub enum VmmActionError { - /// The action `SetBalloonDevice` failed because of bad user input. - #[error("{0}")] + /// {0} BalloonConfig(BalloonConfigError), - /// The action `ConfigureBootSource` failed because of bad user input. - #[error("{0}")] + /// {0} BootSource(BootSourceConfigError), - /// The action `CreateSnapshot` failed. - #[error("{0}")] + /// {0} CreateSnapshot(CreateSnapshotError), - /// The action `ConfigureCpu` failed. - #[error("{0}")] + /// {0} ConfigureCpu(GuestConfigError), - /// One of the actions `InsertBlockDevice` or `UpdateBlockDevicePath` - /// failed because of bad user input. - #[error("{0}")] + // One of the actions `InsertBlockDevice` or `UpdateBlockDevicePath` + /// {0} DriveConfig(DriveError), - /// `SetEntropyDevice` action failed because of bad user input. - #[error("{0}")] + /// {0} EntropyDevice(EntropyDeviceError), - /// Internal Vmm error. - #[error("Internal Vmm error: {0}")] + /// Internal Vmm error: {0} InternalVmm(VmmError), - /// Loading a microVM snapshot failed. - #[error("Load microVM snapshot error: {0}")] + /// Load microVM snapshot error: {0} LoadSnapshot(LoadSnapshotError), - /// The action `ConfigureLogger` failed because of bad user input. - #[error("{0}")] + /// {0} Logger(LoggerConfigError), - /// One of the actions `GetVmConfiguration` or `UpdateVmConfiguration` failed because of bad - /// input. - #[error("{0}")] + // One of the actions `GetVmConfiguration` or `UpdateVmConfiguration` failed because of bad + /// {0} MachineConfig(VmConfigError), - /// The action `ConfigureMetrics` failed because of bad user input. - #[error("{0}")] + /// {0} Metrics(MetricsConfigError), - /// One of the `GetMmds`, `PutMmds` or `PatchMmds` actions failed. + // One of the `GetMmds`, `PutMmds` or `PatchMmds` actions failed. #[from(ignore)] - #[error("{0}")] + /// {0} Mmds(data_store::Error), - /// The action `SetMmdsConfiguration` failed because of bad user input. - #[error("{0}")] + /// {0} MmdsConfig(MmdsConfigError), - /// Mmds contents update failed due to exceeding the data store limit. + // Mmds contents update failed due to exceeding the data store limit. #[from(ignore)] - #[error("{0}")] + /// {0} MmdsLimitExceeded(data_store::Error), - /// The action `InsertNetworkDevice` failed because of bad user input. - #[error("{0}")] + /// {0} NetworkConfig(NetworkInterfaceError), - /// The requested operation is not supported. - #[error("The requested operation is not supported: {0}")] + /// The requested operation is not supported: {0} NotSupported(String), /// The requested operation is not supported after starting the microVM. - #[error("The requested operation is not supported after starting the microVM.")] OperationNotSupportedPostBoot, /// The requested operation is not supported before starting the microVM. - #[error("The requested operation is not supported before starting the microVM.")] OperationNotSupportedPreBoot, - /// The action `StartMicroVm` failed because of an internal error. - #[error("{0}")] + /// {0} StartMicrovm(StartMicrovmError), - /// The action `SetVsockDevice` failed because of bad user input. - #[error("{0}")] + /// {0} VsockConfig(VsockConfigError), } @@ -296,16 +278,13 @@ impl MmdsRequestHandler for PrebootApiController<'_> { } /// Error type for [`PrebootApiController::load_snapshot`] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum LoadSnapshotError { /// Loading a microVM snapshot not allowed after configuring boot-specific resources. - #[error("Loading a microVM snapshot not allowed after configuring boot-specific resources.")] LoadSnapshotNotAllowed, - /// Failed to restore from snapshot. - #[error("Failed to restore from snapshot: {0}")] + /// Failed to restore from snapshot: {0} RestoreFromSnapshot(#[from] RestoreFromSnapshotError), - /// Failed to resume microVM. - #[error("Failed to resume microVM: {0}")] + /// Failed to resume microVM: {0} ResumeMicrovm(#[from] VmmError), } diff --git a/src/vmm/src/vmm_config/balloon.rs b/src/vmm/src/vmm_config/balloon.rs index 20272daecb82..bc4cee32e452 100644 --- a/src/vmm/src/vmm_config/balloon.rs +++ b/src/vmm/src/vmm_config/balloon.rs @@ -12,29 +12,22 @@ use crate::devices::virtio::{Balloon, BalloonConfig}; type MutexBalloon = Arc>; /// Errors associated with the operations allowed on the balloon. -#[derive(Debug, derive_more::From, thiserror::Error)] +#[derive(Debug, derive_more::From, thiserror::Error, displaydoc::Display)] pub enum BalloonConfigError { - /// The user made a request on an inexistent balloon device. - #[error("No balloon device found.")] + /// No balloon device found. DeviceNotFound, - /// Device not activated yet. - #[error("Device is inactive, check if balloon driver is enabled in guest kernel.")] + /// Device is inactive, check if balloon driver is enabled in guest kernel. DeviceNotActive, - /// The user tried to enable/disable the statistics after boot. - #[error("Cannot enable/disable the statistics after boot.")] + /// Cannot enable/disable the statistics after boot. InvalidStatsUpdate, /// Amount of pages requested is too large. - #[error("Amount of pages requested is too large.")] TooManyPagesRequested, - /// The user polled the statistics of a balloon device that - /// does not have the statistics enabled. - #[error("Statistics for the balloon device are not enabled")] + // The user polled the statistics of a balloon device that + /// Statistics for the balloon device are not enabled StatsNotFound, - /// Failed to create a balloon device. - #[error("Error creating the balloon device: {0:?}")] + /// Error creating the balloon device: {0:?} CreateFailure(crate::devices::virtio::balloon::BalloonError), - /// Failed to update the configuration of the ballon device. - #[error("Error updating the balloon device configuration: {0:?}")] + /// Error updating the balloon device configuration: {0:?} UpdateFailure(std::io::Error), } diff --git a/src/vmm/src/vmm_config/boot_source.rs b/src/vmm/src/vmm_config/boot_source.rs index 7e3ec35e8112..d5f6a1f3bdec 100644 --- a/src/vmm/src/vmm_config/boot_source.rs +++ b/src/vmm/src/vmm_config/boot_source.rs @@ -37,16 +37,13 @@ pub struct BootSourceConfig { } /// Errors associated with actions on `BootSourceConfig`. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum BootSourceConfigError { - /// The kernel file cannot be opened. - #[error("The kernel file cannot be opened: {0}")] + /// The kernel file cannot be opened: {0} InvalidKernelPath(io::Error), - /// The initrd file cannot be opened. - #[error("The initrd file cannot be opened due to invalid path or invalid permissions. {0}")] + /// The initrd file cannot be opened due to invalid path or invalid permissions. {0} InvalidInitrdPath(io::Error), - /// The kernel command line is invalid. - #[error("The kernel command line is invalid: {0}")] + /// The kernel command line is invalid: {0} InvalidKernelCommandLine(String), } diff --git a/src/vmm/src/vmm_config/drive.rs b/src/vmm/src/vmm_config/drive.rs index 7af40d46609e..f3a98837eb13 100644 --- a/src/vmm/src/vmm_config/drive.rs +++ b/src/vmm/src/vmm_config/drive.rs @@ -18,22 +18,17 @@ pub use crate::devices::virtio::CacheType; use crate::VmmError; /// Errors associated with the operations allowed on a drive. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum DriveError { - /// Could not create a Block Device. - #[error("Unable to create the block device: {0:?}")] + /// Unable to create the block device: {0:?} CreateBlockDevice(BlockError), - /// Failed to create a `RateLimiter` object. - #[error("Cannot create RateLimiter: {0}")] + /// Cannot create RateLimiter: {0} CreateRateLimiter(io::Error), - /// Error during block device update (patch). - #[error("Unable to patch the block device: {0}")] + /// Unable to patch the block device: {0} DeviceUpdate(VmmError), - /// The block device path is invalid. - #[error("Invalid block device path: {0}")] + /// Invalid block device path: {0} InvalidBlockDevicePath(String), - /// A root block device was already added. - #[error("A root block device already exists!")] + /// A root block device already exists! RootBlockDeviceAlreadyAdded, } diff --git a/src/vmm/src/vmm_config/entropy.rs b/src/vmm/src/vmm_config/entropy.rs index d443f7dcda8a..439657c90f69 100644 --- a/src/vmm/src/vmm_config/entropy.rs +++ b/src/vmm/src/vmm_config/entropy.rs @@ -29,13 +29,11 @@ impl From<&Entropy> for EntropyDeviceConfig { /// Errors that can occur while handling configuration for /// an entropy device -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum EntropyDeviceError { - /// Error while create an entropy device - #[error("Could not create Entropy device: {0}")] + /// Could not create Entropy device: {0} CreateDevice(#[from] EntropyError), - /// Error while creating rate limiter from configuration - #[error("Could not create RateLimiter from configuration: {0}")] + /// Could not create RateLimiter from configuration: {0} CreateRateLimiter(#[from] std::io::Error), } diff --git a/src/vmm/src/vmm_config/machine_config.rs b/src/vmm/src/vmm_config/machine_config.rs index 236c64b9d700..fcaded946365 100644 --- a/src/vmm/src/vmm_config/machine_config.rs +++ b/src/vmm/src/vmm_config/machine_config.rs @@ -13,29 +13,17 @@ pub const DEFAULT_MEM_SIZE_MIB: usize = 128; pub const MAX_SUPPORTED_VCPUS: u8 = 32; /// Errors associated with configuring the microVM. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum VmConfigError { - /// The memory size is smaller than the target size set in the balloon device configuration. - #[error( - "The memory size (MiB) is smaller than the previously set balloon device target size." - )] + /// The memory size (MiB) is smaller than the previously set balloon device target size. IncompatibleBalloonSize, - /// The memory size is invalid. The memory can only be an unsigned integer. - #[error("The memory size (MiB) is invalid.")] + /// The memory size (MiB) is invalid. InvalidMemorySize, - /// The vcpu count is invalid. When SMT is enabled, the `cpu_count` must be either - /// 1 or an even number. - #[error( - "The vCPU number is invalid! The vCPU number can only be 1 or an even number when SMT is \ - enabled." - )] + #[rustfmt::skip] + #[doc = "The vCPU number is invalid! The vCPU number can only be 1 or an even number when SMT is enabled."] InvalidVcpuCount, - /// Could not get the config of the balloon device from the VM resources, even though a - /// balloon device was previously installed. - #[error( - "Could not get the configuration of the previously installed balloon device to validate \ - the memory size." - )] + #[rustfmt::skip] + #[doc = "Could not get the configuration of the previously installed balloon device to validate the memory size."] InvalidVmState, } diff --git a/src/vmm/src/vmm_config/mmds.rs b/src/vmm/src/vmm_config/mmds.rs index d2c0a6f46195..eeeb5fd79c8c 100644 --- a/src/vmm/src/vmm_config/mmds.rs +++ b/src/vmm/src/vmm_config/mmds.rs @@ -38,22 +38,15 @@ impl MmdsConfig { } /// MMDS configuration related errors. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum MmdsConfigError { - /// The network interfaces list provided is empty. - #[error("The list of network interface IDs that allow forwarding MMDS requests is empty.")] + /// The list of network interface IDs that allow forwarding MMDS requests is empty. EmptyNetworkIfaceList, - /// The provided IPv4 address is not link-local valid. - #[error("The MMDS IPv4 address is not link local.")] + /// The MMDS IPv4 address is not link local. InvalidIpv4Addr, - /// The network interfaces list provided contains IDs that - /// does not correspond to any existing network interface. - #[error( - "The list of network interface IDs provided contains at least one ID that does not \ - correspond to any existing network interface." - )] + #[rustfmt::skip] + #[doc = "The list of network interface IDs provided contains at least one ID that does not correspond to any existing network interface."] InvalidNetworkInterfaceId, - /// MMDS version could not be configured. - #[error("The MMDS could not be configured to version {0}: {1}")] + /// The MMDS could not be configured to version {0}: {1} MmdsVersion(MmdsVersion, data_store::Error), } diff --git a/src/vmm/src/vmm_config/net.rs b/src/vmm/src/vmm_config/net.rs index 6f21ac23064a..00dcc5354601 100644 --- a/src/vmm/src/vmm_config/net.rs +++ b/src/vmm/src/vmm_config/net.rs @@ -60,22 +60,17 @@ pub struct NetworkInterfaceUpdateConfig { } /// Errors associated with the operations allowed on a net device. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum NetworkInterfaceError { - /// Could not create the network device. - #[error("Could not create the network device: {0}")] + /// Could not create the network device: {0} CreateNetworkDevice(#[from] crate::devices::virtio::net::NetError), - /// Failed to create a `RateLimiter` object - #[error("Cannot create the rate limiter: {0}")] + /// Cannot create the rate limiter: {0} CreateRateLimiter(#[from] std::io::Error), - /// Error during interface update (patch). - #[error("Unable to update the net device: {0}")] + /// Unable to update the net device: {0} DeviceUpdate(#[from] VmmError), - /// The MAC address is already in use. - #[error("The MAC address is already in use: {0}")] + /// The MAC address is already in use: {0} GuestMacAddressInUse(String), - /// Cannot open/create the tap device. - #[error("Cannot open/create the tap device: {0}")] + /// Cannot open/create the tap device: {0} OpenTap(#[from] TapError), } diff --git a/src/vmm/src/vmm_config/vsock.rs b/src/vmm/src/vmm_config/vsock.rs index 0e30b5322e1e..783f30d5a4fb 100644 --- a/src/vmm/src/vmm_config/vsock.rs +++ b/src/vmm/src/vmm_config/vsock.rs @@ -11,13 +11,11 @@ use crate::devices::virtio::{Vsock, VsockError, VsockUnixBackend, VsockUnixBacke type MutexVsockUnix = Arc>>; /// Errors associated with `NetworkInterfaceConfig`. -#[derive(Debug, derive_more::From, thiserror::Error)] +#[derive(Debug, derive_more::From, thiserror::Error, displaydoc::Display)] pub enum VsockConfigError { - /// Failed to create the backend for the vsock device. - #[error("Cannot create backend for vsock device: {0:?}")] + /// Cannot create backend for vsock device: {0:?} CreateVsockBackend(VsockUnixBackendError), - /// Failed to create the vsock device. - #[error("Cannot create vsock device: {0:?}")] + /// Cannot create vsock device: {0:?} CreateVsockDevice(VsockError), } diff --git a/src/vmm/src/vstate/vcpu/aarch64.rs b/src/vmm/src/vstate/vcpu/aarch64.rs index 5df310e181f8..730e07461c97 100644 --- a/src/vmm/src/vstate/vcpu/aarch64.rs +++ b/src/vmm/src/vstate/vcpu/aarch64.rs @@ -25,31 +25,23 @@ use crate::vstate::vcpu::VcpuEmulation; use crate::vstate::vm::Vm; /// Errors associated with the wrappers over KVM ioctls. -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum KvmVcpuError { - /// Error configuring the vcpu registers. - #[error("Error configuring the vcpu registers: {0}")] + /// Error configuring the vcpu registers: {0} ConfigureRegisters(ArchError), - /// Error creating vcpu. - #[error("Error creating vcpu: {0}")] + /// Error creating vcpu: {0} CreateVcpu(kvm_ioctls::Error), - /// Failed to dump CPU configuration. - #[error("Failed to dump CPU configuration: {0}")] + /// Failed to dump CPU configuration: {0} DumpCpuConfig(ArchError), - /// Error getting the vcpu preferred target. - #[error("Error getting the vcpu preferred target: {0}")] + /// Error getting the vcpu preferred target: {0} GetPreferredTarget(kvm_ioctls::Error), - /// Error initializing the vcpu. - #[error("Error initializing the vcpu: {0}")] + /// Error initializing the vcpu: {0} Init(kvm_ioctls::Error), - /// Error applying template. - #[error("Error applying template: {0}")] + /// Error applying template: {0} ApplyCpuTemplate(ArchError), - /// Failed to restore the state of the vcpu. - #[error("Failed to restore the state of the vcpu: {0}")] + /// Failed to restore the state of the vcpu: {0} RestoreState(ArchError), - /// Failed to save the state of the vcpu. - #[error("Failed to save the state of the vcpu: {0}")] + /// Failed to save the state of the vcpu: {0} SaveState(ArchError), } diff --git a/src/vmm/src/vstate/vcpu/mod.rs b/src/vmm/src/vstate/vcpu/mod.rs index c2b250ddff4b..8707cd4c59ae 100644 --- a/src/vmm/src/vstate/vcpu/mod.rs +++ b/src/vmm/src/vstate/vcpu/mod.rs @@ -44,31 +44,23 @@ pub use x86_64::{KvmVcpuError, *}; pub const VCPU_RTSIG_OFFSET: i32 = 0; /// Errors associated with the wrappers over KVM ioctls. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum VcpuError { - /// Error creating vcpu config. - #[error("Error creating vcpu config: {0}")] + /// Error creating vcpu config: {0} VcpuConfig(GuestConfigError), - /// Error triggered by the KVM subsystem. - #[error("Received error signaling kvm exit: {0}")] + /// Received error signaling kvm exit: {0} FaultyKvmExit(String), - /// Failed to signal Vcpu. - #[error("Failed to signal vcpu: {0}")] + /// Failed to signal vcpu: {0} SignalVcpu(utils::errno::Error), - /// Kvm Exit is not handled by our implementation. - #[error("Unexpected kvm exit received: {0}")] + /// Unexpected kvm exit received: {0} UnhandledKvmExit(String), - /// Wrapper over error triggered by some vcpu action. - #[error("Failed to run action on vcpu: {0}")] + /// Failed to run action on vcpu: {0} VcpuResponse(KvmVcpuError), - /// Cannot spawn a new vCPU thread. - #[error("Cannot spawn a new vCPU thread: {0}")] + /// Cannot spawn a new vCPU thread: {0} VcpuSpawn(io::Error), - /// Cannot cleanly initialize vcpu TLS. - #[error("Cannot clean init vcpu TLS")] + /// Cannot clean init vcpu TLS VcpuTlsInit, - /// Vcpu not present in TLS. - #[error("Vcpu not present in TLS")] + /// Vcpu not present in TLS VcpuTlsNotPresent, } diff --git a/src/vmm/src/vstate/vcpu/x86_64.rs b/src/vmm/src/vstate/vcpu/x86_64.rs index 818c4a4e13d9..a1915c9080b4 100644 --- a/src/vmm/src/vstate/vcpu/x86_64.rs +++ b/src/vmm/src/vstate/vcpu/x86_64.rs @@ -32,106 +32,73 @@ use crate::vstate::vm::Vm; const TSC_KHZ_TOL: f64 = 250.0 / 1_000_000.0; /// Errors associated with the wrappers over KVM ioctls. -#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)] pub enum KvmVcpuError { - /// Failed to convert CPUID type. - #[error("Failed to convert `kvm_bindings::CpuId` to `Cpuid`: {0}")] + /// Failed to convert `kvm_bindings::CpuId` to `Cpuid`: {0} ConvertCpuidType(#[from] cpuid::CpuidTryFromKvmCpuid), - /// A FamStructWrapper operation has failed. - #[error("Failed FamStructWrapper operation: {0:?}")] + /// Failed FamStructWrapper operation: {0:?} Fam(#[from] utils::fam::Error), - /// Error configuring the floating point related registers - #[error("Error configuring the floating point related registers: {0:?}")] + /// Error configuring the floating point related registers: {0:?} FpuConfiguration(crate::arch::x86_64::regs::RegsError), - /// Failed to get dumpable MSR index list. - #[error("Failed to get dumpable MSR index list: {0}")] + /// Failed to get dumpable MSR index list: {0} GetMsrsToDump(#[from] crate::arch::x86_64::msr::MsrError), - /// Cannot set the local interruption due to bad configuration. - #[error("Cannot set the local interruption due to bad configuration: {0:?}")] + /// Cannot set the local interruption due to bad configuration: {0:?} LocalIntConfiguration(crate::arch::x86_64::interrupts::InterruptError), - /// Error configuring the general purpose registers - #[error("Error configuring the general purpose registers: {0:?}")] + /// Error configuring the general purpose registers: {0:?} RegsConfiguration(crate::arch::x86_64::regs::RegsError), - /// Error configuring the special registers - #[error("Error configuring the special registers: {0:?}")] + /// Error configuring the special registers: {0:?} SregsConfiguration(crate::arch::x86_64::regs::RegsError), - /// Cannot open the VCPU file descriptor. - #[error("Cannot open the VCPU file descriptor: {0}")] + /// Cannot open the VCPU file descriptor: {0} VcpuFd(kvm_ioctls::Error), - /// Failed to get KVM vcpu debug regs. - #[error("Failed to get KVM vcpu debug regs: {0}")] + /// Failed to get KVM vcpu debug regs: {0} VcpuGetDebugRegs(kvm_ioctls::Error), - /// Failed to get KVM vcpu lapic. - #[error("Failed to get KVM vcpu lapic: {0}")] + /// Failed to get KVM vcpu lapic: {0} VcpuGetLapic(kvm_ioctls::Error), - /// Failed to get KVM vcpu mp state. - #[error("Failed to get KVM vcpu mp state: {0}")] + /// Failed to get KVM vcpu mp state: {0} VcpuGetMpState(kvm_ioctls::Error), - /// The number of MSRS returned by the kernel is unexpected. - #[error("Unexpected number of MSRS reported by the kernel")] + /// Unexpected number of MSRS reported by the kernel VcpuGetMsrsIncomplete, - /// Failed to get KVM vcpu msrs. - #[error("Failed to get KVM vcpu msrs: {0}")] + /// Failed to get KVM vcpu msrs: {0} VcpuGetMsrs(kvm_ioctls::Error), - /// Failed to get KVM vcpu regs. - #[error("Failed to get KVM vcpu regs: {0}")] + /// Failed to get KVM vcpu regs: {0} VcpuGetRegs(kvm_ioctls::Error), - /// Failed to get KVM vcpu sregs. - #[error("Failed to get KVM vcpu sregs: {0}")] + /// Failed to get KVM vcpu sregs: {0} VcpuGetSregs(kvm_ioctls::Error), - /// Failed to get KVM vcpu event. - #[error("Failed to get KVM vcpu event: {0}")] + /// Failed to get KVM vcpu event: {0} VcpuGetVcpuEvents(kvm_ioctls::Error), - /// Failed to get KVM vcpu xcrs. - #[error("Failed to get KVM vcpu xcrs: {0}")] + /// Failed to get KVM vcpu xcrs: {0} VcpuGetXcrs(kvm_ioctls::Error), - /// Failed to get KVM vcpu xsave. - #[error("Failed to get KVM vcpu xsave: {0}")] + /// Failed to get KVM vcpu xsave: {0} VcpuGetXsave(kvm_ioctls::Error), - /// Failed to get KVM vcpu cpuid. - #[error("Failed to get KVM vcpu cpuid: {0}")] + /// Failed to get KVM vcpu cpuid: {0} VcpuGetCpuid(kvm_ioctls::Error), - /// Failed to get KVM TSC freq. - #[error("Failed to get KVM TSC frequency: {0}")] + /// Failed to get KVM TSC frequency: {0} VcpuGetTsc(kvm_ioctls::Error), - /// Failed to set KVM vcpu cpuid. - #[error("Failed to set KVM vcpu cpuid: {0}")] + /// Failed to set KVM vcpu cpuid: {0} VcpuSetCpuid(kvm_ioctls::Error), - /// Failed to set KVM vcpu debug regs. - #[error("Failed to set KVM vcpu debug regs: {0}")] + /// Failed to set KVM vcpu debug regs: {0} VcpuSetDebugRegs(kvm_ioctls::Error), - /// Failed to set KVM vcpu lapic. - #[error("Failed to set KVM vcpu lapic: {0}")] + /// Failed to set KVM vcpu lapic: {0} VcpuSetLapic(kvm_ioctls::Error), - /// Failed to set KVM vcpu mp state. - #[error("Failed to set KVM vcpu mp state: {0}")] + /// Failed to set KVM vcpu mp state: {0} VcpuSetMpState(kvm_ioctls::Error), - /// Failed to set KVM vcpu msrs. - #[error("Failed to set KVM vcpu msrs: {0}")] + /// Failed to set KVM vcpu msrs: {0} VcpuSetMsrs(kvm_ioctls::Error), - /// Failed to set all KVM vcpu MSRs. Only a partial set was done. - #[error("Failed to set all KVM MSRs for this vCPU. Only a partial write was done.")] + /// Failed to set all KVM MSRs for this vCPU. Only a partial write was done. VcpuSetMsrsIncomplete, - /// Failed to set KVM vcpu regs. - #[error("Failed to set KVM vcpu regs: {0}")] + /// Failed to set KVM vcpu regs: {0} VcpuSetRegs(kvm_ioctls::Error), - /// Failed to set KVM vcpu sregs. - #[error("Failed to set KVM vcpu sregs: {0}")] + /// Failed to set KVM vcpu sregs: {0} VcpuSetSregs(kvm_ioctls::Error), - /// Failed to set KVM vcpu event. - #[error("Failed to set KVM vcpu event: {0}")] + /// Failed to set KVM vcpu event: {0} VcpuSetVcpuEvents(kvm_ioctls::Error), - /// Failed to set KVM vcpu xcrs. - #[error("Failed to set KVM vcpu xcrs: {0}")] + /// Failed to set KVM vcpu xcrs: {0} VcpuSetXcrs(kvm_ioctls::Error), - /// Failed to set KVM vcpu xsave. - #[error("Failed to set KVM vcpu xsave: {0}")] + /// Failed to set KVM vcpu xsave: {0} VcpuSetXsave(kvm_ioctls::Error), - /// Failed to set KVM TSC freq. - #[error("Failed to set KVM TSC frequency: {0}")] + /// Failed to set KVM TSC frequency: {0} VcpuSetTsc(kvm_ioctls::Error), - /// Failed to apply CPU template. - #[error("Failed to apply CPU template")] + /// Failed to apply CPU template VcpuTemplateError, } @@ -146,31 +113,23 @@ pub struct GetTscError(utils::errno::Error); pub struct SetTscError(#[from] kvm_ioctls::Error); /// Error type for [`KvmVcpu::configure`]. -#[derive(Debug, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, Eq, PartialEq)] pub enum KvmVcpuConfigureError { - /// Failed to convert `Cpuid` to `kvm_bindings::CpuId`. - #[error("Failed to convert `Cpuid` to `kvm_bindings::CpuId`: {0}")] + /// Failed to convert `Cpuid` to `kvm_bindings::CpuId`: {0} ConvertCpuidType(#[from] utils::fam::Error), - /// Failed to apply modifications to CPUID. - #[error("Failed to apply modifications to CPUID: {0}")] + /// Failed to apply modifications to CPUID: {0} NormalizeCpuidError(#[from] cpuid::NormalizeCpuidError), - /// Failed to set CPUID. - #[error("Failed to set CPUID: {0}")] + /// Failed to set CPUID: {0} SetCpuid(#[from] utils::errno::Error), - /// Failed to set MSRs. - #[error("Failed to set MSRs: {0}")] + /// Failed to set MSRs: {0} SetMsrs(#[from] MsrError), - /// Failed to setup registers. - #[error("Failed to setup registers: {0}")] + /// Failed to setup registers: {0} SetupRegisters(#[from] SetupRegistersError), - /// Failed to setup FPU. - #[error("Failed to setup FPU: {0}")] + /// Failed to setup FPU: {0} SetupFpu(#[from] SetupFpuError), - /// Failed to setup special registers. - #[error("Failed to setup special registers: {0}")] + /// Failed to setup special registers: {0} SetupSpecialRegisters(#[from] SetupSpecialRegistersError), - /// Failed to setup special registers. - #[error("Failed to configure LAPICs: {0}")] + /// Failed to configure LAPICs: {0} SetLint(#[from] interrupts::InterruptError), } diff --git a/src/vmm/src/vstate/vm.rs b/src/vmm/src/vstate/vm.rs index 64ec657ae5e7..6528e50847ff 100644 --- a/src/vmm/src/vstate/vm.rs +++ b/src/vmm/src/vstate/vm.rs @@ -32,7 +32,7 @@ pub enum VmError { /// The host kernel reports an invalid KVM API version. #[error("The host kernel reports an invalid KVM API version: {0}")] ApiVersion(i32), - /// Cannot initialize the KVM context due to missing capabilities. + /// Missing KVM capabilities. #[error("Missing KVM capabilities: {0:x?}")] Capabilities(u32), /// Cannot initialize the KVM context. @@ -53,13 +53,13 @@ pub enum VmError { #[error("Failed to get MSR index list to save into snapshots: {0}")] GetMsrsToSave(#[from] crate::arch::x86_64::msr::MsrError), /// The number of configured slots is bigger than the maximum reported by KVM. - #[error("The number of configured slots is bigger than the maximum reported by KVM")] + #[error("The number of configured slots is bigger than the maximum reported by KVM.")] NotEnoughMemorySlots, /// Cannot set the memory regions. #[error("Cannot set the memory regions: {0}")] SetUserMemoryRegion(kvm_ioctls::Error), #[cfg(target_arch = "aarch64")] - /// Cannot create the global interrupt controller. + /// Error creating the global interrupt controller. #[error("Error creating the global interrupt controller: {0:?}")] VmCreateGIC(crate::arch::aarch64::gic::GicError), /// Cannot open the VM file descriptor. @@ -105,36 +105,29 @@ pub enum VmError { /// Error type for [`Vm::restore_state`] #[allow(missing_docs)] #[cfg(target_arch = "x86_64")] -#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[derive(Debug, thiserror::Error, displaydoc::Display, PartialEq, Eq)] pub enum RestoreStateError { - #[error("{0}")] + /// {0} SetPit2(kvm_ioctls::Error), - /// SetClock. - #[error("{0}")] + /// {0} SetClock(kvm_ioctls::Error), - /// SetIrqChipPicMaster. - #[error("{0}")] + /// {0} SetIrqChipPicMaster(kvm_ioctls::Error), - /// SetIrqChipPicSlave. - #[error("{0}")] + /// {0} SetIrqChipPicSlave(kvm_ioctls::Error), - /// SetIrqChipIoAPIC. - #[error("{0}")] + /// {0} SetIrqChipIoAPIC(kvm_ioctls::Error), - /// Vm Error - #[error("{0}")] + /// {0} VmError(VmError), } /// Error type for [`Vm::restore_state`] #[cfg(target_arch = "aarch64")] -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum RestoreStateError { - /// GIC Error - #[error("{0}")] + /// {0} GicError(crate::arch::aarch64::gic::GicError), - /// Vm Error - #[error("{0}")] + /// {0} VmError(VmError), }