diff --git a/bootstore/src/schemes/v0/fsm.rs b/bootstore/src/schemes/v0/fsm.rs index 4f2bcc2d11e..5f60b34c777 100644 --- a/bootstore/src/schemes/v0/fsm.rs +++ b/bootstore/src/schemes/v0/fsm.rs @@ -12,13 +12,13 @@ use super::request_manager::ShareAcks; use super::{ - create_pkgs, Envelope, FsmConfig, LearnedSharePkg, Msg, MsgError, RackUuid, - Request, RequestManager, RequestType, Response, ResponseType, Share, - SharePkg, Shares, TrackableRequest, + Envelope, FsmConfig, LearnedSharePkg, Msg, MsgError, RackUuid, Request, + RequestManager, RequestType, Response, ResponseType, Share, SharePkg, + Shares, TrackableRequest, create_pkgs, }; +use crate::Sha3_256Digest; use crate::schemes::v0::share_pkg::SharePkgCommon; use crate::trust_quorum::{RackSecret, TrustQuorumError}; -use crate::Sha3_256Digest; use secrecy::ExposeSecret; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -131,7 +131,9 @@ pub enum ApiError { #[error("critical: failed to decrypt extra shares")] FailedToDecryptExtraShares, - #[error("unexpected response ({msg}) from ({from}) in state ({state}) with request_id ({request_id})")] + #[error( + "unexpected response ({msg}) from ({from}) in state ({state}) with request_id ({request_id})" + )] UnexpectedResponse { from: Baseboard, state: &'static str, @@ -139,7 +141,9 @@ pub enum ApiError { msg: &'static str, }, - #[error("error response received from ({from}) in state ({state}) with request_id ({request_id}): {error:?}")] + #[error( + "error response received from ({from}) in state ({state}) with request_id ({request_id}): {error:?}" + )] ErrorResponseReceived { from: Baseboard, state: &'static str, @@ -360,11 +364,7 @@ impl Fsm { } } } - if errors.is_empty() { - Ok(()) - } else { - Err(errors) - } + if errors.is_empty() { Ok(()) } else { Err(errors) } } /// A peer has been connected. diff --git a/bootstore/src/schemes/v0/mod.rs b/bootstore/src/schemes/v0/mod.rs index ece0732182a..3bdd4a49a4c 100644 --- a/bootstore/src/schemes/v0/mod.rs +++ b/bootstore/src/schemes/v0/mod.rs @@ -25,7 +25,7 @@ pub use messages::{ }; pub use peer::{Config, Node, NodeHandle, NodeRequestError, Status}; pub use request_manager::{RequestManager, TrackableRequest}; -pub use share_pkg::{create_pkgs, LearnedSharePkg, SharePkg, SharePkgCommon}; +pub use share_pkg::{LearnedSharePkg, SharePkg, SharePkgCommon, create_pkgs}; pub use storage::NetworkConfig; /// The current version of supported messages within the v0 scheme diff --git a/bootstore/src/schemes/v0/peer.rs b/bootstore/src/schemes/v0/peer.rs index 1d676953ac2..31ae909e83a 100644 --- a/bootstore/src/schemes/v0/peer.rs +++ b/bootstore/src/schemes/v0/peer.rs @@ -5,9 +5,9 @@ //! The entrypoint of the v0 scheme for use by bootstrap agent use super::peer_networking::{ - spawn_accepted_connection_management_task, spawn_connection_initiator_task, AcceptedConnHandle, ConnToMainMsg, ConnToMainMsgInner, MainToConnMsg, Msg, - PeerConnHandle, + PeerConnHandle, spawn_accepted_connection_management_task, + spawn_connection_initiator_task, }; use super::storage::{NetworkConfig, PersistentFsmState}; use super::{ApiError, ApiOutput, Fsm, FsmConfig, RackUuid}; @@ -15,14 +15,14 @@ use crate::trust_quorum::RackSecret; use camino::Utf8PathBuf; use derive_more::From; use sled_hardware_types::Baseboard; -use slog::{error, info, o, warn, Logger}; +use slog::{Logger, error, info, o, warn}; use std::collections::{BTreeMap, BTreeSet}; use std::net::{SocketAddr, SocketAddrV6}; use std::time::Duration; use thiserror::Error; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::{mpsc, oneshot}; -use tokio::time::{interval, Instant, MissedTickBehavior}; +use tokio::time::{Instant, MissedTickBehavior, interval}; #[derive(Debug, Clone)] pub struct Config { @@ -1172,12 +1172,12 @@ mod tests { learn_timeout: Duration::from_secs(5), rack_init_timeout: Duration::from_secs(10), rack_secret_request_timeout: Duration::from_secs(1), - fsm_state_ledger_paths: vec![tempdir - .path() - .join(&fsm_file)], - network_config_ledger_paths: vec![tempdir - .path() - .join(&network_file)], + fsm_state_ledger_paths: vec![ + tempdir.path().join(&fsm_file), + ], + network_config_ledger_paths: vec![ + tempdir.path().join(&network_file), + ], }; TestNode::new(config, log.clone()) @@ -1240,14 +1240,12 @@ mod tests { learn_timeout: Duration::from_secs(5), rack_init_timeout: Duration::from_secs(10), rack_secret_request_timeout: Duration::from_secs(1), - fsm_state_ledger_paths: vec![self - .tempdir - .path() - .join(&fsm_file)], - network_config_ledger_paths: vec![self - .tempdir - .path() - .join(&network_file)], + fsm_state_ledger_paths: vec![ + self.tempdir.path().join(&fsm_file), + ], + network_config_ledger_paths: vec![ + self.tempdir.path().join(&network_file), + ], }; self.learner = Some(TestNode::new(config, self.log.clone())); diff --git a/bootstore/src/schemes/v0/peer_networking.rs b/bootstore/src/schemes/v0/peer_networking.rs index 9cd81a6d86f..738bcdb2bc0 100644 --- a/bootstore/src/schemes/v0/peer_networking.rs +++ b/bootstore/src/schemes/v0/peer_networking.rs @@ -4,25 +4,25 @@ //! Async networking used by peer.rs +use super::Msg as FsmMsg; use super::messages::Identify; use super::storage::NetworkConfig; -use super::Msg as FsmMsg; use crate::schemes::Hello; use bytes::Buf; use derive_more::From; use serde::{Deserialize, Serialize}; use sled_hardware_types::Baseboard; -use slog::{debug, error, info, o, warn, Logger}; +use slog::{Logger, debug, error, info, o, warn}; use std::collections::VecDeque; use std::io::Cursor; use std::net::SocketAddrV6; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf}; use tokio::net::TcpStream; +use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf}; use tokio::sync::mpsc; use tokio::task::JoinHandle; -use tokio::time::{interval, sleep, Instant, MissedTickBehavior}; +use tokio::time::{Instant, MissedTickBehavior, interval, sleep}; const CONN_BUF_SIZE: usize = 512 * 1024; const CONNECTION_RETRY_TIMEOUT: Duration = Duration::from_secs(1); diff --git a/bootstore/src/schemes/v0/share_pkg.rs b/bootstore/src/schemes/v0/share_pkg.rs index f89d5b73137..e8e4c30ac63 100644 --- a/bootstore/src/schemes/v0/share_pkg.rs +++ b/bootstore/src/schemes/v0/share_pkg.rs @@ -4,11 +4,11 @@ //! Distributable data packages containing key shares and metadata -use crate::trust_quorum::{RackSecret, TrustQuorumError}; use crate::Sha3_256Digest; -use chacha20poly1305::{aead::Aead, ChaCha20Poly1305, Key, KeyInit}; +use crate::trust_quorum::{RackSecret, TrustQuorumError}; +use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit, aead::Aead}; use hkdf::Hkdf; -use rand::{rngs::OsRng, RngCore}; +use rand::{RngCore, rngs::OsRng}; use secrecy::{ExposeSecret, Secret}; use serde::{Deserialize, Serialize}; use sha3::{Digest, Sha3_256}; diff --git a/bootstore/src/schemes/v0/storage.rs b/bootstore/src/schemes/v0/storage.rs index 624d0ee6edf..e92f8b5f7ac 100644 --- a/bootstore/src/schemes/v0/storage.rs +++ b/bootstore/src/schemes/v0/storage.rs @@ -16,7 +16,7 @@ use camino::Utf8PathBuf; use omicron_common::ledger::{Ledger, Ledgerable}; use serde::{Deserialize, Serialize}; use sled_hardware_types::Baseboard; -use slog::{info, Logger}; +use slog::{Logger, info}; /// A persistent version of `Fsm::State` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/bootstore/tests/v0-fsm-proptest-learner.rs b/bootstore/tests/v0-fsm-proptest-learner.rs index b70c3c3a9d3..a91acaad3d8 100644 --- a/bootstore/tests/v0-fsm-proptest-learner.rs +++ b/bootstore/tests/v0-fsm-proptest-learner.rs @@ -11,9 +11,9 @@ mod common; use assert_matches::assert_matches; use bootstore::schemes::v0::{ - create_pkgs, ApiError, ApiOutput, Envelope, Fsm, FsmConfig, - LearnedSharePkg, Msg, MsgError, RackUuid, Request, RequestType, Response, - ResponseType, Share, SharePkg, State, + ApiError, ApiOutput, Envelope, Fsm, FsmConfig, LearnedSharePkg, Msg, + MsgError, RackUuid, Request, RequestType, Response, ResponseType, Share, + SharePkg, State, create_pkgs, }; use bootstore::trust_quorum::RackSecret; use common::CommonTestState; @@ -24,8 +24,9 @@ use std::collections::{BTreeMap, BTreeSet}; use uuid::Uuid; use common::generators::{ - arb_action, arb_config, arb_initial_member_ids, arb_learner_id, Action, - MAX_ACTIONS, MAX_INITIAL_MEMBERS, MIN_INITIAL_MEMBERS, TICK_TIMEOUT, + Action, MAX_ACTIONS, MAX_INITIAL_MEMBERS, MIN_INITIAL_MEMBERS, + TICK_TIMEOUT, arb_action, arb_config, arb_initial_member_ids, + arb_learner_id, }; /// Actions run during the learning phase of the test @@ -237,11 +238,12 @@ impl TestState { peer_id: Baseboard, ) -> Uuid { self.common.connected_peers.insert(peer_id.clone()); - assert!(self - .common - .sut - .on_connected(self.common.now, peer_id.clone()) - .is_ok()); + assert!( + self.common + .sut + .on_connected(self.common.now, peer_id.clone()) + .is_ok() + ); let mut iter = self.common.sut.drain_envelopes(); let envelope = iter.next().unwrap(); assert_matches!(envelope, diff --git a/bootstore/tests/v0-fsm-proptest-rack-coordinator.rs b/bootstore/tests/v0-fsm-proptest-rack-coordinator.rs index 0de1f83ba7f..812be1a447c 100644 --- a/bootstore/tests/v0-fsm-proptest-rack-coordinator.rs +++ b/bootstore/tests/v0-fsm-proptest-rack-coordinator.rs @@ -25,8 +25,8 @@ use std::collections::{BTreeMap, BTreeSet}; use uuid::Uuid; use common::generators::{ - arb_action, arb_config, arb_initial_member_ids, Action, MAX_ACTIONS, - MAX_INITIAL_MEMBERS, MIN_INITIAL_MEMBERS, + Action, MAX_ACTIONS, MAX_INITIAL_MEMBERS, MIN_INITIAL_MEMBERS, arb_action, + arb_config, arb_initial_member_ids, }; use common::{CommonTestState, TestRequest}; @@ -360,9 +360,11 @@ impl TestState { { assert!(!test_req.acks.contains(&envelope.to)); } else { - assert!(!self.learn_requests[&request_id] - .acks - .contains(&envelope.to)); + assert!( + !self.learn_requests[&request_id] + .acks + .contains(&envelope.to) + ); } } } diff --git a/certificates/src/lib.rs b/certificates/src/lib.rs index ee4ab4a6bd4..cc5e9924733 100644 --- a/certificates/src/lib.rs +++ b/certificates/src/lib.rs @@ -39,7 +39,9 @@ pub enum CertificateError { #[error("Error validating certificate hostname")] ErrorValidatingHostname(#[source] openssl::error::ErrorStack), - #[error("Certificate not valid for given hostnames {hostname:?}: {cert_description}")] + #[error( + "Certificate not valid for given hostnames {hostname:?}: {cert_description}" + )] NoDnsNameMatchingHostname { hostname: String, cert_description: String }, #[error("Unsupported certificate purpose (not usable for server auth)")] diff --git a/certificates/src/openssl_ext.rs b/certificates/src/openssl_ext.rs index e5fcd2dcbca..a20aa205add 100644 --- a/certificates/src/openssl_ext.rs +++ b/certificates/src/openssl_ext.rs @@ -10,10 +10,10 @@ use openssl::error::ErrorStack; use openssl::nid::Nid; use openssl::x509::X509Ref; use openssl_sys::X509 as RawX509; +use std::ffi::CStr; use std::ffi::c_char; use std::ffi::c_int; use std::ffi::c_uint; -use std::ffi::CStr; use std::ptr; extern "C" { diff --git a/clickhouse-admin/src/bin/clickhouse-admin-keeper.rs b/clickhouse-admin/src/bin/clickhouse-admin-keeper.rs index 7a994dc07d4..8aac5ffb565 100644 --- a/clickhouse-admin/src/bin/clickhouse-admin-keeper.rs +++ b/clickhouse-admin/src/bin/clickhouse-admin-keeper.rs @@ -9,8 +9,8 @@ use anyhow::anyhow; use camino::Utf8PathBuf; use clap::Parser; use omicron_clickhouse_admin::Config; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use std::net::{SocketAddr, SocketAddrV6}; #[derive(Debug, Parser)] diff --git a/clickhouse-admin/src/bin/clickhouse-admin-server.rs b/clickhouse-admin/src/bin/clickhouse-admin-server.rs index cc49ed9fd43..279b1860807 100644 --- a/clickhouse-admin/src/bin/clickhouse-admin-server.rs +++ b/clickhouse-admin/src/bin/clickhouse-admin-server.rs @@ -9,8 +9,8 @@ use anyhow::anyhow; use camino::Utf8PathBuf; use clap::Parser; use omicron_clickhouse_admin::Config; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use std::net::{SocketAddr, SocketAddrV6}; #[derive(Debug, Parser)] diff --git a/clickhouse-admin/src/bin/clickhouse-admin-single.rs b/clickhouse-admin/src/bin/clickhouse-admin-single.rs index a23eadd396b..977c130835e 100644 --- a/clickhouse-admin/src/bin/clickhouse-admin-single.rs +++ b/clickhouse-admin/src/bin/clickhouse-admin-single.rs @@ -8,8 +8,8 @@ use anyhow::anyhow; use camino::Utf8PathBuf; use clap::Parser; use omicron_clickhouse_admin::Config; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use std::net::{SocketAddr, SocketAddrV6}; #[derive(Debug, Parser)] diff --git a/clickhouse-admin/src/clickhouse_cli.rs b/clickhouse-admin/src/clickhouse_cli.rs index a6e3c8b91c3..3e5d1f79170 100644 --- a/clickhouse-admin/src/clickhouse_cli.rs +++ b/clickhouse-admin/src/clickhouse_cli.rs @@ -6,12 +6,12 @@ use anyhow::Result; use camino::Utf8PathBuf; use clickhouse_admin_types::{ ClickhouseKeeperClusterMembership, DistributedDdlQueue, KeeperConf, - KeeperId, Lgif, RaftConfig, SystemTimeSeries, SystemTimeSeriesSettings, - OXIMETER_CLUSTER, + KeeperId, Lgif, OXIMETER_CLUSTER, RaftConfig, SystemTimeSeries, + SystemTimeSeriesSettings, }; use dropshot::HttpError; -use illumos_utils::{output_to_exec_error, ExecutionError}; -use slog::{debug, Logger}; +use illumos_utils::{ExecutionError, output_to_exec_error}; +use slog::{Logger, debug}; use slog_error_chain::{InlineErrorChain, SlogInlineError}; use std::collections::BTreeSet; use std::ffi::OsStr; @@ -234,7 +234,7 @@ impl ClickhouseCli { Err(e) => { return Err(ClickhouseCliError::ServerUnavailable(format!( "command timed out after {elapsed:?}: {e}" - ))) + ))); } }; diff --git a/clickhouse-admin/src/context.rs b/clickhouse-admin/src/context.rs index 96f5a18f07a..36442a99700 100644 --- a/clickhouse-admin/src/context.rs +++ b/clickhouse-admin/src/context.rs @@ -4,13 +4,13 @@ use crate::{ClickhouseCli, Clickward}; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use camino::Utf8PathBuf; use clickhouse_admin_types::{ + CLICKHOUSE_KEEPER_CONFIG_DIR, CLICKHOUSE_KEEPER_CONFIG_FILE, + CLICKHOUSE_SERVER_CONFIG_DIR, CLICKHOUSE_SERVER_CONFIG_FILE, GenerateConfigResult, KeeperConfigurableSettings, - ServerConfigurableSettings, CLICKHOUSE_KEEPER_CONFIG_DIR, - CLICKHOUSE_KEEPER_CONFIG_FILE, CLICKHOUSE_SERVER_CONFIG_DIR, - CLICKHOUSE_SERVER_CONFIG_FILE, + ServerConfigurableSettings, }; use dropshot::{ClientErrorStatusCode, HttpError}; use flume::{Receiver, Sender, TrySendError}; @@ -342,9 +342,8 @@ fn generate_config_and_enable_svc( ClientErrorStatusCode::CONFLICT, format!( "current generation '{}' is greater than incoming generation '{}'", - current, - incoming_generation, - ) + current, incoming_generation, + ), )); } }; @@ -573,7 +572,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "first line of configuration file 'types/testutils/malformed_3.xml' is malformed: -->" + "first line of configuration file 'types/testutils/malformed_3.xml' is malformed: -->" ); } } diff --git a/clickhouse-admin/src/http_entrypoints.rs b/clickhouse-admin/src/http_entrypoints.rs index 15d025c17bc..0014be7ac7a 100644 --- a/clickhouse-admin/src/http_entrypoints.rs +++ b/clickhouse-admin/src/http_entrypoints.rs @@ -61,7 +61,7 @@ impl ClickhouseAdminServerApi for ClickhouseAdminServerImpl { Some(String::from("ObjectNotFound")), ClientErrorStatusCode::NOT_FOUND, "no generation number found".to_string(), - )) + )); } }; Ok(HttpResponseOk(gen)) @@ -127,7 +127,7 @@ impl ClickhouseAdminKeeperApi for ClickhouseAdminKeeperImpl { Some(String::from("ObjectNotFound")), ClientErrorStatusCode::NOT_FOUND, "no generation number found".to_string(), - )) + )); } }; Ok(HttpResponseOk(gen)) diff --git a/clickhouse-admin/src/lib.rs b/clickhouse-admin/src/lib.rs index 5f1ac6f0f57..88168911ba3 100644 --- a/clickhouse-admin/src/lib.rs +++ b/clickhouse-admin/src/lib.rs @@ -6,7 +6,7 @@ use camino::Utf8PathBuf; use context::{KeeperServerContext, ServerContext}; use dropshot::HttpServer; use omicron_common::FileKv; -use slog::{debug, error, Drain}; +use slog::{Drain, debug, error}; use slog_dtrace::ProbeRegistration; use slog_error_chain::SlogInlineError; use std::io; diff --git a/clickhouse-admin/test-utils/src/lib.rs b/clickhouse-admin/test-utils/src/lib.rs index 7bc73a43a8f..7ecd566b665 100644 --- a/clickhouse-admin/test-utils/src/lib.rs +++ b/clickhouse-admin/test-utils/src/lib.rs @@ -7,7 +7,7 @@ use camino::Utf8PathBuf; use clickhouse_admin_types::OXIMETER_CLUSTER; use clickward::{BasePorts, Deployment, DeploymentConfig}; -use dropshot::test_util::{log_prefix_for_test, LogContext}; +use dropshot::test_util::{LogContext, log_prefix_for_test}; use dropshot::{ConfigLogging, ConfigLoggingLevel}; pub const DEFAULT_CLICKHOUSE_ADMIN_BASE_PORTS: BasePorts = BasePorts { diff --git a/clickhouse-admin/tests/integration_test.rs b/clickhouse-admin/tests/integration_test.rs index b6d56618f7e..d9d1f45f451 100644 --- a/clickhouse-admin/tests/integration_test.rs +++ b/clickhouse-admin/tests/integration_test.rs @@ -4,15 +4,16 @@ use camino::Utf8PathBuf; use clickhouse_admin_test_utils::{ + DEFAULT_CLICKHOUSE_ADMIN_BASE_PORTS, default_clickhouse_cluster_test_deployment, - default_clickhouse_log_ctx_and_path, DEFAULT_CLICKHOUSE_ADMIN_BASE_PORTS, + default_clickhouse_log_ctx_and_path, }; use clickhouse_admin_types::{ ClickhouseHost, ClickhouseKeeperClusterMembership, KeeperId, KeeperServerInfo, KeeperServerType, RaftConfig, }; use omicron_clickhouse_admin::ClickhouseCli; -use slog::{info, o, Drain}; +use slog::{Drain, info, o}; use slog_term::{FullFormat, PlainDecorator, TestStdoutWriter}; use std::collections::BTreeSet; use std::net::{Ipv6Addr, SocketAddrV6}; diff --git a/clickhouse-admin/types/src/config.rs b/clickhouse-admin/types/src/config.rs index 0b1c7ffe1be..742b442bf3e 100644 --- a/clickhouse-admin/types/src/config.rs +++ b/clickhouse-admin/types/src/config.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::{path_schema, KeeperId, ServerId, OXIMETER_CLUSTER}; -use anyhow::{bail, Error}; +use crate::{KeeperId, OXIMETER_CLUSTER, ServerId, path_schema}; +use anyhow::{Error, bail}; use camino::Utf8PathBuf; use omicron_common::address::{ CLICKHOUSE_HTTP_PORT, CLICKHOUSE_INTERSERVER_PORT, diff --git a/clickhouse-admin/types/src/lib.rs b/clickhouse-admin/types/src/lib.rs index 5193126db58..00c2e1d02bf 100644 --- a/clickhouse-admin/types/src/lib.rs +++ b/clickhouse-admin/types/src/lib.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{bail, Context, Error, Result}; +use anyhow::{Context, Error, Result, bail}; use atomicwrites::AtomicFile; use camino::Utf8PathBuf; use chrono::{DateTime, Utc}; @@ -11,12 +11,12 @@ use derive_more::{Add, AddAssign, Display, From}; use itertools::Itertools; use omicron_common::api::external::Generation; use schemars::{ + JsonSchema, gen::SchemaGenerator, schema::{Schema, SchemaObject}, - JsonSchema, }; use serde::{Deserialize, Serialize}; -use slog::{info, Logger}; +use slog::{Logger, info}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::fs::create_dir; @@ -365,14 +365,20 @@ impl Lgif { bail!("Returned None while attempting to retrieve key"); }; if key != expected_key { - bail!("Extracted key `{key:?}` from output differs from expected key `{expected_key}`"); + bail!( + "Extracted key `{key:?}` from output differs from expected key `{expected_key}`" + ); } let Some(val) = split.next() else { - bail!("Command output has a line that does not contain a key-value pair: {key:?}"); + bail!( + "Command output has a line that does not contain a key-value pair: {key:?}" + ); }; let val = match u64::from_str(val) { Ok(v) => v, - Err(e) => bail!("Unable to convert value {val:?} into u64 for key {key}: {e}"), + Err(e) => bail!( + "Unable to convert value {val:?} into u64 for key {key}: {e}" + ), }; vals.push(val); } @@ -504,13 +510,17 @@ impl RaftConfig { for line in s.lines() { let mut split = line.split('='); let Some(server) = split.next() else { - bail!("Returned None while attempting to retrieve raft configuration"); + bail!( + "Returned None while attempting to retrieve raft configuration" + ); }; // Retrieve server ID let mut split_server = server.split("."); let Some(s) = split_server.next() else { - bail!("Returned None while attempting to retrieve server identifier") + bail!( + "Returned None while attempting to retrieve server identifier" + ) }; if s != "server" { bail!( @@ -551,7 +561,9 @@ impl RaftConfig { // Retrieve host let p = format!(":{}", port); let Some(h) = address.split(&p).next() else { - bail!("A host could not be extracted from {address}. Missing port {port}") + bail!( + "A host could not be extracted from {address}. Missing port {port}" + ) }; // The ouput we get from running the clickhouse keeper-client // command does not add square brackets to an IPv6 address @@ -719,10 +731,14 @@ impl KeeperConf { bail!("Returned None while attempting to retrieve key"); }; if key != expected_key { - bail!("Extracted key `{key:?}` from output differs from expected key `{expected_key}`"); + bail!( + "Extracted key `{key:?}` from output differs from expected key `{expected_key}`" + ); } let Some(val) = split.next() else { - bail!("Command output has a line that does not contain a key-value pair: {key:?}"); + bail!( + "Command output has a line that does not contain a key-value pair: {key:?}" + ); }; vals.push(val); } @@ -1288,7 +1304,7 @@ mod tests { use camino_tempfile::Builder; use chrono::{DateTime, Utc}; use omicron_common::api::external::Generation; - use slog::{o, Drain}; + use slog::{Drain, o}; use slog_term::{FullFormat, PlainDecorator, TestStdoutWriter}; use std::collections::BTreeMap; use std::net::{Ipv4Addr, Ipv6Addr}; @@ -1520,7 +1536,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Output from the Keeper differs to the expected output keys \ + "Output from the Keeper differs to the expected output keys \ Output: \"\" \ Expected output keys: [\"first_log_idx\", \"first_log_term\", \"last_log_idx\", \"last_log_term\", \"last_committed_log_idx\", \"leader_committed_log_idx\", \"target_committed_log_idx\", \"last_snapshot_idx\"]", ); @@ -1568,7 +1584,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Output is not as expected. Server identifier: 'serv.1' Expected server identifier: 'server.{SERVER_ID}'", + "Output is not as expected. Server identifier: 'serv.1' Expected server identifier: 'server.{SERVER_ID}'", ); } @@ -1583,7 +1599,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Unable to convert value \"BOB\" into u16: invalid digit found in string", + "Unable to convert value \"BOB\" into u16: invalid digit found in string", ); } @@ -1610,7 +1626,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Unable to convert value \"\" into u64: cannot parse integer from empty string", + "Unable to convert value \"\" into u64: cannot parse integer from empty string", ); } @@ -1655,7 +1671,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Unable to convert value \"\" into u16: cannot parse integer from empty string", + "Unable to convert value \"\" into u16: cannot parse integer from empty string", ); } @@ -1711,7 +1727,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Unable to convert value \"\" into u16: cannot parse integer from empty string", + "Unable to convert value \"\" into u16: cannot parse integer from empty string", ); let data = "server.1=::1:21001;learner\n".as_bytes(); @@ -1737,7 +1753,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Unable to convert value \"BOB\" into u16: invalid digit found in string", + "Unable to convert value \"BOB\" into u16: invalid digit found in string", ); } @@ -1752,7 +1768,7 @@ mod tests { assert_eq!( format!("{}", root_cause), - "Output is not as expected. Server identifier: '' Expected server identifier: 'server.{SERVER_ID}'", + "Output is not as expected. Server identifier: '' Expected server identifier: 'server.{SERVER_ID}'", ); } @@ -1805,7 +1821,10 @@ snapshot_storage_disk=LocalSnapshotDisk assert!(conf.server_id == KeeperId(1)); assert!(conf.enable_ipv6); assert!(conf.tcp_port == 20001); - assert!(conf.four_letter_word_allow_list == *"conf,cons,crst,envi,ruok,srst,srvr,stat,wchs,dirs,mntr,isro,rcvr,apiv,csnp,lgif,rqld,rclc,clrs,ftfl" ); + assert!( + conf.four_letter_word_allow_list + == *"conf,cons,crst,envi,ruok,srst,srvr,stat,wchs,dirs,mntr,isro,rcvr,apiv,csnp,lgif,rqld,rclc,clrs,ftfl" + ); assert!(conf.max_requests_batch_size == 100); assert!(conf.min_session_timeout_ms == 10000); assert!(conf.session_timeout_ms == 30000); @@ -2231,7 +2250,7 @@ snapshot_storage_disk=LocalSnapshotDisk assert_eq!( format!("{}", root_cause), - "invalid type: integer `2024`, expected a string at line 1 column 12", + "invalid type: integer `2024`, expected a string at line 1 column 12", ); } } diff --git a/clients/ddm-admin-client/src/lib.rs b/clients/ddm-admin-client/src/lib.rs index d15de8c0ca0..850fe04e69d 100644 --- a/clients/ddm-admin-client/src/lib.rs +++ b/clients/ddm-admin-client/src/lib.rs @@ -9,21 +9,21 @@ #![allow(clippy::match_single_binding)] #![allow(clippy::clone_on_copy)] -pub use ddm_admin_client::types; pub use ddm_admin_client::Error; +pub use ddm_admin_client::types; -use ddm_admin_client::types::TunnelOrigin; use ddm_admin_client::Client as InnerClient; +use ddm_admin_client::types::TunnelOrigin; use either::Either; use omicron_common::address::Ipv6Subnet; use omicron_common::address::SLED_PREFIX; use omicron_common::backoff::retry_notify; use omicron_common::backoff::retry_policy_internal_service_aggressive; -use sled_hardware_types::underlay::BootstrapInterface; use sled_hardware_types::underlay::BOOTSTRAP_MASK; use sled_hardware_types::underlay::BOOTSTRAP_PREFIX; -use slog::info; +use sled_hardware_types::underlay::BootstrapInterface; use slog::Logger; +use slog::info; use std::net::IpAddr; use std::net::Ipv6Addr; use std::net::SocketAddr; diff --git a/clients/dpd-client/build.rs b/clients/dpd-client/build.rs index 3d10b919019..5d4b21a417b 100644 --- a/clients/dpd-client/build.rs +++ b/clients/dpd-client/build.rs @@ -10,9 +10,9 @@ // public, we can remove this and point the services in `omicron` // that require the `dpd-client` library to the `Dendrite` repo. -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::bail; use omicron_zone_package::config::Config; use omicron_zone_package::config::PackageName; use omicron_zone_package::package::PackageSource; @@ -47,7 +47,9 @@ fn main() -> Result<()> { format!("../../out/downloads/dpd-{commit}.json") }); if !Path::new(&local_path).exists() { - bail!("{local_path} doesn't exist; rerun `cargo xtask download dendrite-openapi` (after updating `tools/dendrite_openapi_version` if the dendrite commit in package-manifest.toml has changed)"); + bail!( + "{local_path} doesn't exist; rerun `cargo xtask download dendrite-openapi` (after updating `tools/dendrite_openapi_version` if the dendrite commit in package-manifest.toml has changed)" + ); } println!("cargo:rerun-if-changed={local_path}"); local_path @@ -56,14 +58,18 @@ fn main() -> Result<()> { PackageSource::Manual => { let local_path = "../../out/downloads/dpd-manual.json".to_string(); if !Path::new(&local_path).exists() { - bail!("{local_path} doesn't exist, please copy manually built dpd.json there!"); + bail!( + "{local_path} doesn't exist, please copy manually built dpd.json there!" + ); } println!("cargo:rerun-if-changed={local_path}"); local_path } _ => { - bail!("dendrite external package must have type `prebuilt` or `manual`") + bail!( + "dendrite external package must have type `prebuilt` or `manual`" + ) } }; diff --git a/clients/dpd-client/src/lib.rs b/clients/dpd-client/src/lib.rs index a0608a5c7d8..b7180e79ac9 100644 --- a/clients/dpd-client/src/lib.rs +++ b/clients/dpd-client/src/lib.rs @@ -12,8 +12,8 @@ use std::net::IpAddr; -use slog::info; use slog::Logger; +use slog::info; include!(concat!(env!("OUT_DIR"), "/dpd-client.rs")); diff --git a/clients/oxide-client/src/lib.rs b/clients/oxide-client/src/lib.rs index 3e5247bbcbd..f02581faaf4 100644 --- a/clients/oxide-client/src/lib.rs +++ b/clients/oxide-client/src/lib.rs @@ -4,13 +4,13 @@ //! Interface for making API requests to the Oxide control plane. -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use futures::FutureExt; +use hickory_resolver::TokioAsyncResolver; use hickory_resolver::config::{ NameServerConfig, Protocol, ResolverConfig, ResolverOpts, }; -use hickory_resolver::TokioAsyncResolver; use std::net::SocketAddr; use std::sync::Arc; use thiserror::Error; diff --git a/cockroach-admin/src/bin/cockroach-admin.rs b/cockroach-admin/src/bin/cockroach-admin.rs index ee6d8f4aa96..0019de50c36 100644 --- a/cockroach-admin/src/bin/cockroach-admin.rs +++ b/cockroach-admin/src/bin/cockroach-admin.rs @@ -10,8 +10,8 @@ use camino::Utf8PathBuf; use clap::Parser; use omicron_cockroach_admin::CockroachCli; use omicron_cockroach_admin::Config; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use omicron_uuid_kinds::OmicronZoneUuid; use std::net::SocketAddr; use std::net::SocketAddrV6; diff --git a/cockroach-admin/src/cockroach_cli.rs b/cockroach-admin/src/cockroach_cli.rs index e072dc9b343..7f54606a04e 100644 --- a/cockroach-admin/src/cockroach_cli.rs +++ b/cockroach-admin/src/cockroach_cli.rs @@ -6,8 +6,8 @@ use camino::Utf8PathBuf; use cockroach_admin_types::NodeDecommission; use cockroach_admin_types::NodeStatus; use dropshot::HttpError; -use illumos_utils::output_to_exec_error; use illumos_utils::ExecutionError; +use illumos_utils::output_to_exec_error; use slog_error_chain::InlineErrorChain; use slog_error_chain::SlogInlineError; use std::io; diff --git a/cockroach-admin/src/context.rs b/cockroach-admin/src/context.rs index d986967c54b..37c84b43ecf 100644 --- a/cockroach-admin/src/context.rs +++ b/cockroach-admin/src/context.rs @@ -5,8 +5,8 @@ use std::net::SocketAddr; use crate::CockroachCli; -use anyhow::bail; use anyhow::Context; +use anyhow::bail; use dropshot::HttpError; use omicron_uuid_kinds::OmicronZoneUuid; use slog::Logger; diff --git a/cockroach-admin/src/lib.rs b/cockroach-admin/src/lib.rs index dbe36358d21..10cecf56a05 100644 --- a/cockroach-admin/src/lib.rs +++ b/cockroach-admin/src/lib.rs @@ -5,9 +5,9 @@ use context::ServerContext; use omicron_common::FileKv; use omicron_uuid_kinds::OmicronZoneUuid; +use slog::Drain; use slog::debug; use slog::error; -use slog::Drain; use slog_dtrace::ProbeRegistration; use slog_error_chain::SlogInlineError; use std::io; diff --git a/cockroach-admin/types/src/lib.rs b/cockroach-admin/types/src/lib.rs index 973c86bcedc..11c2d2719a6 100644 --- a/cockroach-admin/types/src/lib.rs +++ b/cockroach-admin/types/src/lib.rs @@ -6,7 +6,7 @@ use std::{io, net::SocketAddr}; use chrono::{DateTime, NaiveDateTime, Utc}; use schemars::JsonSchema; -use serde::{de, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de}; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -432,9 +432,11 @@ No more data reported on target nodes. Please verify cluster health before remov is_decommissioning: true, membership: NodeMembership::Decommissioned, is_draining: false, - notes: vec!["No more data reported on target nodes. \ + notes: vec![ + "No more data reported on target nodes. \ Please verify cluster health before removing the nodes." - .to_string()], + .to_string(), + ], }; let statuses = diff --git a/common/src/address.rs b/common/src/address.rs index dc79163581c..9a9623fe27d 100644 --- a/common/src/address.rs +++ b/common/src/address.rs @@ -841,7 +841,9 @@ mod test { "net": "ff12::3456/64" }); - assert!(serde_json::from_value::>(value.clone()).is_ok()); + assert!( + serde_json::from_value::>(value.clone()).is_ok() + ); assert!(serde_json::from_value::>(value).is_err()); } } diff --git a/common/src/api/external/http_pagination.rs b/common/src/api/external/http_pagination.rs index d4d237b2341..bec973fd29c 100644 --- a/common/src/api/external/http_pagination.rs +++ b/common/src/api/external/http_pagination.rs @@ -51,9 +51,9 @@ use dropshot::RequestContext; use dropshot::ResultsPage; use dropshot::WhichPage; use schemars::JsonSchema; -use serde::de::DeserializeOwned; use serde::Deserialize; use serde::Serialize; +use serde::de::DeserializeOwned; use std::fmt::Debug; use std::num::NonZeroU32; use uuid::Uuid; @@ -284,9 +284,8 @@ fn default_id_sort_mode() -> IdSortMode { IdSortMode::IdAscending } -impl< - T: Clone + Debug + DeserializeOwned + JsonSchema + PartialEq + Serialize, - > ScanParams for ScanById +impl + ScanParams for ScanById { type MarkerValue = Uuid; fn direction(&self) -> PaginationOrder { @@ -368,9 +367,8 @@ pub enum PaginatedBy<'a> { Name(DataPageParams<'a, Name>), } -impl< - T: Clone + Debug + DeserializeOwned + JsonSchema + PartialEq + Serialize, - > ScanParams for ScanByNameOrId +impl + ScanParams for ScanByNameOrId { type MarkerValue = NameOrId; @@ -412,11 +410,6 @@ impl< #[cfg(test)] mod test { - use super::data_page_params_with_limit; - use super::marker_for_id; - use super::marker_for_name; - use super::marker_for_name_or_id; - use super::page_selector_for; use super::IdSortMode; use super::Name; use super::NameOrId; @@ -434,9 +427,14 @@ mod test { use super::ScanByName; use super::ScanByNameOrId; use super::ScanParams; - use crate::api::external::http_pagination::name_or_id_pagination; + use super::data_page_params_with_limit; + use super::marker_for_id; + use super::marker_for_name; + use super::marker_for_name_or_id; + use super::page_selector_for; use crate::api::external::IdentityMetadata; use crate::api::external::ObjectIdentity; + use crate::api::external::http_pagination::name_or_id_pagination; use chrono::Utc; use dropshot::PaginationOrder; use dropshot::PaginationParams; diff --git a/common/src/api/external/mod.rs b/common/src/api/external/mod.rs index c40a9a65b5e..7015efd9367 100644 --- a/common/src/api/external/mod.rs +++ b/common/src/api/external/mod.rs @@ -28,8 +28,8 @@ use oxnet::IpNet; use oxnet::Ipv4Net; use parse_display::Display; use parse_display::FromStr; -use rand::thread_rng; use rand::Rng; +use rand::thread_rng; use schemars::JsonSchema; use semver; use serde::Deserialize; @@ -3787,18 +3787,15 @@ mod test { assert!(!"fd00::/40".parse::().unwrap().is_vpc_prefix()); let vpc_prefix = "fd00::/48".parse::().unwrap(); - assert!("fd00::/64" - .parse::() - .unwrap() - .is_vpc_subnet(&vpc_prefix)); - assert!(!"fd10::/64" - .parse::() - .unwrap() - .is_vpc_subnet(&vpc_prefix)); - assert!(!"fd00::/63" - .parse::() - .unwrap() - .is_vpc_subnet(&vpc_prefix)); + assert!( + "fd00::/64".parse::().unwrap().is_vpc_subnet(&vpc_prefix) + ); + assert!( + !"fd10::/64".parse::().unwrap().is_vpc_subnet(&vpc_prefix) + ); + assert!( + !"fd00::/63".parse::().unwrap().is_vpc_subnet(&vpc_prefix) + ); } #[test] diff --git a/common/src/api/internal/shared.rs b/common/src/api/internal/shared.rs index a3f02e5b759..c66b2effc70 100644 --- a/common/src/api/internal/shared.rs +++ b/common/src/api/internal/shared.rs @@ -11,7 +11,7 @@ use crate::{ use daft::Diffable; use oxnet::{IpNet, Ipv4Net, Ipv6Net}; use schemars::JsonSchema; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; use std::{ collections::{HashMap, HashSet}, fmt, diff --git a/common/src/backoff.rs b/common/src/backoff.rs index 1fc031947e4..1ed85c7997a 100644 --- a/common/src/backoff.rs +++ b/common/src/backoff.rs @@ -15,10 +15,10 @@ use std::future::Future; use std::time::Duration; use std::time::Instant; -pub use ::backoff::future::{retry, retry_notify}; pub use ::backoff::Error as BackoffError; +pub use ::backoff::future::{retry, retry_notify}; pub use ::backoff::{ - backoff::Backoff, ExponentialBackoff, ExponentialBackoffBuilder, Notify, + ExponentialBackoff, ExponentialBackoffBuilder, Notify, backoff::Backoff, }; /// A helper function which modifies what information is tracked within the @@ -79,8 +79,8 @@ pub fn retry_policy_internal_service() -> ::backoff::ExponentialBackoff { /// /// The most significant difference is the "multiplier" - rather than backoff /// roughly doubling, it backs off at a smaller interval. -pub fn retry_policy_internal_service_aggressive( -) -> ::backoff::ExponentialBackoff { +pub fn retry_policy_internal_service_aggressive() +-> ::backoff::ExponentialBackoff { backoff_builder() .with_initial_interval(Duration::from_millis(100)) .with_multiplier(1.2) diff --git a/common/src/disk.rs b/common/src/disk.rs index b5c3ef6b1c1..f5a64219049 100644 --- a/common/src/disk.rs +++ b/common/src/disk.rs @@ -502,7 +502,9 @@ pub enum DiskManagementError { #[error("Expected zpool UUID of {expected}, but saw {observed}")] ZpoolUuidMismatch { expected: ZpoolUuid, observed: ZpoolUuid }, - #[error("Failed to access keys necessary to unlock storage. This error may be transient.")] + #[error( + "Failed to access keys necessary to unlock storage. This error may be transient." + )] KeyManager(String), #[error("Other error starting disk management: {0}")] diff --git a/common/src/ledger.rs b/common/src/ledger.rs index a52c2441cad..5c590e464db 100644 --- a/common/src/ledger.rs +++ b/common/src/ledger.rs @@ -6,8 +6,8 @@ use async_trait::async_trait; use camino::{Utf8Path, Utf8PathBuf}; -use serde::{de::DeserializeOwned, Serialize}; -use slog::{debug, error, info, warn, Logger}; +use serde::{Serialize, de::DeserializeOwned}; +use slog::{Logger, debug, error, info, warn}; #[derive(thiserror::Error, Debug)] pub enum Error { @@ -27,7 +27,9 @@ pub enum Error { #[error("Not found in storage")] NotFound, - #[error("Failed to write the ledger to storage (tried to access: {failed_paths:?})")] + #[error( + "Failed to write the ledger to storage (tried to access: {failed_paths:?})" + )] FailedToWrite { failed_paths: Vec<(Utf8PathBuf, Error)> }, } @@ -95,11 +97,7 @@ impl Ledger { // Return the ledger with the highest generation number. let ledger = ledgers.into_iter().reduce(|prior, ledger| { - if ledger.is_newer_than(&prior) { - ledger - } else { - prior - } + if ledger.is_newer_than(&prior) { ledger } else { prior } }); ledger } @@ -215,10 +213,10 @@ pub trait Ledgerable: DeserializeOwned + Serialize + Send + Sync { mod test { use super::*; - pub use dropshot::test_util::LogContext; use dropshot::ConfigLogging; use dropshot::ConfigLoggingIfExists; use dropshot::ConfigLoggingLevel; + pub use dropshot::test_util::LogContext; // Copied from `omicron-test-utils` to avoid a circular dependency where // `omicron-common` depends on `omicron-test-utils` which depends on diff --git a/common/src/progenitor_operation_retry.rs b/common/src/progenitor_operation_retry.rs index 4864cc90b78..5a24fc724f0 100644 --- a/common/src/progenitor_operation_retry.rs +++ b/common/src/progenitor_operation_retry.rs @@ -3,13 +3,13 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use futures::Future; -use slog::warn; use slog::Logger; +use slog::warn; use crate::api::external::Error; +use crate::backoff::BackoffError; use crate::backoff::retry_notify; use crate::backoff::retry_policy_internal_service; -use crate::backoff::BackoffError; #[derive(Debug, thiserror::Error)] pub enum ProgenitorOperationRetryError { diff --git a/common/src/update.rs b/common/src/update.rs index fc747cf16d9..1cd6f64cdff 100644 --- a/common/src/update.rs +++ b/common/src/update.rs @@ -7,9 +7,9 @@ use std::{borrow::Cow, convert::Infallible, fmt, str::FromStr}; use crate::api::{external::SemverVersion, internal::nexus::KnownArtifactKind}; use hex::FromHexError; use schemars::{ + JsonSchema, gen::SchemaGenerator, schema::{Schema, SchemaObject}, - JsonSchema, }; use serde::{Deserialize, Serialize}; diff --git a/dev-tools/cert-dev/tests/test-cert-dev.rs b/dev-tools/cert-dev/tests/test-cert-dev.rs index 7d07b4685cb..bf37c8a5117 100644 --- a/dev-tools/cert-dev/tests/test-cert-dev.rs +++ b/dev-tools/cert-dev/tests/test-cert-dev.rs @@ -8,7 +8,7 @@ use std::path::PathBuf; use anyhow::Context; use omicron_test_utils::dev::test_cmds::{ - assert_exit_code, path_to_executable, run_command, EXIT_SUCCESS, + EXIT_SUCCESS, assert_exit_code, path_to_executable, run_command, }; use subprocess::Exec; @@ -44,11 +44,13 @@ fn test_cert_create() { let private_key = openssl::pkey::PKey::private_key_from_pem(&key_contents) .context("parsing private key") .unwrap(); - assert!(certs_pem - .iter() - .last() - .unwrap() - .public_key() - .unwrap() - .public_eq(&private_key)); + assert!( + certs_pem + .iter() + .last() + .unwrap() + .public_key() + .unwrap() + .public_eq(&private_key) + ); } diff --git a/dev-tools/ch-dev/src/main.rs b/dev-tools/ch-dev/src/main.rs index ea4719f46ce..0cd6a2a26c4 100644 --- a/dev-tools/ch-dev/src/main.rs +++ b/dev-tools/ch-dev/src/main.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use clap::{Args, Parser, Subcommand}; use dropshot::test_util::LogContext; use futures::StreamExt; diff --git a/dev-tools/clickana/src/chart.rs b/dev-tools/clickana/src/chart.rs index f8a78fb63dc..907b1608dad 100644 --- a/dev-tools/clickana/src/chart.rs +++ b/dev-tools/clickana/src/chart.rs @@ -2,16 +2,16 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use chrono::{DateTime, Utc}; use clickhouse_admin_server_client::types::{SystemTable, SystemTimeSeries}; use ratatui::{ + Frame, layout::{Constraint, Rect}, style::{Color, Style, Stylize}, symbols::Marker, text::Line, widgets::{Axis, Block, Chart, Dataset, GraphType, LegendPosition}, - Frame, }; use std::fmt::Display; @@ -186,11 +186,7 @@ fn padded_min_value_raw(unit: Unit, min_value_raw: &f64) -> Result { } Unit::Gibibyte | Unit::Mebibyte => { let bytes = unit.as_bytes_f64()?; - if *min_value_raw <= bytes { - 0.0 - } else { - min_value_raw - bytes - } + if *min_value_raw <= bytes { 0.0 } else { min_value_raw - bytes } } }; Ok(padded_value.floor()) @@ -211,11 +207,7 @@ fn padded_min_value_as_unit(unit: Unit, min_value_raw: &f64) -> Result { } Unit::Gibibyte | Unit::Mebibyte => { let value_as_unit = min_value_raw / unit.as_bytes_f64()?; - if value_as_unit < 1.0 { - 0.0 - } else { - value_as_unit - 1.0 - } + if value_as_unit < 1.0 { 0.0 } else { value_as_unit - 1.0 } } }; Ok(padded_value.floor()) @@ -431,11 +423,13 @@ impl ChartData { } pub fn render_line_chart(&self, frame: &mut Frame, area: Rect) { - let datasets = vec![Dataset::default() - .marker(Marker::Braille) - .style(Style::default().fg(Color::LightGreen)) - .graph_type(GraphType::Line) - .data(&self.data_points.data)]; + let datasets = vec![ + Dataset::default() + .marker(Marker::Braille) + .style(Style::default().fg(Color::LightGreen)) + .graph_type(GraphType::Line) + .data(&self.data_points.data), + ]; let chart = Chart::new(datasets) .block( @@ -530,8 +524,8 @@ impl ChartData { #[cfg(test)] mod tests { use crate::{ - chart::{Unit, YAxisValues}, ChartData, ChartMetadata, MetricName, + chart::{Unit, YAxisValues}, }; use chrono::DateTime; use clickhouse_admin_server_client::types::SystemTimeSeries; diff --git a/dev-tools/clickana/src/lib.rs b/dev-tools/clickana/src/lib.rs index 76af35ba8de..601ca17fe1d 100644 --- a/dev-tools/clickana/src/lib.rs +++ b/dev-tools/clickana/src/lib.rs @@ -2,15 +2,15 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use camino::Utf8PathBuf; use chrono::{DateTime, Utc}; +use clickhouse_admin_server_client::Client as ClickhouseServerClient; use clickhouse_admin_server_client::types::{ SystemTimeSeries, TimestampFormat, }; -use clickhouse_admin_server_client::Client as ClickhouseServerClient; -use futures::stream::FuturesOrdered; use futures::StreamExt; +use futures::stream::FuturesOrdered; use omicron_common::FileKv; use ratatui::crossterm::event::{self, Event, KeyCode}; use ratatui::layout::{Constraint, Layout, Rect}; @@ -18,7 +18,7 @@ use ratatui::style::{Color, Style, Stylize}; use ratatui::text::Span; use ratatui::widgets::Paragraph; use ratatui::{DefaultTerminal, Frame}; -use slog::{o, Drain, Logger}; +use slog::{Drain, Logger, o}; use slog_async::Async; use slog_term::{FullFormat, PlainDecorator}; use std::collections::BTreeMap; diff --git a/dev-tools/crdb-seed/src/main.rs b/dev-tools/crdb-seed/src/main.rs index 26b0e19410e..d7384fe6f85 100644 --- a/dev-tools/crdb-seed/src/main.rs +++ b/dev-tools/crdb-seed/src/main.rs @@ -3,11 +3,11 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use anyhow::{Context, Result}; -use dropshot::{test_util::LogContext, ConfigLogging, ConfigLoggingLevel}; +use dropshot::{ConfigLogging, ConfigLoggingLevel, test_util::LogContext}; +use omicron_test_utils::dev::CRDB_SEED_TAR_ENV; use omicron_test_utils::dev::seed::{ ensure_seed_tarball_exists, should_invalidate_seed, }; -use omicron_test_utils::dev::CRDB_SEED_TAR_ENV; use std::io::Write; #[tokio::main] diff --git a/dev-tools/db-dev/src/main.rs b/dev-tools/db-dev/src/main.rs index 21a129f8494..f0584c02b6f 100644 --- a/dev-tools/db-dev/src/main.rs +++ b/dev-tools/db-dev/src/main.rs @@ -4,7 +4,7 @@ //! Developer tool for operating on Nexus databases. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::Utf8PathBuf; use clap::{Args, Parser, Subcommand}; use futures::stream::StreamExt; diff --git a/dev-tools/db-dev/tests/test-db-dev.rs b/dev-tools/db-dev/tests/test-db-dev.rs index 1f2dc27dcf4..90ce9f65523 100644 --- a/dev-tools/db-dev/tests/test-db-dev.rs +++ b/dev-tools/db-dev/tests/test-db-dev.rs @@ -11,7 +11,7 @@ use omicron_test_utils::dev::{ db::has_omicron_schema, process_running, test_cmds::{ - assert_exit_code, path_to_executable, run_command, EXIT_USAGE, + EXIT_USAGE, assert_exit_code, path_to_executable, run_command, }, }; use subprocess::{Exec, ExitStatus, Redirection}; diff --git a/dev-tools/downloader/src/lib.rs b/dev-tools/downloader/src/lib.rs index f98f0f5655d..c29bfe4b9c2 100644 --- a/dev-tools/downloader/src/lib.rs +++ b/dev-tools/downloader/src/lib.rs @@ -7,14 +7,14 @@ //! This is a separate binary because it requires many dependencies that other //! parts of `cargo xtask` do not. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::{Utf8Path, Utf8PathBuf}; use clap::Parser; use clap::ValueEnum; use flate2::bufread::GzDecoder; use futures::StreamExt; use sha2::Digest; -use slog::{info, o, warn, Drain, Logger}; +use slog::{Drain, Logger, info, o, warn}; use std::collections::{BTreeSet, HashMap}; use std::io::Write; use std::os::unix::fs::PermissionsExt; @@ -586,7 +586,9 @@ impl Downloader<'_> { }; let tarball_filename = "cockroach.tgz"; - let tarball_url = format!("{BUILDOMAT_URL}/oxidecomputer/cockroach/{build}/{commit}/{tarball_filename}"); + let tarball_url = format!( + "{BUILDOMAT_URL}/oxidecomputer/cockroach/{build}/{commit}/{tarball_filename}" + ); let tarball_path = download_dir.join(tarball_filename); tokio::fs::create_dir_all(&download_dir).await?; diff --git a/dev-tools/downloader/src/main.rs b/dev-tools/downloader/src/main.rs index eacddd476ee..99999dcc27e 100644 --- a/dev-tools/downloader/src/main.rs +++ b/dev-tools/downloader/src/main.rs @@ -3,7 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use clap::Parser; -use xtask_downloader::{run_cmd, DownloadArgs}; +use xtask_downloader::{DownloadArgs, run_cmd}; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/dev-tools/ls-apis/src/api_metadata.rs b/dev-tools/ls-apis/src/api_metadata.rs index 01f133debe9..fc83942d707 100644 --- a/dev-tools/ls-apis/src/api_metadata.rs +++ b/dev-tools/ls-apis/src/api_metadata.rs @@ -4,13 +4,13 @@ //! Developer-maintained API metadata -use crate::cargo::DepPath; -use crate::workspaces::Workspaces; use crate::ClientPackageName; use crate::DeploymentUnitName; use crate::ServerComponentName; use crate::ServerPackageName; -use anyhow::{bail, Result}; +use crate::cargo::DepPath; +use crate::workspaces::Workspaces; +use anyhow::{Result, bail}; use serde::Deserialize; use std::borrow::Borrow; use std::collections::BTreeMap; diff --git a/dev-tools/ls-apis/src/bin/ls-apis.rs b/dev-tools/ls-apis/src/bin/ls-apis.rs index ea0ae48cd4b..05d03788758 100644 --- a/dev-tools/ls-apis/src/bin/ls-apis.rs +++ b/dev-tools/ls-apis/src/bin/ls-apis.rs @@ -4,7 +4,7 @@ //! Show information about Progenitor-based APIs -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::Utf8PathBuf; use clap::{Args, Parser, Subcommand}; use omicron_ls_apis::{ diff --git a/dev-tools/ls-apis/src/cargo.rs b/dev-tools/ls-apis/src/cargo.rs index f3e5f56bc34..01d7bb98220 100644 --- a/dev-tools/ls-apis/src/cargo.rs +++ b/dev-tools/ls-apis/src/cargo.rs @@ -6,7 +6,7 @@ use crate::ClientPackageName; use anyhow::bail; -use anyhow::{anyhow, ensure, Context, Result}; +use anyhow::{Context, Result, anyhow, ensure}; use camino::Utf8Path; use camino::Utf8PathBuf; use cargo_metadata::{CargoOpt, Package}; @@ -311,11 +311,7 @@ impl Workspace { pkgname: &'a str, ) -> impl Iterator + 'a { self.packages_by_id.iter().filter_map(move |(pkgid, pkg)| { - if pkg.name == pkgname { - Some(pkgid) - } else { - None - } + if pkg.name == pkgname { Some(pkgid) } else { None } }) } diff --git a/dev-tools/ls-apis/src/lib.rs b/dev-tools/ls-apis/src/lib.rs index c27606c25fb..4da58bfe892 100644 --- a/dev-tools/ls-apis/src/lib.rs +++ b/dev-tools/ls-apis/src/lib.rs @@ -17,8 +17,8 @@ pub use system_apis::SystemApis; use anyhow::{Context, Result}; use camino::Utf8Path; use camino::Utf8PathBuf; -use serde::de::DeserializeOwned; use serde::Deserialize; +use serde::de::DeserializeOwned; use std::borrow::Borrow; #[macro_use] diff --git a/dev-tools/ls-apis/src/system_apis.rs b/dev-tools/ls-apis/src/system_apis.rs index ef6dae0e43c..edcd3d019b8 100644 --- a/dev-tools/ls-apis/src/system_apis.rs +++ b/dev-tools/ls-apis/src/system_apis.rs @@ -5,6 +5,11 @@ //! Query information about the Dropshot/OpenAPI/Progenitor-based APIs within //! the Oxide system +use crate::ClientPackageName; +use crate::DeploymentUnitName; +use crate::LoadArgs; +use crate::ServerComponentName; +use crate::ServerPackageName; use crate::api_metadata::AllApiMetadata; use crate::api_metadata::ApiMetadata; use crate::api_metadata::Evaluation; @@ -12,13 +17,8 @@ use crate::api_metadata::VersionedHow; use crate::cargo::DepPath; use crate::parse_toml_file; use crate::workspaces::Workspaces; -use crate::ClientPackageName; -use crate::DeploymentUnitName; -use crate::LoadArgs; -use crate::ServerComponentName; -use crate::ServerPackageName; use anyhow::Result; -use anyhow::{anyhow, bail, Context}; +use anyhow::{Context, anyhow, bail}; use camino::Utf8PathBuf; use cargo_metadata::Package; use parse_display::{Display, FromStr}; @@ -882,11 +882,12 @@ impl<'a> ServerComponentsTracker<'a> { ); } - assert!(self - .unit_server_components - .entry(deployment_unit.clone()) - .or_default() - .insert(server_component.clone())); + assert!( + self.unit_server_components + .entry(deployment_unit.clone()) + .or_default() + .insert(server_component.clone()) + ); Ok(()) } } diff --git a/dev-tools/ls-apis/src/workspaces.rs b/dev-tools/ls-apis/src/workspaces.rs index 143f1e59e03..f2723fc69a1 100644 --- a/dev-tools/ls-apis/src/workspaces.rs +++ b/dev-tools/ls-apis/src/workspaces.rs @@ -4,10 +4,10 @@ //! Combines information about multiple `Workspace`s +use crate::ClientPackageName; use crate::api_metadata::AllApiMetadata; use crate::cargo::Workspace; -use crate::ClientPackageName; -use anyhow::{anyhow, ensure, Context, Result}; +use anyhow::{Context, Result, anyhow, ensure}; use camino::Utf8Path; use cargo_metadata::CargoOpt; use cargo_metadata::Package; diff --git a/dev-tools/ls-apis/tests/test_dependencies.rs b/dev-tools/ls-apis/tests/test_dependencies.rs index ffb0edc566b..3497e7b807d 100644 --- a/dev-tools/ls-apis/tests/test_dependencies.rs +++ b/dev-tools/ls-apis/tests/test_dependencies.rs @@ -9,10 +9,10 @@ //! //! This isn't (supposed to be) a test for the `ls-apis` tool itself. +use omicron_test_utils::dev::test_cmds::EXIT_SUCCESS; use omicron_test_utils::dev::test_cmds::assert_exit_code; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; -use omicron_test_utils::dev::test_cmds::EXIT_SUCCESS; /// name of the "ls-apis" executable const CMD_LS_APIS: &str = env!("CARGO_BIN_EXE_ls-apis"); diff --git a/dev-tools/omdb/src/bin/omdb/crucible_agent.rs b/dev-tools/omdb/src/bin/omdb/crucible_agent.rs index 102f7b4c7e4..5b95fcde446 100644 --- a/dev-tools/omdb/src/bin/omdb/crucible_agent.rs +++ b/dev-tools/omdb/src/bin/omdb/crucible_agent.rs @@ -4,16 +4,16 @@ //! omdb commands that query a crucible-agent -use anyhow::bail; use anyhow::Context; +use anyhow::bail; use clap::Args; use clap::Subcommand; -use crucible_agent_client::types::RegionId; use crucible_agent_client::Client; +use crucible_agent_client::types::RegionId; use tabled::Tabled; -use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::Omdb; +use crate::helpers::CONNECTION_OPTIONS_HEADING; /// Arguments to the "omdb crucible-agent" subcommand #[derive(Debug, Args)] diff --git a/dev-tools/omdb/src/bin/omdb/db.rs b/dev-tools/omdb/src/bin/omdb/db.rs index 4bdf3a023da..518243e0c71 100644 --- a/dev-tools/omdb/src/bin/omdb/db.rs +++ b/dev-tools/omdb/src/bin/omdb/db.rs @@ -17,34 +17,34 @@ // NOTE: allowing "transaction_async" without retry #![allow(clippy::disallowed_methods)] +use crate::Omdb; use crate::check_allow_destructive::DestructiveOperationToken; -use crate::helpers::const_max_len; use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::helpers::DATABASE_OPTIONS_HEADING; -use crate::Omdb; -use anyhow::bail; +use crate::helpers::const_max_len; use anyhow::Context; +use anyhow::bail; use async_bb8_diesel::AsyncConnection; use async_bb8_diesel::AsyncRunQueryDsl; use async_bb8_diesel::AsyncSimpleConnection; use chrono::DateTime; use chrono::SecondsFormat; use chrono::Utc; -use clap::builder::PossibleValue; -use clap::builder::PossibleValuesParser; -use clap::builder::TypedValueParser; use clap::ArgAction; use clap::Args; use clap::Subcommand; use clap::ValueEnum; -use diesel::expression::SelectableHelper; -use diesel::query_dsl::QueryDsl; +use clap::builder::PossibleValue; +use clap::builder::PossibleValuesParser; +use clap::builder::TypedValueParser; use diesel::BoolExpressionMethods; use diesel::ExpressionMethods; use diesel::JoinOnDsl; use diesel::NullableExpressionMethods; use diesel::OptionalExtension; use diesel::TextExpressionMethods; +use diesel::expression::SelectableHelper; +use diesel::query_dsl::QueryDsl; use gateway_client::types::SpType; use indicatif::ProgressBar; use indicatif::ProgressDrawTarget; @@ -53,7 +53,6 @@ use internal_dns_types::names::ServiceName; use ipnetwork::IpNetwork; use itertools::Itertools; use nexus_config::PostgresConfigWithUrl; -use nexus_db_model::to_db_typed_uuid; use nexus_db_model::CrucibleDataset; use nexus_db_model::Disk; use nexus_db_model::DnsGroup; @@ -97,18 +96,19 @@ use nexus_db_model::Volume; use nexus_db_model::VolumeRepair; use nexus_db_model::VpcSubnet; use nexus_db_model::Zpool; +use nexus_db_model::to_db_typed_uuid; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; -use nexus_db_queries::db::datastore::read_only_resources_associated_with_volume; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::CrucibleTargets; use nexus_db_queries::db::datastore::DataStoreConnection; use nexus_db_queries::db::datastore::InstanceAndActiveVmm; +use nexus_db_queries::db::datastore::read_only_resources_associated_with_volume; use nexus_db_queries::db::identity::Asset; use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::ServiceKind; use nexus_db_queries::db::pagination::paginated; use nexus_db_queries::db::queries::ALLOW_FULL_TABLE_SCAN_SQL; -use nexus_db_queries::db::DataStore; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; @@ -3352,7 +3352,9 @@ async fn cmd_db_instance_info( } }; if vmm.is_none() { - eprintln!(" /!\\ BAD: instance has an active VMM ({id}) but no matching VMM record was found!"); + eprintln!( + " /!\\ BAD: instance has an active VMM ({id}) but no matching VMM record was found!" + ); } vmm } else { @@ -3441,7 +3443,7 @@ async fn cmd_db_instance_info( } println!("\n{:=<80}", "== CONFIGURATION "); - println!(" {VCPUS:>WIDTH$}: {}", instance.ncpus.0 .0); + println!(" {VCPUS:>WIDTH$}: {}", instance.ncpus.0.0); println!(" {MEMORY:>WIDTH$}: {}", instance.memory.0); println!(" {HOSTNAME:>WIDTH$}: {}", instance.hostname); println!(" {BOOT_DISK:>WIDTH$}: {:?}", instance.boot_disk_id); @@ -4932,9 +4934,9 @@ async fn cmd_db_validate_regions( continue; } + use crucible_agent_client::Client as CrucibleAgentClient; use crucible_agent_client::types::RegionId; use crucible_agent_client::types::State; - use crucible_agent_client::Client as CrucibleAgentClient; let dataset_addr = dataset.address(); let url = format!("http://{}", dataset_addr); @@ -5050,8 +5052,8 @@ async fn cmd_db_validate_regions( continue; } - use crucible_agent_client::types::State; use crucible_agent_client::Client as CrucibleAgentClient; + use crucible_agent_client::types::State; let dataset_addr = dataset.address(); let url = format!("http://{}", dataset_addr); @@ -5199,9 +5201,9 @@ async fn cmd_db_validate_region_snapshots( continue; } + use crucible_agent_client::Client as CrucibleAgentClient; use crucible_agent_client::types::RegionId; use crucible_agent_client::types::State; - use crucible_agent_client::Client as CrucibleAgentClient; let dataset_addr = dataset.address(); let url = format!("http://{}", dataset_addr); @@ -5375,9 +5377,9 @@ async fn cmd_db_validate_region_snapshots( continue; } + use crucible_agent_client::Client as CrucibleAgentClient; use crucible_agent_client::types::RegionId; use crucible_agent_client::types::State; - use crucible_agent_client::Client as CrucibleAgentClient; let dataset_addr = dataset.address(); let url = format!("http://{}", dataset_addr); diff --git a/dev-tools/omdb/src/bin/omdb/main.rs b/dev-tools/omdb/src/bin/omdb/main.rs index 4048091e2b2..2228a78db3a 100644 --- a/dev-tools/omdb/src/bin/omdb/main.rs +++ b/dev-tools/omdb/src/bin/omdb/main.rs @@ -33,9 +33,9 @@ //! find strange things when debugging but we need our tools to tell us as //! much as they can!) +use anyhow::Context; use anyhow::anyhow; use anyhow::ensure; -use anyhow::Context; use clap::Args; use clap::ColorChoice; use clap::Parser; diff --git a/dev-tools/omdb/src/bin/omdb/mgs.rs b/dev-tools/omdb/src/bin/omdb/mgs.rs index 7d8ddf2a50b..56bfc1263cb 100644 --- a/dev-tools/omdb/src/bin/omdb/mgs.rs +++ b/dev-tools/omdb/src/bin/omdb/mgs.rs @@ -4,8 +4,8 @@ //! Prototype code for collecting information from systems in the rack -use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::Omdb; +use crate::helpers::CONNECTION_OPTIONS_HEADING; use anyhow::Context; use clap::Args; use clap::Subcommand; diff --git a/dev-tools/omdb/src/bin/omdb/mgs/dashboard.rs b/dev-tools/omdb/src/bin/omdb/mgs/dashboard.rs index b3f34d57910..9fcf51c285c 100644 --- a/dev-tools/omdb/src/bin/omdb/mgs/dashboard.rs +++ b/dev-tools/omdb/src/bin/omdb/mgs/dashboard.rs @@ -13,12 +13,13 @@ use crossterm::{ }, execute, terminal::{ - disable_raw_mode, enable_raw_mode, EnterAlternateScreen, - LeaveAlternateScreen, + EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, + enable_raw_mode, }, }; use dyn_clone::DynClone; use ratatui::{ + Frame, Terminal, backend::{Backend, CrosstermBackend}, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, @@ -28,12 +29,11 @@ use ratatui::{ Axis, Block, Borders, Chart, Dataset, List, ListItem, ListState, Paragraph, }, - Frame, Terminal, }; use crate::mgs::sensors::{ - sensor_data, sensor_metadata, SensorId, SensorInput, SensorMetadata, - SensorValues, SensorsArgs, + SensorId, SensorInput, SensorMetadata, SensorValues, SensorsArgs, + sensor_data, sensor_metadata, }; use crate::mgs::sp_to_string; use clap::Args; diff --git a/dev-tools/omdb/src/bin/omdb/mgs/sensors.rs b/dev-tools/omdb/src/bin/omdb/mgs/sensors.rs index f36e8633f96..840909fd99b 100644 --- a/dev-tools/omdb/src/bin/omdb/mgs/sensors.rs +++ b/dev-tools/omdb/src/bin/omdb/mgs/sensors.rs @@ -4,7 +4,7 @@ //! Implementation of the "mgs sensors" subcommand -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use clap::Args; use gateway_client::types::MeasurementErrorCode; use gateway_client::types::MeasurementKind; diff --git a/dev-tools/omdb/src/bin/omdb/nexus.rs b/dev-tools/omdb/src/bin/omdb/nexus.rs index 208b43d054c..ec903d6de23 100644 --- a/dev-tools/omdb/src/bin/omdb/nexus.rs +++ b/dev-tools/omdb/src/bin/omdb/nexus.rs @@ -4,14 +4,14 @@ //! omdb commands that query or update specific Nexus instances +use crate::Omdb; use crate::check_allow_destructive::DestructiveOperationToken; use crate::db::DbUrlOptions; +use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::helpers::const_max_len; use crate::helpers::should_colorize; -use crate::helpers::CONNECTION_OPTIONS_HEADING; -use crate::Omdb; -use anyhow::bail; use anyhow::Context; +use anyhow::bail; use camino::Utf8PathBuf; use chrono::DateTime; use chrono::SecondsFormat; @@ -20,8 +20,8 @@ use clap::Args; use clap::ColorChoice; use clap::Subcommand; use clap::ValueEnum; -use futures::future::try_join; use futures::TryStreamExt; +use futures::future::try_join; use http::StatusCode; use internal_dns_types::names::ServiceName; use itertools::Itertools; @@ -34,8 +34,8 @@ use nexus_client::types::PhysicalDiskPath; use nexus_client::types::SagaState; use nexus_client::types::SledSelector; use nexus_client::types::UninitializedSledId; -use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::lookup::LookupPath; use nexus_inventory::now_db_precision; use nexus_saga_recovery::LastPass; use nexus_types::deployment::Blueprint; @@ -75,21 +75,21 @@ use std::collections::BTreeMap; use std::collections::BTreeSet; use std::str::FromStr; use std::sync::Arc; -use tabled::settings::object::Columns; -use tabled::settings::Padding; use tabled::Tabled; +use tabled::settings::Padding; +use tabled::settings::object::Columns; use tokio::sync::OnceCell; -use update_engine::display::LineDisplay; -use update_engine::display::LineDisplayStyles; -use update_engine::display::ProgressRatioDisplay; -use update_engine::events::EventReport; -use update_engine::events::StepOutcome; use update_engine::EventBuffer; use update_engine::ExecutionStatus; use update_engine::ExecutionTerminalInfo; use update_engine::NestedError; use update_engine::NestedSpec; use update_engine::TerminalKind; +use update_engine::display::LineDisplay; +use update_engine::display::LineDisplayStyles; +use update_engine::display::ProgressRatioDisplay; +use update_engine::events::EventReport; +use update_engine::events::StepOutcome; use uuid::Uuid; /// Arguments to the "omdb nexus" subcommand @@ -2153,11 +2153,21 @@ fn print_task_support_bundle_collector(details: &serde_json::Value) { }) = cleanup_report { println!(" Support Bundle Cleanup Report:"); - println!(" Bundles deleted from sleds: {sled_bundles_deleted_ok}"); - println!(" Bundles not found on sleds: {sled_bundles_deleted_not_found}"); - println!(" Bundles delete failed on sleds: {sled_bundles_delete_failed}"); - println!(" Bundles deleted from database: {db_destroying_bundles_removed}"); - println!(" Bundles marked failed in database: {db_failing_bundles_updated}"); + println!( + " Bundles deleted from sleds: {sled_bundles_deleted_ok}" + ); + println!( + " Bundles not found on sleds: {sled_bundles_deleted_not_found}" + ); + println!( + " Bundles delete failed on sleds: {sled_bundles_delete_failed}" + ); + println!( + " Bundles deleted from database: {db_destroying_bundles_removed}" + ); + println!( + " Bundles marked failed in database: {db_failing_bundles_updated}" + ); } if let Some(collection_err) = collection_err { @@ -2172,8 +2182,12 @@ fn print_task_support_bundle_collector(details: &serde_json::Value) { { println!(" Support Bundle Collection Report:"); println!(" Bundle ID: {bundle}"); - println!(" Bundle was able to list in-service sleds: {listed_in_service_sleds}"); - println!(" Bundle was activated in the database: {activated_in_db_ok}"); + println!( + " Bundle was able to list in-service sleds: {listed_in_service_sleds}" + ); + println!( + " Bundle was activated in the database: {activated_in_db_ok}" + ); } } } diff --git a/dev-tools/omdb/src/bin/omdb/oximeter.rs b/dev-tools/omdb/src/bin/omdb/oximeter.rs index 7dae63e947c..b3d6bcafd67 100644 --- a/dev-tools/omdb/src/bin/omdb/oximeter.rs +++ b/dev-tools/omdb/src/bin/omdb/oximeter.rs @@ -4,19 +4,19 @@ //! omdb commands that query oximeter -use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::Omdb; +use crate::helpers::CONNECTION_OPTIONS_HEADING; use anyhow::Context; use chrono::SecondsFormat; use clap::Args; use clap::Subcommand; use futures::TryStreamExt; use internal_dns_types::names::ServiceName; +use oximeter_client::Client; use oximeter_client::types::FailedCollection; use oximeter_client::types::ProducerDetails; use oximeter_client::types::ProducerEndpoint; use oximeter_client::types::SuccessfulCollection; -use oximeter_client::Client; use slog::Logger; use std::net::SocketAddr; use std::time::Duration; diff --git a/dev-tools/omdb/src/bin/omdb/oxql.rs b/dev-tools/omdb/src/bin/omdb/oxql.rs index 39736d8fda4..1746b2bbe00 100644 --- a/dev-tools/omdb/src/bin/omdb/oxql.rs +++ b/dev-tools/omdb/src/bin/omdb/oxql.rs @@ -6,8 +6,8 @@ // Copyright 2024 Oxide Computer -use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::Omdb; +use crate::helpers::CONNECTION_OPTIONS_HEADING; use anyhow::Context; use clap::Args; use internal_dns_types::names::ServiceName; diff --git a/dev-tools/omdb/src/bin/omdb/reconfigurator.rs b/dev-tools/omdb/src/bin/omdb/reconfigurator.rs index 1af0c790b7e..487c5b014b6 100644 --- a/dev-tools/omdb/src/bin/omdb/reconfigurator.rs +++ b/dev-tools/omdb/src/bin/omdb/reconfigurator.rs @@ -4,9 +4,9 @@ //! omdb commands that interact with Reconfigurator +use crate::Omdb; use crate::check_allow_destructive::DestructiveOperationToken; use crate::db::DbUrlOptions; -use crate::Omdb; use anyhow::Context as _; use camino::Utf8PathBuf; use clap::Args; diff --git a/dev-tools/omdb/src/bin/omdb/sled_agent.rs b/dev-tools/omdb/src/bin/omdb/sled_agent.rs index 44adbf47638..d02203e052b 100644 --- a/dev-tools/omdb/src/bin/omdb/sled_agent.rs +++ b/dev-tools/omdb/src/bin/omdb/sled_agent.rs @@ -4,10 +4,10 @@ //! omdb commands that query or update specific Sleds -use crate::helpers::CONNECTION_OPTIONS_HEADING; use crate::Omdb; -use anyhow::bail; +use crate::helpers::CONNECTION_OPTIONS_HEADING; use anyhow::Context; +use anyhow::bail; use clap::Args; use clap::Subcommand; diff --git a/dev-tools/omdb/tests/test_all_output.rs b/dev-tools/omdb/tests/test_all_output.rs index 148b8eb1452..146965273d3 100644 --- a/dev-tools/omdb/tests/test_all_output.rs +++ b/dev-tools/omdb/tests/test_all_output.rs @@ -16,9 +16,9 @@ use nexus_test_utils_macros::nexus_test; use nexus_types::deployment::Blueprint; use nexus_types::deployment::SledFilter; use nexus_types::deployment::UnstableReconfiguratorState; +use omicron_test_utils::dev::test_cmds::Redactor; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; -use omicron_test_utils::dev::test_cmds::Redactor; use slog_error_chain::InlineErrorChain; use std::fmt::Write; use std::net::IpAddr; @@ -276,11 +276,13 @@ async fn test_omdb_success_cases(cptestctx: &ControlPlaneTestContext) { }); // Did we find at least one sled in the planning input, and at least one // collection? - assert!(parsed - .planning_input - .all_sled_ids(SledFilter::Commissioned) - .next() - .is_some()); + assert!( + parsed + .planning_input + .all_sled_ids(SledFilter::Commissioned) + .next() + .is_some() + ); assert!(!parsed.collections.is_empty()); let ox_invocation = &["oximeter", "list-producers"]; diff --git a/dev-tools/omicron-dev/tests/test-omicron-dev.rs b/dev-tools/omicron-dev/tests/test-omicron-dev.rs index 927b6002838..da6decd1a6d 100644 --- a/dev-tools/omicron-dev/tests/test-omicron-dev.rs +++ b/dev-tools/omicron-dev/tests/test-omicron-dev.rs @@ -7,13 +7,13 @@ use anyhow::Context; use expectorate::assert_contents; use omicron_dev_lib::test_utils::verify_graceful_exit; +use omicron_test_utils::dev::CRDB_SEED_TAR_ENV; use omicron_test_utils::dev::db::has_omicron_schema; use omicron_test_utils::dev::process_running; +use omicron_test_utils::dev::test_cmds::EXIT_USAGE; use omicron_test_utils::dev::test_cmds::assert_exit_code; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; -use omicron_test_utils::dev::test_cmds::EXIT_USAGE; -use omicron_test_utils::dev::CRDB_SEED_TAR_ENV; use oxide_client::ClientHiddenExt; use std::io::BufRead; use std::path::PathBuf; diff --git a/dev-tools/openapi-manager/src/check.rs b/dev-tools/openapi-manager/src/check.rs index b43e43e7e57..bbe6f2d54dc 100644 --- a/dev-tools/openapi-manager/src/check.rs +++ b/dev-tools/openapi-manager/src/check.rs @@ -10,12 +10,12 @@ use owo_colors::OwoColorize; use similar::TextDiff; use crate::{ + FAILURE_EXIT_CODE, NEEDS_UPDATE_EXIT_CODE, output::{ - display_api_spec, display_api_spec_file, display_error, - display_summary, headers::*, plural, write_diff, OutputOpts, Styles, + OutputOpts, Styles, display_api_spec, display_api_spec_file, + display_error, display_summary, headers::*, plural, write_diff, }, - spec::{all_apis, CheckStale, Environment}, - FAILURE_EXIT_CODE, NEEDS_UPDATE_EXIT_CODE, + spec::{CheckStale, Environment, all_apis}, }; #[derive(Clone, Copy, Debug)] @@ -109,7 +109,7 @@ pub(crate) fn check_impl( eprintln!( "{:>HEADER_WIDTH$}{count_section_indent}\ ({error_count:>total_errors_width$}/{total_errors}) {}", - heading.style(styles.warning_header), + heading.style(styles.warning_header), display_api_spec_file(spec, spec_file, &styles), ); }; diff --git a/dev-tools/openapi-manager/src/generate.rs b/dev-tools/openapi-manager/src/generate.rs index 1cf9ebbb613..a556bfaa58a 100644 --- a/dev-tools/openapi-manager/src/generate.rs +++ b/dev-tools/openapi-manager/src/generate.rs @@ -9,12 +9,12 @@ use indent_write::io::IndentWriter; use owo_colors::OwoColorize; use crate::{ + FAILURE_EXIT_CODE, output::{ - display_api_spec, display_error, display_summary, headers::*, plural, - OutputOpts, Styles, + OutputOpts, Styles, display_api_spec, display_error, display_summary, + headers::*, plural, }, - spec::{all_apis, Environment}, - FAILURE_EXIT_CODE, + spec::{Environment, all_apis}, }; #[derive(Clone, Copy, Debug)] diff --git a/dev-tools/openapi-manager/src/list.rs b/dev-tools/openapi-manager/src/list.rs index bf1920c69d2..2f72d2bdcc0 100644 --- a/dev-tools/openapi-manager/src/list.rs +++ b/dev-tools/openapi-manager/src/list.rs @@ -8,7 +8,7 @@ use indent_write::io::IndentWriter; use owo_colors::OwoColorize; use crate::{ - output::{display_api_spec, display_error, OutputOpts, Styles}, + output::{OutputOpts, Styles, display_api_spec, display_error}, spec::all_apis, }; diff --git a/dev-tools/openapi-manager/src/output.rs b/dev-tools/openapi-manager/src/output.rs index fee7f0f15cb..e410a1b5c56 100644 --- a/dev-tools/openapi-manager/src/output.rs +++ b/dev-tools/openapi-manager/src/output.rs @@ -256,34 +256,18 @@ pub(crate) mod headers { pub(crate) mod plural { pub(crate) fn files(count: usize) -> &'static str { - if count == 1 { - "file" - } else { - "files" - } + if count == 1 { "file" } else { "files" } } pub(crate) fn documents(count: usize) -> &'static str { - if count == 1 { - "document" - } else { - "documents" - } + if count == 1 { "document" } else { "documents" } } pub(crate) fn paths(count: usize) -> &'static str { - if count == 1 { - "path" - } else { - "paths" - } + if count == 1 { "path" } else { "paths" } } pub(crate) fn schemas(count: usize) -> &'static str { - if count == 1 { - "schema" - } else { - "schemas" - } + if count == 1 { "schema" } else { "schemas" } } } diff --git a/dev-tools/oxlog/src/lib.rs b/dev-tools/oxlog/src/lib.rs index a7b936d289d..777ef4928c5 100644 --- a/dev-tools/oxlog/src/lib.rs +++ b/dev-tools/oxlog/src/lib.rs @@ -25,11 +25,7 @@ fn get_uuid_dir(result: io::Result) -> Option { return None; } let file_name = entry.file_name(); - if let Ok(uuid) = file_name.parse() { - Some(uuid) - } else { - None - } + if let Ok(uuid) = file_name.parse() { Some(uuid) } else { None } } #[derive(Debug)] @@ -484,18 +480,24 @@ mod tests { "system-illumos-blah:default.log.0" ) ); - assert!(oxide_smf_service_name_from_log_file_name( - "not-oxide-blah:default.log" - ) - .is_none()); - assert!(oxide_smf_service_name_from_log_file_name( - "not-system-illumos-blah:default.log" - ) - .is_none()); - assert!(oxide_smf_service_name_from_log_file_name( - "system-blah:default.log" - ) - .is_none()); + assert!( + oxide_smf_service_name_from_log_file_name( + "not-oxide-blah:default.log" + ) + .is_none() + ); + assert!( + oxide_smf_service_name_from_log_file_name( + "not-system-illumos-blah:default.log" + ) + .is_none() + ); + assert!( + oxide_smf_service_name_from_log_file_name( + "system-blah:default.log" + ) + .is_none() + ); } #[test] diff --git a/dev-tools/reconfigurator-cli/src/log_capture.rs b/dev-tools/reconfigurator-cli/src/log_capture.rs index 6216fa5d78b..94aa0ae1364 100644 --- a/dev-tools/reconfigurator-cli/src/log_capture.rs +++ b/dev-tools/reconfigurator-cli/src/log_capture.rs @@ -7,10 +7,10 @@ use colored::Color; use colored::Colorize; use slog::Drain; +use slog::KV as _; use slog::Level; use slog::LevelFilter; use slog::Logger; -use slog::KV as _; use slog_term::Decorator; use slog_term::PlainSyncDecorator; use slog_term::Serializer; diff --git a/dev-tools/reconfigurator-cli/src/main.rs b/dev-tools/reconfigurator-cli/src/main.rs index a22019143bc..f23b2b34fa0 100644 --- a/dev-tools/reconfigurator-cli/src/main.rs +++ b/dev-tools/reconfigurator-cli/src/main.rs @@ -4,7 +4,7 @@ //! developer REPL for driving blueprint planning -use anyhow::{anyhow, bail, Context}; +use anyhow::{Context, anyhow, bail}; use camino::Utf8PathBuf; use clap::CommandFactory; use clap::FromArgMatches; @@ -24,13 +24,13 @@ use nexus_reconfigurator_planning::system::{SledBuilder, SystemDescription}; use nexus_reconfigurator_simulation::SimState; use nexus_reconfigurator_simulation::SimStateBuilder; use nexus_reconfigurator_simulation::Simulator; -use nexus_types::deployment::execution; -use nexus_types::deployment::execution::blueprint_external_dns_config; -use nexus_types::deployment::execution::blueprint_internal_dns_config; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::OmicronZoneNic; use nexus_types::deployment::PlanningInput; use nexus_types::deployment::SledFilter; +use nexus_types::deployment::execution; +use nexus_types::deployment::execution::blueprint_external_dns_config; +use nexus_types::deployment::execution::blueprint_internal_dns_config; use nexus_types::deployment::{Blueprint, UnstableReconfiguratorState}; use omicron_common::api::external::Generation; use omicron_common::api::external::Name; @@ -48,7 +48,7 @@ use std::collections::BTreeMap; use std::fmt::Write; use std::io::BufRead; use std::io::IsTerminal; -use swrite::{swriteln, SWrite}; +use swrite::{SWrite, swriteln}; use tabled::Tabled; mod log_capture; diff --git a/dev-tools/reconfigurator-cli/tests/test_basic.rs b/dev-tools/reconfigurator-cli/tests/test_basic.rs index bab01156166..6f8dc74e240 100644 --- a/dev-tools/reconfigurator-cli/tests/test_basic.rs +++ b/dev-tools/reconfigurator-cli/tests/test_basic.rs @@ -8,20 +8,20 @@ use expectorate::assert_contents; use nexus_db_queries::authn; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; -use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::SLED_AGENT_UUID; +use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use nexus_types::deployment::Blueprint; use nexus_types::deployment::SledFilter; use nexus_types::deployment::UnstableReconfiguratorState; use omicron_common::api::external::Error; -use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; +use omicron_test_utils::dev::poll::wait_for_condition; +use omicron_test_utils::dev::test_cmds::EXIT_SUCCESS; +use omicron_test_utils::dev::test_cmds::Redactor; use omicron_test_utils::dev::test_cmds::assert_exit_code; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; -use omicron_test_utils::dev::test_cmds::Redactor; -use omicron_test_utils::dev::test_cmds::EXIT_SUCCESS; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::SledUuid; use slog::debug; @@ -32,8 +32,8 @@ use std::sync::Arc; use std::time::Duration; use subprocess::Exec; use subprocess::ExitStatus; -use swrite::swriteln; use swrite::SWrite; +use swrite::swriteln; fn path_to_cli() -> PathBuf { path_to_executable(env!("CARGO_BIN_EXE_reconfigurator-cli")) diff --git a/dev-tools/releng/src/cmd.rs b/dev-tools/releng/src/cmd.rs index 198eabf99ff..18cd0cae9c2 100644 --- a/dev-tools/releng/src/cmd.rs +++ b/dev-tools/releng/src/cmd.rs @@ -9,11 +9,11 @@ use std::process::Output; use std::process::Stdio; use std::time::Instant; -use anyhow::ensure; use anyhow::Context; use anyhow::Result; -use slog::debug; +use anyhow::ensure; use slog::Logger; +use slog::debug; /// Wrapper for `tokio::process::Command` where the builder methods take/return /// `self`, plus a number of convenience methods. diff --git a/dev-tools/releng/src/hubris.rs b/dev-tools/releng/src/hubris.rs index f46af4bfaf8..82157253deb 100644 --- a/dev-tools/releng/src/hubris.rs +++ b/dev-tools/releng/src/hubris.rs @@ -14,8 +14,8 @@ use omicron_common::api::external::SemverVersion; use omicron_common::api::internal::nexus::KnownArtifactKind; use semver::Version; use serde::Deserialize; -use slog::warn; use slog::Logger; +use slog::warn; use tufaceous_lib::assemble::DeserializedArtifactData; use tufaceous_lib::assemble::DeserializedArtifactSource; use tufaceous_lib::assemble::DeserializedFileArtifactSource; diff --git a/dev-tools/releng/src/job.rs b/dev-tools/releng/src/job.rs index 51368c20fb4..fdd40e1e2fd 100644 --- a/dev-tools/releng/src/job.rs +++ b/dev-tools/releng/src/job.rs @@ -21,9 +21,9 @@ use std::process::Stdio; use std::sync::Arc; use std::time::Instant; -use anyhow::anyhow; use anyhow::Context; use anyhow::Result; +use anyhow::anyhow; use camino::Utf8Path; use camino::Utf8PathBuf; use fs_err::tokio::File; @@ -31,16 +31,16 @@ use futures::future::BoxFuture; use futures::future::FutureExt; use futures::stream::FuturesUnordered; use futures::stream::TryStreamExt; -use slog::info; use slog::Logger; +use slog::info; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncRead; use tokio::io::AsyncWrite; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; +use tokio::sync::Semaphore; use tokio::sync::oneshot; use tokio::sync::oneshot::error::RecvError; -use tokio::sync::Semaphore; use crate::cmd::Command; diff --git a/dev-tools/releng/src/main.rs b/dev-tools/releng/src/main.rs index e00020aa83f..f1dd3181b66 100644 --- a/dev-tools/releng/src/main.rs +++ b/dev-tools/releng/src/main.rs @@ -12,9 +12,9 @@ use std::sync::LazyLock; use std::time::Duration; use std::time::Instant; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::bail; use camino::Utf8PathBuf; use chrono::Utc; use clap::Parser; @@ -22,11 +22,11 @@ use fs_err::tokio as fs; use omicron_zone_package::config::Config; use omicron_zone_package::config::PackageName; use semver::Version; +use slog::Drain; +use slog::Logger; use slog::debug; use slog::error; use slog::info; -use slog::Drain; -use slog::Logger; use slog_term::FullFormat; use slog_term::TermDecorator; use tokio::sync::Semaphore; diff --git a/dev-tools/releng/src/tuf.rs b/dev-tools/releng/src/tuf.rs index 011b2ddd474..6078ae9242f 100644 --- a/dev-tools/releng/src/tuf.rs +++ b/dev-tools/releng/src/tuf.rs @@ -20,13 +20,13 @@ use sha2::Digest; use sha2::Sha256; use slog::Logger; use tokio::io::AsyncReadExt; +use tufaceous_lib::Key; use tufaceous_lib::assemble::ArtifactManifest; use tufaceous_lib::assemble::DeserializedArtifactData; use tufaceous_lib::assemble::DeserializedArtifactSource; use tufaceous_lib::assemble::DeserializedControlPlaneZoneSource; use tufaceous_lib::assemble::DeserializedManifest; use tufaceous_lib::assemble::OmicronRepoAssembler; -use tufaceous_lib::Key; pub(crate) async fn build_tuf_repo( logger: Logger, diff --git a/dev-tools/xtask/src/check_features.rs b/dev-tools/xtask/src/check_features.rs index 044f48c3d16..3618b2b224f 100644 --- a/dev-tools/xtask/src/check_features.rs +++ b/dev-tools/xtask/src/check_features.rs @@ -4,7 +4,7 @@ //! Subcommand: cargo xtask check-features -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use camino::Utf8PathBuf; use clap::Parser; use std::{collections::HashSet, process::Command}; diff --git a/dev-tools/xtask/src/check_workspace_deps.rs b/dev-tools/xtask/src/check_workspace_deps.rs index a9627569b97..7163dc3790c 100644 --- a/dev-tools/xtask/src/check_workspace_deps.rs +++ b/dev-tools/xtask/src/check_workspace_deps.rs @@ -4,7 +4,7 @@ //! Subcommand: cargo xtask check-workspace-deps -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::Utf8Path; use cargo_toml::{Dependency, Manifest}; use fs_err as fs; diff --git a/dev-tools/xtask/src/common.rs b/dev-tools/xtask/src/common.rs index 03b17a560f2..d6e83f531b1 100644 --- a/dev-tools/xtask/src/common.rs +++ b/dev-tools/xtask/src/common.rs @@ -4,7 +4,7 @@ //! Common xtask command helpers -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use std::process::Command; /// Runs the given command, printing some basic debug information around it, and diff --git a/dev-tools/xtask/src/live_tests.rs b/dev-tools/xtask/src/live_tests.rs index 3f236ec5597..0bbf9368c99 100644 --- a/dev-tools/xtask/src/live_tests.rs +++ b/dev-tools/xtask/src/live_tests.rs @@ -5,7 +5,7 @@ //! Subcommand: cargo xtask live-tests use crate::common::run_subcmd; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use clap::Parser; use std::process::Command; diff --git a/dev-tools/xtask/src/usdt.rs b/dev-tools/xtask/src/usdt.rs index ad183656a4f..22121f3bac2 100644 --- a/dev-tools/xtask/src/usdt.rs +++ b/dev-tools/xtask/src/usdt.rs @@ -5,9 +5,9 @@ //! Xtask for printing USDT probes. use crate::load_workspace; -use tabled::settings::Style; use tabled::Table; use tabled::Tabled; +use tabled::settings::Style; #[derive(Tabled)] #[tabled(rename_all = "SCREAMING_SNAKE_CASE")] @@ -43,11 +43,7 @@ pub(crate) fn print_probes(filter: Option) -> anyhow::Result<()> { .filter_map(|p| { let path = workspace.target_directory.join(p).join(&bin_target.name); - if path.exists() { - Some(path) - } else { - None - } + if path.exists() { Some(path) } else { None } }) .next(); let Some(path) = maybe_path else { diff --git a/dev-tools/xtask/src/verify_libraries.rs b/dev-tools/xtask/src/verify_libraries.rs index af2b87daf17..4915c7bf866 100644 --- a/dev-tools/xtask/src/verify_libraries.rs +++ b/dev-tools/xtask/src/verify_libraries.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::Utf8Path; use cargo_metadata::Message; use clap::Parser; @@ -13,7 +13,7 @@ use std::{ io::BufReader, process::{Command, Stdio}, }; -use swrite::{swriteln, SWrite}; +use swrite::{SWrite, swriteln}; use crate::load_workspace; diff --git a/dev-tools/xtask/src/virtual_hardware.rs b/dev-tools/xtask/src/virtual_hardware.rs index 29738016f54..0573226b104 100644 --- a/dev-tools/xtask/src/virtual_hardware.rs +++ b/dev-tools/xtask/src/virtual_hardware.rs @@ -4,7 +4,7 @@ //! Subcommand: cargo xtask virtual-hardware -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use camino::{Utf8Path, Utf8PathBuf}; use clap::{Parser, Subcommand}; use macaddr::MacAddr; @@ -210,7 +210,9 @@ fn verify_omicron_uninstalled() -> Result<()> { let mut cmd = Command::new("svcs"); cmd.arg("svc:/oxide/sled-agent:default"); if let Ok(_) = execute(cmd) { - bail!("Omicron is still installed, please run `omicron-package uninstall` first"); + bail!( + "Omicron is still installed, please run `omicron-package uninstall` first" + ); } Ok(()) } @@ -342,7 +344,9 @@ fn ensure_softnpu_zone(npu_zone: &Utf8Path) -> Result<()> { let zones = zoneadm_list()?; if !zones.iter().any(|z| z == "sidecar_softnpu") { if !npu_zone.exists() { - bail!("npu binary is not installed. Please re-run ./tools/install_prerequisites.sh"); + bail!( + "npu binary is not installed. Please re-run ./tools/install_prerequisites.sh" + ); } let mut cmd = Command::new(PFEXEC); diff --git a/dns-server/src/bin/dns-db-dump.rs b/dns-server/src/bin/dns-db-dump.rs index 532689c1cf9..56215fd42f0 100644 --- a/dns-server/src/bin/dns-db-dump.rs +++ b/dns-server/src/bin/dns-db-dump.rs @@ -7,7 +7,7 @@ //! This is a low-level debugging tool, not something we'd expect people to use //! regularly. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use clap::Parser; #[derive(Debug, Parser)] diff --git a/dns-server/src/bin/dns-server.rs b/dns-server/src/bin/dns-server.rs index 9e8d098ee2f..7ba41f94dca 100644 --- a/dns-server/src/bin/dns-server.rs +++ b/dns-server/src/bin/dns-server.rs @@ -5,8 +5,8 @@ //! Executable that starts the HTTP-configurable DNS server used for both //! internal DNS (RFD 248) and external DNS (RFD 357) for the Oxide system -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use clap::Parser; use serde::Deserialize; use slog::info; diff --git a/dns-server/src/bin/dnsadm.rs b/dns-server/src/bin/dnsadm.rs index 372a8109684..b285cf1e38a 100644 --- a/dns-server/src/bin/dnsadm.rs +++ b/dns-server/src/bin/dnsadm.rs @@ -12,9 +12,9 @@ //! - All writes involve a read-modify-write with no ability to avoid clobbering //! a concurrent write. -use anyhow::ensure; use anyhow::Context; use anyhow::Result; +use anyhow::ensure; use clap::{Args, Parser, Subcommand}; use dns_service_client::Client; use internal_dns_types::config::DnsConfig; diff --git a/dns-server/src/dns_server.rs b/dns-server/src/dns_server.rs index 6259c4951e5..9f8e848089c 100644 --- a/dns-server/src/dns_server.rs +++ b/dns-server/src/dns_server.rs @@ -10,14 +10,14 @@ use crate::storage; use crate::storage::QueryError; use crate::storage::Store; -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use hickory_proto::op::Header; use hickory_proto::op::ResponseCode; -use hickory_proto::rr::rdata::SRV; use hickory_proto::rr::RData; use hickory_proto::rr::Record; use hickory_proto::rr::RecordType; +use hickory_proto::rr::rdata::SRV; use hickory_proto::serialize::binary::BinDecodable; use hickory_proto::serialize::binary::BinDecoder; use hickory_proto::serialize::binary::BinEncoder; @@ -29,7 +29,7 @@ use internal_dns_types::config::DnsRecord; use internal_dns_types::config::Srv; use pretty_hex::*; use serde::Deserialize; -use slog::{debug, error, info, o, trace, Logger}; +use slog::{Logger, debug, error, info, o, trace}; use std::net::SocketAddr; use std::str::FromStr; use std::sync::Arc; diff --git a/dns-server/src/lib.rs b/dns-server/src/lib.rs index d509524ee20..0e54ec73b47 100644 --- a/dns-server/src/lib.rs +++ b/dns-server/src/lib.rs @@ -46,12 +46,12 @@ pub mod dns_server; pub mod http_server; pub mod storage; -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; +use hickory_resolver::TokioAsyncResolver; use hickory_resolver::config::NameServerConfig; use hickory_resolver::config::Protocol; use hickory_resolver::config::ResolverConfig; use hickory_resolver::config::ResolverOpts; -use hickory_resolver::TokioAsyncResolver; use internal_dns_types::config::DnsConfigParams; use slog::o; use std::net::SocketAddr; diff --git a/dns-server/src/storage.rs b/dns-server/src/storage.rs index 73e6cff100a..01ade2d383f 100644 --- a/dns-server/src/storage.rs +++ b/dns-server/src/storage.rs @@ -92,7 +92,7 @@ // backwards-compatible way (but obviously one wouldn't get the scaling benefits // while continuing to use the old API). -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use camino::Utf8PathBuf; use hickory_proto::rr::LowerName; use hickory_resolver::Name; @@ -104,9 +104,9 @@ use serde::{Deserialize, Serialize}; use sled::transaction::ConflictableTransactionError; use slog::{debug, error, info, o, warn}; use std::str::FromStr; +use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; -use std::sync::Arc; use thiserror::Error; use tokio::sync::Mutex; diff --git a/dns-server/tests/basic_test.rs b/dns-server/tests/basic_test.rs index 06df402bcae..5ca515320e2 100644 --- a/dns-server/tests/basic_test.rs +++ b/dns-server/tests/basic_test.rs @@ -5,14 +5,14 @@ use anyhow::{Context, Result}; use camino_tempfile::Utf8TempDir; use dns_service_client::Client; -use dropshot::{test_util::LogContext, HandlerTaskMode}; +use dropshot::{HandlerTaskMode, test_util::LogContext}; use hickory_client::{ client::{AsyncClient, ClientHandle}, error::ClientError, udp::UdpClientStream, }; -use hickory_resolver::error::ResolveErrorKind; use hickory_resolver::TokioAsyncResolver; +use hickory_resolver::error::ResolveErrorKind; use hickory_resolver::{ config::{NameServerConfig, Protocol, ResolverConfig, ResolverOpts}, proto::{ diff --git a/dns-server/tests/commands_test.rs b/dns-server/tests/commands_test.rs index 8c812cb2aa8..281b5baefed 100644 --- a/dns-server/tests/commands_test.rs +++ b/dns-server/tests/commands_test.rs @@ -4,10 +4,10 @@ use camino_tempfile::Utf8TempDir; use dns_server::storage::Store; +use omicron_test_utils::dev::test_cmds::EXIT_SUCCESS; use omicron_test_utils::dev::test_cmds::assert_exit_code; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; -use omicron_test_utils::dev::test_cmds::EXIT_SUCCESS; use omicron_test_utils::dev::test_setup_log; use std::net::SocketAddr; diff --git a/end-to-end-tests/src/bin/bootstrap.rs b/end-to-end-tests/src/bin/bootstrap.rs index cc49eabfcc2..97ad4384f7f 100644 --- a/end-to-end-tests/src/bin/bootstrap.rs +++ b/end-to-end-tests/src/bin/bootstrap.rs @@ -1,7 +1,7 @@ use anyhow::Result; use end_to_end_tests::helpers::ctx::{ClientParams, Context}; use end_to_end_tests::helpers::{generate_name, get_system_ip_pool}; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use oxide_client::types::{ ByteCount, DeviceAccessTokenRequest, DeviceAuthRequest, DeviceAuthVerify, DiskCreate, DiskSource, IpPoolCreate, IpPoolLinkSilo, IpRange, Ipv4Range, @@ -11,7 +11,7 @@ use oxide_client::{ ClientDisksExt, ClientHiddenExt, ClientProjectsExt, ClientSystemIpPoolsExt, ClientSystemSilosExt, }; -use serde::{de::DeserializeOwned, Deserialize}; +use serde::{Deserialize, de::DeserializeOwned}; use std::time::Duration; use uuid::Uuid; diff --git a/end-to-end-tests/src/bin/commtest.rs b/end-to-end-tests/src/bin/commtest.rs index 5711a52179b..74f89502a03 100644 --- a/end-to-end-tests/src/bin/commtest.rs +++ b/end-to-end-tests/src/bin/commtest.rs @@ -1,16 +1,16 @@ -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use clap::{Parser, Subcommand}; use end_to_end_tests::helpers::cli::oxide_cli_style; use end_to_end_tests::helpers::icmp::ping4_test_run; use oxide_client::{ + ClientHiddenExt, ClientLoginExt, ClientProjectsExt, + ClientSystemHardwareExt, ClientSystemIpPoolsExt, ClientSystemStatusExt, + ClientVpcsExt, types::{ IpPoolCreate, IpPoolLinkSilo, IpRange, Ipv4Range, Name, NameOrId, PingStatus, ProbeCreate, ProbeInfo, ProjectCreate, UsernamePasswordCredentials, }, - ClientHiddenExt, ClientLoginExt, ClientProjectsExt, - ClientSystemHardwareExt, ClientSystemIpPoolsExt, ClientSystemStatusExt, - ClientVpcsExt, }; use std::{ net::{IpAddr, Ipv4Addr}, diff --git a/end-to-end-tests/src/bin/dhcp-server.rs b/end-to-end-tests/src/bin/dhcp-server.rs index 69681fa4132..db03b7d9a50 100644 --- a/end-to-end-tests/src/bin/dhcp-server.rs +++ b/end-to-end-tests/src/bin/dhcp-server.rs @@ -6,11 +6,11 @@ use anyhow::Result; use clap::Parser; use dhcproto::{ + Encoder, v4::{ self, Decodable, Decoder, DhcpOptions, Encodable, Message, Opcode, OptionCode, }, - Encoder, }; use end_to_end_tests::helpers::cli::oxide_cli_style; use macaddr::MacAddr6; diff --git a/end-to-end-tests/src/helpers/ctx.rs b/end-to-end-tests/src/helpers/ctx.rs index 3301988b8a0..09cd83c149a 100644 --- a/end-to-end-tests/src/helpers/ctx.rs +++ b/end-to-end-tests/src/helpers/ctx.rs @@ -1,14 +1,14 @@ use crate::helpers::generate_name; -use anyhow::{anyhow, Context as _, Result}; +use anyhow::{Context as _, Result, anyhow}; use chrono::Utc; use hickory_resolver::error::ResolveErrorKind; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; -use oxide_client::types::{Name, ProjectCreate}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use oxide_client::CustomDnsResolver; +use oxide_client::types::{Name, ProjectCreate}; use oxide_client::{Client, ClientImagesExt, ClientProjectsExt, ClientVpcsExt}; +use reqwest::Url; use reqwest::dns::Resolve; use reqwest::header::{HeaderMap, HeaderValue}; -use reqwest::Url; use sled_agent_types::rack_init::RackInitializeRequest; use std::net::IpAddr; use std::net::SocketAddr; diff --git a/end-to-end-tests/src/helpers/icmp.rs b/end-to-end-tests/src/helpers/icmp.rs index 40256db8d93..858763584f2 100644 --- a/end-to-end-tests/src/helpers/icmp.rs +++ b/end-to-end-tests/src/helpers/icmp.rs @@ -136,45 +136,49 @@ impl Pinger4 { "lost".dimmed() ); // run the reporting on a background thread - spawn(move || loop { - // print a status line for each target - for (_id, t) in self.targets.lock().unwrap().iter() { - println!( - "{:15} {:7} {:7} {:7} {:7} {:7} {:9} {:<7}", - t.dest.to_string().cyan(), - format!("{:.3}", (t.low.as_micros() as f32 / 1000.0)), - if t.rx_count == 0 { - format!("{:.3}", 0.0) - } else { - format!( - "{:.3}", - (t.sum.as_micros() as f32 - / 1000.0 - / f32::from(t.rx_count)) - ) - }, - format!("{:.3}", (t.high.as_micros() as f32 / 1000.0)), - match t.current { - Some(dt) => - format!("{:.3}", (dt.as_micros() as f32 / 1000.0)), - None => format!("{:.3}", 0.0), - }, - t.tx_count.to_string(), - t.rx_count.to_string(), - if t.lost == 0 { - t.lost.to_string().green() - } else { - t.lost.to_string().red() - }, - ); - } - // move the cursor back to the top for another round of reporting - for _ in 0..self.targets.lock().unwrap().len() { - print!("{MOVE_CURSOR_UP}"); - } - print!("\r"); + spawn(move || { + loop { + // print a status line for each target + for (_id, t) in self.targets.lock().unwrap().iter() { + println!( + "{:15} {:7} {:7} {:7} {:7} {:7} {:9} {:<7}", + t.dest.to_string().cyan(), + format!("{:.3}", (t.low.as_micros() as f32 / 1000.0)), + if t.rx_count == 0 { + format!("{:.3}", 0.0) + } else { + format!( + "{:.3}", + (t.sum.as_micros() as f32 + / 1000.0 + / f32::from(t.rx_count)) + ) + }, + format!("{:.3}", (t.high.as_micros() as f32 / 1000.0)), + match t.current { + Some(dt) => format!( + "{:.3}", + (dt.as_micros() as f32 / 1000.0) + ), + None => format!("{:.3}", 0.0), + }, + t.tx_count.to_string(), + t.rx_count.to_string(), + if t.lost == 0 { + t.lost.to_string().green() + } else { + t.lost.to_string().red() + }, + ); + } + // move the cursor back to the top for another round of reporting + for _ in 0..self.targets.lock().unwrap().len() { + print!("{MOVE_CURSOR_UP}"); + } + print!("\r"); - sleep(Duration::from_millis(100)); + sleep(Duration::from_millis(100)); + } }); } @@ -200,35 +204,37 @@ impl Pinger4 { let mut seq = 0u16; let stop = Instant::now() + duration; // send ICMP test packets on a background thread - spawn(move || loop { - if Instant::now() >= stop { - break; - } - let mut c = Checksum::new(); - c.add_bytes(&[ICMP_ECHO_TYPE, ICMP_ECHO_CODE]); - c.add_bytes(&id.to_be_bytes()); - c.add_bytes(&seq.to_be_bytes()); - let pkt = EchoRequest { - typ: ICMP_ECHO_TYPE, - code: ICMP_ECHO_CODE, - checksum: u16::from_be_bytes(c.checksum()), - identifier: id, - sequence_number: seq, - }; - let msg = ispf::to_bytes_be(&pkt).unwrap(); + spawn(move || { + loop { + if Instant::now() >= stop { + break; + } + let mut c = Checksum::new(); + c.add_bytes(&[ICMP_ECHO_TYPE, ICMP_ECHO_CODE]); + c.add_bytes(&id.to_be_bytes()); + c.add_bytes(&seq.to_be_bytes()); + let pkt = EchoRequest { + typ: ICMP_ECHO_TYPE, + code: ICMP_ECHO_CODE, + checksum: u16::from_be_bytes(c.checksum()), + identifier: id, + sequence_number: seq, + }; + let msg = ispf::to_bytes_be(&pkt).unwrap(); - match self.targets.lock().unwrap().get_mut(&id) { - Some(ref mut tgt) => { - tgt.sent = Some(Instant::now()); - tgt.tx_count = seq; - let sa: SockAddr = SocketAddrV4::new(dst, 0).into(); - self.sock.send_to(&msg, &sa).unwrap(); + match self.targets.lock().unwrap().get_mut(&id) { + Some(ref mut tgt) => { + tgt.sent = Some(Instant::now()); + tgt.tx_count = seq; + let sa: SockAddr = SocketAddrV4::new(dst, 0).into(); + self.sock.send_to(&msg, &sa).unwrap(); + } + None => continue, } - None => continue, - } - seq += 1; - sleep(interval); + seq += 1; + sleep(interval); + } }); } @@ -236,63 +242,71 @@ impl Pinger4 { // report. But it's really nice for interactive use to have a live // ticker for lost packet count. fn count_lost(self: Arc) { - spawn(move || loop { - for (_, tgt) in self.targets.lock().unwrap().iter_mut() { - // Only start considering packets lost after the first packet - // is received. This allows the remote endpoint time to come - // online without considering initial packets lost while it's - // coming up. - if tgt.first != 0 { - tgt.lost = tgt - .tx_count - .saturating_sub(tgt.first) - .saturating_sub(tgt.rx_count) - as usize; + spawn(move || { + loop { + for (_, tgt) in self.targets.lock().unwrap().iter_mut() { + // Only start considering packets lost after the first packet + // is received. This allows the remote endpoint time to come + // online without considering initial packets lost while it's + // coming up. + if tgt.first != 0 { + tgt.lost = tgt + .tx_count + .saturating_sub(tgt.first) + .saturating_sub(tgt.rx_count) + as usize; + } } + sleep(Duration::from_millis(10)); } - sleep(Duration::from_millis(10)); }); } fn rx(self: Arc) { // Spawn a background thread to receive ICMP replies and do the // necessary accounting. - spawn(move || loop { - let mut ubuf = [MaybeUninit::new(0); 10240]; - if let Ok((sz, _)) = self.sock.recv_from(&mut ubuf) { - let buf = unsafe { &slice_assume_init_ref(&ubuf[..sz]) }; - let msg: EchoRequest = match ispf::from_bytes_be(&buf[20..sz]) { - Ok(msg) => msg, - Err(_) => { - continue; - } - }; - // correlate the ICMP id with a target - match self.targets.lock().unwrap().get_mut(&msg.identifier) { - Some(ref mut target) => match target.sent { - Some(ref mut sent) => { - let t1 = Instant::now(); - let dt = t1 - *sent; - target.current = Some(dt); - if target.low == Duration::ZERO || dt < target.low { - target.low = dt; + spawn(move || { + loop { + let mut ubuf = [MaybeUninit::new(0); 10240]; + if let Ok((sz, _)) = self.sock.recv_from(&mut ubuf) { + let buf = unsafe { &slice_assume_init_ref(&ubuf[..sz]) }; + let msg: EchoRequest = + match ispf::from_bytes_be(&buf[20..sz]) { + Ok(msg) => msg, + Err(_) => { + continue; } - if dt > target.high { - target.high = dt; + }; + // correlate the ICMP id with a target + match self.targets.lock().unwrap().get_mut(&msg.identifier) + { + Some(ref mut target) => match target.sent { + Some(ref mut sent) => { + let t1 = Instant::now(); + let dt = t1 - *sent; + target.current = Some(dt); + if target.low == Duration::ZERO + || dt < target.low + { + target.low = dt; + } + if dt > target.high { + target.high = dt; + } + target.sum += dt; + target.current = Some(dt); + target.rx_count += 1; + if target.first == 0 { + target.first = target.tx_count; + } } - target.sum += dt; - target.current = Some(dt); - target.rx_count += 1; - if target.first == 0 { - target.first = target.tx_count; + None => { + println!("no sent"); } - } + }, None => { - println!("no sent"); + println!("no target {}", msg.identifier); } - }, - None => { - println!("no target {}", msg.identifier); } } } diff --git a/end-to-end-tests/src/helpers/mod.rs b/end-to-end-tests/src/helpers/mod.rs index b7cd6d55749..06beb09be9f 100644 --- a/end-to-end-tests/src/helpers/mod.rs +++ b/end-to-end-tests/src/helpers/mod.rs @@ -3,9 +3,9 @@ pub mod ctx; pub mod icmp; use self::ctx::nexus_addr; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use oxide_client::types::Name; -use rand::{thread_rng, Rng}; +use rand::{Rng, thread_rng}; use std::env; use std::net::{IpAddr, Ipv4Addr}; diff --git a/end-to-end-tests/src/instance_launch.rs b/end-to-end-tests/src/instance_launch.rs index fc3a29bffa2..a6dbc8149fe 100644 --- a/end-to-end-tests/src/instance_launch.rs +++ b/end-to-end-tests/src/instance_launch.rs @@ -1,9 +1,9 @@ #![cfg(test)] use crate::helpers::{ctx::Context, generate_name}; -use anyhow::{ensure, Context as _, Result}; +use anyhow::{Context as _, Result, ensure}; use async_trait::async_trait; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use oxide_client::types::{ ByteCount, DiskCreate, DiskSource, ExternalIp, ExternalIpCreate, InstanceCpuCount, InstanceCreate, InstanceDiskAttachment, @@ -11,8 +11,8 @@ use oxide_client::types::{ }; use oxide_client::{ClientDisksExt, ClientInstancesExt, ClientSessionExt}; use russh::{ChannelMsg, Disconnect}; -use russh_keys::key::{KeyPair, PublicKey}; use russh_keys::PublicKeyBase64; +use russh_keys::key::{KeyPair, PublicKey}; use std::sync::Arc; use std::time::Duration; diff --git a/end-to-end-tests/src/noop_blueprint.rs b/end-to-end-tests/src/noop_blueprint.rs index a7d5693d52b..c64981fe54d 100644 --- a/end-to-end-tests/src/noop_blueprint.rs +++ b/end-to-end-tests/src/noop_blueprint.rs @@ -6,7 +6,7 @@ use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use nexus_client::Client as NexusClient; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use omicron_test_utils::dev::test_setup_log; use omicron_uuid_kinds::GenericUuid; use slog::{debug, info}; diff --git a/gateway-cli/src/main.rs b/gateway-cli/src/main.rs index 7bc1110e1e6..c26e10133bb 100644 --- a/gateway-cli/src/main.rs +++ b/gateway-cli/src/main.rs @@ -4,12 +4,13 @@ // Copyright 2023 Oxide Computer Company -use anyhow::anyhow; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::anyhow; +use anyhow::bail; use clap::Parser; use clap::Subcommand; +use gateway_client::Client; use gateway_client::types::HostStartupOptions; use gateway_client::types::IgnitionCommand; use gateway_client::types::InstallinatorImageId; @@ -18,20 +19,19 @@ use gateway_client::types::SpComponentFirmwareSlot; use gateway_client::types::SpIdentifier; use gateway_client::types::SpUpdateStatus; use gateway_client::types::UpdateAbortBody; -use gateway_client::Client; use omicron_common::update::ArtifactHash; use serde::Serialize; -use slog::o; use slog::Drain; use slog::Level; use slog::Logger; +use slog::o; use std::fs; use std::io; use std::net::SocketAddrV6; use std::path::PathBuf; use std::time::Duration; -use tokio_tungstenite::tungstenite::protocol::Role; use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::protocol::Role; use uuid::Uuid; mod picocom_map; diff --git a/gateway-cli/src/picocom_map.rs b/gateway-cli/src/picocom_map.rs index e55403bfc22..591c4029207 100644 --- a/gateway-cli/src/picocom_map.rs +++ b/gateway-cli/src/picocom_map.rs @@ -6,7 +6,7 @@ use std::{collections::VecDeque, str::FromStr}; -use anyhow::{bail, ensure, Error, Result}; +use anyhow::{Error, Result, bail, ensure}; #[derive(Debug, Default, Clone, Copy)] pub struct RemapRules { diff --git a/gateway-cli/src/usart.rs b/gateway-cli/src/usart.rs index 40dda1391b9..5f520a936ad 100644 --- a/gateway-cli/src/usart.rs +++ b/gateway-cli/src/usart.rs @@ -21,10 +21,10 @@ use std::time::Duration; use termios::Termios; use tokio::io::AsyncReadExt; use tokio::sync::mpsc; -use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; -use tokio_tungstenite::tungstenite::protocol::CloseFrame; -use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::protocol::CloseFrame; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; const CTRL_A: u8 = b'\x01'; const CTRL_X: u8 = b'\x18'; diff --git a/gateway-test-utils/src/setup.rs b/gateway-test-utils/src/setup.rs index d8e5a89734c..5254880357e 100644 --- a/gateway-test-utils/src/setup.rs +++ b/gateway-test-utils/src/setup.rs @@ -8,10 +8,10 @@ use camino::Utf8Path; use dropshot::test_util::ClientTestContext; use dropshot::test_util::LogContext; use gateway_messages::SpPort; -pub use omicron_gateway::metrics::MetricsConfig; use omicron_gateway::MgsArguments; use omicron_gateway::SpType; use omicron_gateway::SwitchPortConfig; +pub use omicron_gateway::metrics::MetricsConfig; use omicron_test_utils::dev::poll; use omicron_test_utils::dev::poll::CondCheckError; use slog::o; diff --git a/gateway-test-utils/src/sim_state.rs b/gateway-test-utils/src/sim_state.rs index b88b8e7afb6..a7c82e6717c 100644 --- a/gateway-test-utils/src/sim_state.rs +++ b/gateway-test-utils/src/sim_state.rs @@ -54,11 +54,7 @@ pub async fn current_simulator_state(simrack: &SimRack) -> Vec { // setup. slot = all_sps.last().map_or(0, |prev_info| { // if the type changed, reset to slot 0; otherwise increment - if prev_info.ignition.id.typ != typ { - 0 - } else { - slot + 1 - } + if prev_info.ignition.id.typ != typ { 0 } else { slot + 1 } }); let sp: &dyn SimulatedSp = match typ { diff --git a/gateway/src/bin/mgs.rs b/gateway/src/bin/mgs.rs index 91290bffae3..8126b42b8c7 100644 --- a/gateway/src/bin/mgs.rs +++ b/gateway/src/bin/mgs.rs @@ -4,12 +4,12 @@ //! Executable program to run gateway, the management gateway service -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use camino::Utf8PathBuf; use clap::Parser; use futures::StreamExt; -use omicron_common::cmd::{fatal, CmdError}; -use omicron_gateway::{start_server, Config, MgsArguments}; +use omicron_common::cmd::{CmdError, fatal}; +use omicron_gateway::{Config, MgsArguments, start_server}; use signal_hook::consts::signal; use signal_hook_tokio::Signals; use std::net::SocketAddrV6; diff --git a/gateway/src/context.rs b/gateway/src/context.rs index dc5717604bf..7e214e5b8fc 100644 --- a/gateway/src/context.rs +++ b/gateway/src/context.rs @@ -6,7 +6,7 @@ use crate::error::StartupError; use crate::management_switch::ManagementSwitch; use crate::management_switch::SwitchConfig; use gateway_sp_comms::InMemoryHostPhase2Provider; -use slog::{info, Logger}; +use slog::{Logger, info}; use std::sync::Arc; use std::sync::OnceLock; use uuid::Uuid; diff --git a/gateway/src/error.rs b/gateway/src/error.rs index a726293ba1f..d70c873fb8d 100644 --- a/gateway/src/error.rs +++ b/gateway/src/error.rs @@ -7,9 +7,9 @@ use crate::management_switch::SpIdentifier; use dropshot::HttpError; use gateway_messages::SpError; +use gateway_sp_comms::BindError; pub use gateway_sp_comms::error::CommunicationError; use gateway_sp_comms::error::UpdateError; -use gateway_sp_comms::BindError; use slog_error_chain::InlineErrorChain; use slog_error_chain::SlogInlineError; use std::time::Duration; diff --git a/gateway/src/http_entrypoints.rs b/gateway/src/http_entrypoints.rs index 7a90bdb43f9..3bcb17a57c7 100644 --- a/gateway/src/http_entrypoints.rs +++ b/gateway/src/http_entrypoints.rs @@ -6,9 +6,9 @@ //! HTTP entrypoint functions for the gateway service +use crate::ServerContext; use crate::error::SpCommsError; use crate::http_err_with_message; -use crate::ServerContext; use base64::Engine; use dropshot::ApiDescription; use dropshot::HttpError; @@ -25,9 +25,9 @@ use futures::TryFutureExt; use gateway_api::*; use gateway_messages::RotBootInfo; use gateway_messages::SpComponent; -use gateway_sp_comms::error::CommunicationError; use gateway_sp_comms::HostPhase2Provider; use gateway_sp_comms::VersionedSpState; +use gateway_sp_comms::error::CommunicationError; use gateway_types::caboose::SpComponentCaboose; use gateway_types::component::PowerState; use gateway_types::component::SpComponentFirmwareSlot; diff --git a/gateway/src/lib.rs b/gateway/src/lib.rs index c7e3f66b991..8d9b280c5a2 100644 --- a/gateway/src/lib.rs +++ b/gateway/src/lib.rs @@ -16,8 +16,8 @@ pub use context::ServerContext; pub use error::*; use dropshot::ShutdownWaitFuture; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; use gateway_sp_comms::InMemoryHostPhase2Provider; pub use management_switch::LocationConfig; pub use management_switch::LocationDeterminationConfig; @@ -32,15 +32,15 @@ use omicron_common::FileKv; use dropshot::ConfigDropshot; use dropshot::HandlerTaskMode; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::mem; use std::net::SocketAddr; use std::net::SocketAddrV6; diff --git a/gateway/src/management_switch.rs b/gateway/src/management_switch.rs index ce45d58c2f7..2fd6ce23ba0 100644 --- a/gateway/src/management_switch.rs +++ b/gateway/src/management_switch.rs @@ -23,17 +23,17 @@ use crate::error::SpCommsError; use crate::error::SpLookupError; use crate::error::StartupError; use gateway_messages::IgnitionState; -use gateway_sp_comms::default_discovery_addr; use gateway_sp_comms::BindError; use gateway_sp_comms::HostPhase2Provider; use gateway_sp_comms::SharedSocket; use gateway_sp_comms::SingleSp; use gateway_sp_comms::SpRetryConfig; +use gateway_sp_comms::default_discovery_addr; use serde::Deserialize; use serde::Serialize; +use slog::Logger; use slog::o; use slog::warn; -use slog::Logger; use std::collections::HashMap; use std::net::Ipv6Addr; use std::net::SocketAddrV6; diff --git a/gateway/src/management_switch/location_map.rs b/gateway/src/management_switch/location_map.rs index f7877c10511..f4433c1b49a 100644 --- a/gateway/src/management_switch/location_map.rs +++ b/gateway/src/management_switch/location_map.rs @@ -7,16 +7,16 @@ use super::SpIdentifier; use super::SwitchPort; use crate::error::StartupError; -use futures::stream::FuturesUnordered; use futures::Stream; use futures::StreamExt; +use futures::stream::FuturesUnordered; use gateway_messages::SpPort; use gateway_sp_comms::SingleSp; use serde::Deserialize; use serde::Serialize; +use slog::Logger; use slog::debug; use slog::info; -use slog::Logger; use std::collections::HashMap; use std::collections::HashSet; use std::net::SocketAddrV6; @@ -346,7 +346,7 @@ async fn discover_sps( SwitchPort(i), sp.interface().to_string(), sp_port, - ) + ); } None => { addr_watch.changed().await.unwrap(); diff --git a/gateway/src/metrics.rs b/gateway/src/metrics.rs index f91af70bc98..7e873e326e8 100644 --- a/gateway/src/metrics.rs +++ b/gateway/src/metrics.rs @@ -1,26 +1,26 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::MgsArguments; +use crate::ServerContext; use crate::error::CommunicationError; use crate::management_switch::SpIdentifier; use crate::management_switch::SpType; -use crate::MgsArguments; -use crate::ServerContext; use anyhow::Context; -use gateway_messages::measurement::MeasurementError; -use gateway_messages::measurement::MeasurementKind; use gateway_messages::ComponentDetails; use gateway_messages::DeviceCapabilities; +use gateway_messages::measurement::MeasurementError; +use gateway_messages::measurement::MeasurementKind; use gateway_sp_comms::SingleSp; use gateway_sp_comms::SpComponent; use gateway_sp_comms::VersionedSpState; use omicron_common::api::internal::nexus::ProducerEndpoint; use omicron_common::api::internal::nexus::ProducerKind; use omicron_common::backoff; +use oximeter::MetricsError; use oximeter::types::Cumulative; use oximeter::types::ProducerRegistry; use oximeter::types::Sample; -use oximeter::MetricsError; use std::borrow::Cow; use std::collections::hash_map; use std::collections::hash_map::HashMap; @@ -467,8 +467,7 @@ impl SpPoller { Err(e) => { // This should never happen, but it's not worth taking down the // entire management network over that... - const MSG: &'static str = - "the `SpPoller::run` function is only called after \ + const MSG: &'static str = "the `SpPoller::run` function is only called after \ discovery completes successfully, and the `SpIdentifier` \ used was returned by the management switch, \ so it should be valid."; @@ -733,7 +732,7 @@ impl SpPoller { Ok(deets) => deets, // SP seems gone! Err(CommunicationError::NoSpDiscovered) => { - return Err(CommunicationError::NoSpDiscovered) + return Err(CommunicationError::NoSpDiscovered); } Err(error) => { slog::warn!( diff --git a/gateway/src/serial_console.rs b/gateway/src/serial_console.rs index 12ddbe7e9b4..79ca2ed6448 100644 --- a/gateway/src/serial_console.rs +++ b/gateway/src/serial_console.rs @@ -4,22 +4,22 @@ // Copyright 2022 Oxide Computer Company -use crate::error::SpCommsError; use crate::SpIdentifier; +use crate::error::SpCommsError; use dropshot::WebsocketChannelResult; use dropshot::WebsocketConnection; use dropshot::WebsocketConnectionRaw; -use futures::stream::SplitSink; -use futures::stream::SplitStream; use futures::SinkExt; use futures::StreamExt; +use futures::stream::SplitSink; +use futures::stream::SplitStream; use gateway_messages::SERIAL_CONSOLE_IDLE_TIMEOUT; use gateway_sp_comms::AttachedSerialConsole; use gateway_sp_comms::AttachedSerialConsoleSend; +use slog::Logger; use slog::error; use slog::info; use slog::warn; -use slog::Logger; use slog_error_chain::SlogInlineError; use std::borrow::Cow; use std::ops::Deref; @@ -29,12 +29,12 @@ use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; use tokio::time; use tokio::time::MissedTickBehavior; -use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; +use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::protocol::CloseFrame; use tokio_tungstenite::tungstenite::protocol::Role; use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; -use tokio_tungstenite::tungstenite::Message; -use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; #[derive(Debug, thiserror::Error, SlogInlineError)] enum SerialTaskError { diff --git a/gateway/tests/integration_tests/serial_console.rs b/gateway/tests/integration_tests/serial_console.rs index c2f67437231..f7822aee0cd 100644 --- a/gateway/tests/integration_tests/serial_console.rs +++ b/gateway/tests/integration_tests/serial_console.rs @@ -11,9 +11,9 @@ use gateway_test_utils::current_simulator_state; use gateway_test_utils::setup; use gateway_test_utils::sim_sp_serial_console; use gateway_types::component::SpType; -use http::uri::Scheme; use http::StatusCode; use http::Uri; +use http::uri::Scheme; use tokio_tungstenite::tungstenite; use tokio_tungstenite::tungstenite::protocol::Message; diff --git a/illumos-utils/src/coreadm.rs b/illumos-utils/src/coreadm.rs index 00e31a3309a..3a4558fb2fd 100644 --- a/illumos-utils/src/coreadm.rs +++ b/illumos-utils/src/coreadm.rs @@ -1,4 +1,4 @@ -use crate::{execute, ExecutionError}; +use crate::{ExecutionError, execute}; use std::process::Command; const COREADM: &str = "/usr/bin/coreadm"; diff --git a/illumos-utils/src/destructor.rs b/illumos-utils/src/destructor.rs index ccc5b154862..85b1c1cb2af 100644 --- a/illumos-utils/src/destructor.rs +++ b/illumos-utils/src/destructor.rs @@ -6,11 +6,11 @@ use anyhow::Error; use async_trait::async_trait; +use futures::StreamExt; use futures::future::{FusedFuture, FutureExt, Shared}; use futures::stream::FuturesUnordered; -use futures::StreamExt; use omicron_common::backoff::{ - retry_notify, retry_policy_internal_service, BackoffError, + BackoffError, retry_notify, retry_policy_internal_service, }; use std::future::Future; use std::pin::Pin; diff --git a/illumos-utils/src/dladm.rs b/illumos-utils/src/dladm.rs index b93353eb189..187d32f6024 100644 --- a/illumos-utils/src/dladm.rs +++ b/illumos-utils/src/dladm.rs @@ -6,7 +6,7 @@ use crate::link::{Link, LinkKind}; use crate::zone::IPADM; -use crate::{execute, ExecutionError, PFEXEC}; +use crate::{ExecutionError, PFEXEC, execute}; use omicron_common::api::external::MacAddr; use omicron_common::vlan::VlanID; use serde::{Deserialize, Serialize}; @@ -115,7 +115,9 @@ pub struct GetLinkpropError { /// Errors returned from [`Dladm::set_linkprop`]. #[derive(thiserror::Error, Debug)] -#[error("Failed to set link property \"{prop_name}\" to \"{prop_value}\" on vnic {link_name}: {err}")] +#[error( + "Failed to set link property \"{prop_name}\" to \"{prop_value}\" on vnic {link_name}: {err}" +)] pub struct SetLinkpropError { link_name: String, prop_name: String, diff --git a/illumos-utils/src/dumpadm.rs b/illumos-utils/src/dumpadm.rs index 5a8247041b6..1fb511fd7b1 100644 --- a/illumos-utils/src/dumpadm.rs +++ b/illumos-utils/src/dumpadm.rs @@ -1,4 +1,4 @@ -use crate::{execute, ExecutionError}; +use crate::{ExecutionError, execute}; use camino::Utf8PathBuf; use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; diff --git a/illumos-utils/src/fstyp.rs b/illumos-utils/src/fstyp.rs index dbbe3442dcc..fe5abef6757 100644 --- a/illumos-utils/src/fstyp.rs +++ b/illumos-utils/src/fstyp.rs @@ -5,7 +5,7 @@ //! Helper for calling fstyp. use crate::zpool::ZpoolName; -use crate::{execute, PFEXEC}; +use crate::{PFEXEC, execute}; use camino::Utf8Path; use std::str::FromStr; diff --git a/illumos-utils/src/ipadm.rs b/illumos-utils/src/ipadm.rs index ff99cd7a26e..99aa521f0e2 100644 --- a/illumos-utils/src/ipadm.rs +++ b/illumos-utils/src/ipadm.rs @@ -6,7 +6,7 @@ use crate::addrobj::{IPV6_LINK_LOCAL_ADDROBJ_NAME, IPV6_STATIC_ADDROBJ_NAME}; use crate::zone::IPADM; -use crate::{execute, ExecutionError, PFEXEC}; +use crate::{ExecutionError, PFEXEC, execute}; use oxnet::IpNet; use std::net::{IpAddr, Ipv6Addr}; diff --git a/illumos-utils/src/link.rs b/illumos-utils/src/link.rs index 5d0c80b0e1f..7ea03953be8 100644 --- a/illumos-utils/src/link.rs +++ b/illumos-utils/src/link.rs @@ -6,13 +6,13 @@ use crate::destructor::{Deletable, Destructor}; use crate::dladm::{ - CreateVnicError, DeleteVnicError, VnicSource, VNIC_PREFIX, - VNIC_PREFIX_BOOTSTRAP, VNIC_PREFIX_CONTROL, + CreateVnicError, DeleteVnicError, VNIC_PREFIX, VNIC_PREFIX_BOOTSTRAP, + VNIC_PREFIX_CONTROL, VnicSource, }; use omicron_common::api::external::MacAddr; use std::sync::{ - atomic::{AtomicU64, Ordering}, Arc, + atomic::{AtomicU64, Ordering}, }; #[cfg(not(any(test, feature = "testing")))] diff --git a/illumos-utils/src/opte/illumos.rs b/illumos-utils/src/opte/illumos.rs index 464340498c1..7feaa84af4c 100644 --- a/illumos-utils/src/opte/illumos.rs +++ b/illumos-utils/src/opte/illumos.rs @@ -10,8 +10,8 @@ use camino::Utf8Path; use omicron_common::api::internal::shared::NetworkInterfaceKind; use opte_ioctl::Error as OpteError; use opte_ioctl::OpteHdl; -use slog::info; use slog::Logger; +use slog::info; use std::net::IpAddr; #[derive(thiserror::Error, Debug)] diff --git a/illumos-utils/src/opte/non_illumos.rs b/illumos-utils/src/opte/non_illumos.rs index a9c9680d8af..f878efc0678 100644 --- a/illumos-utils/src/opte/non_illumos.rs +++ b/illumos-utils/src/opte/non_illumos.rs @@ -25,8 +25,8 @@ use oxide_vpc::api::SetFwRulesReq; use oxide_vpc::api::SetVirt2PhysReq; use oxide_vpc::api::VpcCfg; use slog::Logger; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::net::IpAddr; use std::sync::Mutex; use std::sync::OnceLock; diff --git a/illumos-utils/src/opte/port_manager.rs b/illumos-utils/src/opte/port_manager.rs index b93f89ea5cc..d3b1c14b5a8 100644 --- a/illumos-utils/src/opte/port_manager.rs +++ b/illumos-utils/src/opte/port_manager.rs @@ -5,13 +5,13 @@ //! Manager for all OPTE ports on a Helios system use crate::dladm::OPTE_LINK_PREFIX; -use crate::opte::opte_firewall_rules; -use crate::opte::port::PortData; use crate::opte::Error; use crate::opte::Gateway; use crate::opte::Handle; use crate::opte::Port; use crate::opte::Vni; +use crate::opte::opte_firewall_rules; +use crate::opte::port::PortData; use ipnetwork::IpNetwork; use macaddr::MacAddr6; use omicron_common::api::external; @@ -46,20 +46,20 @@ use oxide_vpc::api::VpcCfg; use oxnet::IpNet; use oxnet::Ipv4Net; use oxnet::Ipv6Net; +use slog::Logger; use slog::debug; use slog::error; use slog::info; -use slog::Logger; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::net::IpAddr; use std::net::Ipv4Addr; use std::net::Ipv6Addr; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::Mutex; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; use uuid::Uuid; /// Stored routes (and usage count) for a given VPC/subnet. diff --git a/illumos-utils/src/route.rs b/illumos-utils/src/route.rs index e49bda22108..54bb75784ba 100644 --- a/illumos-utils/src/route.rs +++ b/illumos-utils/src/route.rs @@ -5,7 +5,7 @@ //! Utilities for manipulating the routing tables. use crate::zone::ROUTE; -use crate::{execute, inner, output_to_exec_error, ExecutionError, PFEXEC}; +use crate::{ExecutionError, PFEXEC, execute, inner, output_to_exec_error}; use libc::ESRCH; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; diff --git a/illumos-utils/src/running_zone.rs b/illumos-utils/src/running_zone.rs index 600d7ffffee..22be5578600 100644 --- a/illumos-utils/src/running_zone.rs +++ b/illumos-utils/src/running_zone.rs @@ -20,7 +20,7 @@ use ipnetwork::IpNetwork; use omicron_common::backoff; use omicron_uuid_kinds::OmicronZoneUuid; pub use oxlog::is_oxide_smf_log_file; -use slog::{error, info, o, warn, Logger}; +use slog::{Logger, error, info, o, warn}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; #[cfg(target_os = "illumos")] @@ -71,7 +71,9 @@ pub enum BootError { /// Errors returned from [`RunningZone::ensure_address`]. #[derive(thiserror::Error, Debug)] pub enum EnsureAddressError { - #[error("Failed ensuring address {request:?} in {zone}: could not construct addrobj name: {err}")] + #[error( + "Failed ensuring address {request:?} in {zone}: could not construct addrobj name: {err}" + )] AddrObject { request: AddressRequest, zone: String, @@ -128,7 +130,7 @@ pub fn ensure_contract_reaper(log: &Logger) { mod zenter { use libc::ctid_t; use libc::zoneid_t; - use slog::{debug, error, Logger}; + use slog::{Logger, debug, error}; use std::ffi::c_int; use std::ffi::c_uint; use std::ffi::c_void; @@ -1261,11 +1263,7 @@ impl<'a> ZoneBuilder<'a> { .iter() .find_map(|image_path| { let path = image_path.join(&image); - if path.exists() { - Some(path) - } else { - None - } + if path.exists() { Some(path) } else { None } }) .ok_or_else(|| InstallZoneError::ImageNotFound { image: image.to_string(), diff --git a/illumos-utils/src/svc.rs b/illumos-utils/src/svc.rs index 5360ca4dfc4..6700926b827 100644 --- a/illumos-utils/src/svc.rs +++ b/illumos-utils/src/svc.rs @@ -12,7 +12,7 @@ use omicron_common::backoff; #[cfg_attr(any(test, feature = "testing"), mockall::automock, allow(dead_code))] mod inner { use super::*; - use slog::{warn, Logger}; + use slog::{Logger, warn}; // TODO(https://www.illumos.org/issues/13837): This is a hack; // remove me when when fixed. Ideally, the ".synchronous()" argument @@ -53,11 +53,7 @@ mod inner { || async { let mut p = smf::Properties::new(); let properties = { - if let Some(zone) = zone { - p.zone(zone) - } else { - &mut p - } + if let Some(zone) = zone { p.zone(zone) } else { &mut p } }; if let Ok(value) = properties.lookup().run(&name, &fmri) { if value.value() @@ -81,7 +77,10 @@ mod inner { .output() .await { - warn!(log, "clearing service maintenance failed: {out}"); + warn!( + log, + "clearing service maintenance failed: {out}" + ); }; } } diff --git a/illumos-utils/src/svcadm.rs b/illumos-utils/src/svcadm.rs index 7e970dea048..f7a05b4d823 100644 --- a/illumos-utils/src/svcadm.rs +++ b/illumos-utils/src/svcadm.rs @@ -5,7 +5,7 @@ //! Utilities for manipulating SMF services. use crate::zone::SVCADM; -use crate::{execute, ExecutionError, PFEXEC}; +use crate::{ExecutionError, PFEXEC, execute}; /// Wraps commands for interacting with svcadm. pub struct Svcadm {} diff --git a/illumos-utils/src/zfs.rs b/illumos-utils/src/zfs.rs index e99ebc5b599..b61e2d4c9e6 100644 --- a/illumos-utils/src/zfs.rs +++ b/illumos-utils/src/zfs.rs @@ -4,10 +4,10 @@ //! Utilities for poking at ZFS. -use crate::{execute, PFEXEC}; +use crate::{PFEXEC, execute}; +use anyhow::Context; use anyhow::anyhow; use anyhow::bail; -use anyhow::Context; use camino::{Utf8Path, Utf8PathBuf}; use itertools::Itertools; use omicron_common::api::external::ByteCount; @@ -121,7 +121,9 @@ pub struct GetValueError { pub struct ListSnapshotsError(#[from] crate::ExecutionError); #[derive(Debug, thiserror::Error)] -#[error("Failed to create snapshot '{snap_name}' from filesystem '{filesystem}': {err}")] +#[error( + "Failed to create snapshot '{snap_name}' from filesystem '{filesystem}': {err}" +)] pub struct CreateSnapshotError { filesystem: String, snap_name: String, @@ -964,8 +966,7 @@ mod test { #[test] fn parse_dataset_props_with_optionals() { - let input = - "dataset_name\toxide:uuid\td4e1e554-7b98-4413-809e-4a42561c3d0c\tlocal\n\ + let input = "dataset_name\toxide:uuid\td4e1e554-7b98-4413-809e-4a42561c3d0c\tlocal\n\ dataset_name\tavailable\t1234\t-\n\ dataset_name\tused\t5678\t-\n\ dataset_name\tquota\t111\t-\n\ @@ -1085,8 +1086,7 @@ mod test { #[test] fn parse_dataset_uuid_ignored_if_inherited() { - let input = - "dataset_name\toxide:uuid\tb8698ede-60c2-4e16-b792-d28c165cfd12\tinherited from parent\n\ + let input = "dataset_name\toxide:uuid\tb8698ede-60c2-4e16-b792-d28c165cfd12\tinherited from parent\n\ dataset_name\tavailable\t1234\t-\n\ dataset_name\tused\t5678\t-\n\ dataset_name\tcompression\toff\t-"; diff --git a/illumos-utils/src/zone.rs b/illumos-utils/src/zone.rs index da08c7b7df5..9ebb5c74ac2 100644 --- a/illumos-utils/src/zone.rs +++ b/illumos-utils/src/zone.rs @@ -8,14 +8,14 @@ use anyhow::anyhow; use camino::Utf8Path; use ipnetwork::IpNetwork; use ipnetwork::IpNetworkError; -use slog::info; use slog::Logger; +use slog::info; use std::net::{IpAddr, Ipv6Addr}; use crate::addrobj::AddrObject; use crate::dladm::{EtherstubVnic, VNIC_PREFIX_BOOTSTRAP, VNIC_PREFIX_CONTROL}; use crate::zpool::PathInPool; -use crate::{execute, PFEXEC}; +use crate::{PFEXEC, execute}; use omicron_common::address::SLED_PREFIX; use omicron_uuid_kinds::OmicronZoneUuid; @@ -142,7 +142,9 @@ pub struct EnsureAddressError { /// Errors from [`Zones::ensure_has_global_zone_v6_address`]. #[derive(thiserror::Error, Debug)] -#[error("Failed to create address {address} with name {name} in the GZ on {link:?}: {err}. Note to developers: {extra_note}")] +#[error( + "Failed to create address {address} with name {name} in the GZ on {link:?}: {err}. Note to developers: {extra_note}" +)] pub struct EnsureGzAddressError { address: IpAddr, link: String, diff --git a/illumos-utils/src/zpool.rs b/illumos-utils/src/zpool.rs index 9656d755bfb..441eca0619f 100644 --- a/illumos-utils/src/zpool.rs +++ b/illumos-utils/src/zpool.rs @@ -4,7 +4,7 @@ //! Utilities for managing Zpools. -use crate::{execute, ExecutionError, PFEXEC}; +use crate::{ExecutionError, PFEXEC, execute}; use camino::{Utf8Path, Utf8PathBuf}; use std::str::FromStr; diff --git a/installinator-common/src/block_size_writer.rs b/installinator-common/src/block_size_writer.rs index 1548594b417..0370d304cb6 100644 --- a/installinator-common/src/block_size_writer.rs +++ b/installinator-common/src/block_size_writer.rs @@ -4,9 +4,9 @@ use std::io; use std::pin::Pin; -use std::task::ready; use std::task::Context; use std::task::Poll; +use std::task::ready; use tokio::io::AsyncWrite; /// `BlockSizeBufWriter` is analogous to a tokio's `BufWriter`, except it @@ -233,15 +233,13 @@ mod tests { if !inner.write_requests.is_empty() { let last = inner.write_requests.len() - 1; assert!( - inner.write_requests[last] - <= block_size, + inner.write_requests[last] <= block_size, "last block size too large (expected at most {block_size}, got {})", inner.write_requests[last], ); for (i, &wr) in inner.write_requests.iter().take(last).enumerate() { assert_eq!( - wr, - block_size, + wr, block_size, "write request {i} had size {wr} (expected block size {block_size})", ); } diff --git a/installinator-common/src/progress.rs b/installinator-common/src/progress.rs index 9078da6ba5f..cafed7a7f40 100644 --- a/installinator-common/src/progress.rs +++ b/installinator-common/src/progress.rs @@ -8,14 +8,14 @@ use camino::Utf8PathBuf; use illumos_utils::zpool; use omicron_common::disk::M2Slot; use schemars::{ + JsonSchema, gen::SchemaGenerator, schema::{Schema, SchemaObject}, - JsonSchema, }; use serde::{Deserialize, Serialize}; use serde_with::rust::deserialize_ignore_any; use thiserror::Error; -use update_engine::{errors::NestedEngineError, AsError, StepSpec}; +use update_engine::{AsError, StepSpec, errors::NestedEngineError}; // --- // Type definitions for use by installinator code. diff --git a/installinator/src/bootstrap.rs b/installinator/src/bootstrap.rs index 9be1c12b867..accfd1d77c4 100644 --- a/installinator/src/bootstrap.rs +++ b/installinator/src/bootstrap.rs @@ -6,9 +6,9 @@ //! Perform "bootstrap-agent lite" sled setup. -use anyhow::ensure; use anyhow::Context; use anyhow::Result; +use anyhow::ensure; use illumos_utils::addrobj::AddrObject; use illumos_utils::dladm; use illumos_utils::dladm::Dladm; @@ -17,8 +17,8 @@ use omicron_common::address::Ipv6Subnet; use omicron_ddm_admin_client::Client as DdmAdminClient; use sled_hardware::underlay; use sled_hardware_types::underlay::BootstrapInterface; -use slog::info; use slog::Logger; +use slog::info; const MG_DDM_SERVICE_FMRI: &str = "svc:/oxide/mg-ddm"; const MG_DDM_MANIFEST_PATH: &str = "/opt/oxide/mg-ddm/pkg/ddm/manifest.xml"; diff --git a/installinator/src/dispatch.rs b/installinator/src/dispatch.rs index 1fcf351a9b7..5a931afb373 100644 --- a/installinator/src/dispatch.rs +++ b/installinator/src/dispatch.rs @@ -4,7 +4,7 @@ use std::time::Duration; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use buf_list::{BufList, Cursor}; use camino::{Utf8Path, Utf8PathBuf}; use clap::{Args, Parser, Subcommand}; @@ -19,7 +19,7 @@ use omicron_common::{ update::{ArtifactHash, ArtifactHashId, ArtifactKind}, }; use sha2::{Digest, Sha256}; -use slog::{error, warn, Drain}; +use slog::{Drain, error, warn}; use tufaceous_lib::ControlPlaneZoneImages; use update_engine::StepResult; diff --git a/installinator/src/errors.rs b/installinator/src/errors.rs index 577d0d6f4db..7c04226dfda 100644 --- a/installinator/src/errors.rs +++ b/installinator/src/errors.rs @@ -16,10 +16,14 @@ pub(crate) enum ArtifactFetchError { error: HttpError, }, - #[error("peer {peer} timed out ({timeout:?}) after returning {bytes_fetched} bytes")] + #[error( + "peer {peer} timed out ({timeout:?}) after returning {bytes_fetched} bytes" + )] Timeout { peer: SocketAddr, timeout: Duration, bytes_fetched: usize }, - #[error("artifact size in Content-Length header ({artifact_size}) did not match downloaded size ({downloaded_bytes})")] + #[error( + "artifact size in Content-Length header ({artifact_size}) did not match downloaded size ({downloaded_bytes})" + )] SizeMismatch { artifact_size: u64, downloaded_bytes: u64 }, } diff --git a/installinator/src/hardware.rs b/installinator/src/hardware.rs index af2ecd2dff0..dea966712fe 100644 --- a/installinator/src/hardware.rs +++ b/installinator/src/hardware.rs @@ -2,18 +2,18 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::anyhow; -use anyhow::ensure; use anyhow::Context; use anyhow::Result; +use anyhow::anyhow; +use anyhow::ensure; use omicron_common::disk::DiskVariant; use sled_hardware::HardwareManager; use sled_hardware::SledMode; use sled_storage::config::MountConfig; use sled_storage::disk::Disk; use sled_storage::disk::RawDisk; -use slog::info; use slog::Logger; +use slog::info; pub struct Hardware { m2_disks: Vec, diff --git a/installinator/src/mock_peers.rs b/installinator/src/mock_peers.rs index ccb35a2f066..2760527a412 100644 --- a/installinator/src/mock_peers.rs +++ b/installinator/src/mock_peers.rs @@ -13,7 +13,7 @@ use std::{ time::Duration, }; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use async_trait::async_trait; use bytes::Bytes; use installinator_client::{ClientError, ResponseValue}; @@ -554,7 +554,7 @@ mod tests { }; use bytes::Buf; - use futures::{future, StreamExt}; + use futures::{StreamExt, future}; use installinator_common::{ InstallinatorCompletionMetadata, InstallinatorComponent, InstallinatorProgressMetadata, InstallinatorStepId, StepContext, @@ -671,10 +671,14 @@ mod tests { } (Err(_), Err(_)) => {} (Err(_), Ok(fetched_artifact)) => { - panic!("expected failure to fetch but found success: {fetched_artifact:?}"); + panic!( + "expected failure to fetch but found success: {fetched_artifact:?}" + ); } (Ok((attempt, addr)), Err(err)) => { - panic!("expected success at attempt `{attempt}` from `{addr}`, but found failure: {err}"); + panic!( + "expected success at attempt `{attempt}` from `{addr}`, but found failure: {err}" + ); } } @@ -754,7 +758,9 @@ mod tests { ); } other => { - panic!("expected download metadata, found {other:?}"); + panic!( + "expected download metadata, found {other:?}" + ); } }; } diff --git a/installinator/src/peers.rs b/installinator/src/peers.rs index 3d2e05077d2..8600dcb6ef9 100644 --- a/installinator/src/peers.rs +++ b/installinator/src/peers.rs @@ -10,7 +10,7 @@ use std::{ time::Duration, }; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use async_trait::async_trait; use buf_list::BufList; use bytes::Bytes; @@ -110,7 +110,10 @@ impl FromStr for DiscoveryMechanism { .collect::, _>>()?; Ok(Self::List(peers)) } else { - bail!("invalid discovery mechanism (expected \"bootstrap\" or \"list:[::1]:8000\"): {}", s); + bail!( + "invalid discovery mechanism (expected \"bootstrap\" or \"list:[::1]:8000\"): {}", + s + ); } } } @@ -150,7 +153,9 @@ impl FetchedArtifact { slog::warn!( log, "(attempt {attempt}) failed to discover peers, retrying: {}", - DisplayErrorChain::new(AsRef::::as_ref(&error)), + DisplayErrorChain::new( + AsRef::::as_ref(&error) + ), ); cx.send_progress(StepProgress::retry(format!( "failed to discover peers: {error}" @@ -172,7 +177,7 @@ impl FetchedArtifact { ); match peers.fetch_artifact(&cx, artifact_hash_id).await { Some((addr, artifact)) => { - return Ok(Self { attempt, addr, artifact }) + return Ok(Self { attempt, addr, artifact }); } None => { slog::warn!( diff --git a/installinator/src/write.rs b/installinator/src/write.rs index 7274ef4ad55..832fae54778 100644 --- a/installinator/src/write.rs +++ b/installinator/src/write.rs @@ -3,13 +3,13 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use std::{ - collections::{btree_map::Entry, BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, btree_map::Entry}, fmt, io::{self, Read}, time::Duration, }; -use anyhow::{anyhow, ensure, Context, Result}; +use anyhow::{Context, Result, anyhow, ensure}; use async_trait::async_trait; use buf_list::BufList; use bytes::Buf; @@ -25,14 +25,14 @@ use omicron_common::{ update::{ArtifactHash, ArtifactHashId}, }; use sha2::{Digest, Sha256}; -use slog::{info, warn, Logger}; +use slog::{Logger, info, warn}; use tokio::{ fs::File, io::{AsyncWrite, AsyncWriteExt}, }; use tufaceous_lib::ControlPlaneZoneImages; use update_engine::{ - errors::NestedEngineError, events::ProgressUnits, StepSpec, + StepSpec, errors::NestedEngineError, events::ProgressUnits, }; use crate::{async_temp_file::AsyncNamedTempFile, hardware::Hardware}; @@ -307,7 +307,9 @@ impl<'a> ArtifactWriter<'a> { DriveWriteProgress::ControlPlaneFailed; } WriteComponent::Unknown => { - unreachable!("we should never generate an unknown component") + unreachable!( + "we should never generate an unknown component" + ) } } } @@ -929,10 +931,10 @@ mod tests { }; use omicron_test_utils::dev::test_setup_log; use partial_io::{ + PartialAsyncWrite, PartialOp, proptest_types::{ interrupted_would_block_strategy, partial_op_strategy, }, - PartialAsyncWrite, PartialOp, }; use proptest::prelude::*; use test_strategy::proptest; diff --git a/internal-dns/resolver/src/resolver.rs b/internal-dns/resolver/src/resolver.rs index a40232db155..72dd84edd37 100644 --- a/internal-dns/resolver/src/resolver.rs +++ b/internal-dns/resolver/src/resolver.rs @@ -2,14 +2,14 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use hickory_resolver::TokioAsyncResolver; use hickory_resolver::config::{ LookupIpStrategy, NameServerConfig, Protocol, ResolverConfig, ResolverOpts, }; use hickory_resolver::lookup::SrvLookup; -use hickory_resolver::TokioAsyncResolver; use internal_dns_types::names::ServiceName; use omicron_common::address::{ - get_internal_dns_server_addresses, Ipv6Subnet, AZ_PREFIX, DNS_PORT, + AZ_PREFIX, DNS_PORT, Ipv6Subnet, get_internal_dns_server_addresses, }; use slog::{debug, error, info, trace}; use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6}; @@ -394,16 +394,16 @@ mod test { use anyhow::Context; use assert_matches::assert_matches; use dropshot::{ - endpoint, ApiDescription, HandlerTaskMode, HttpError, HttpResponseOk, - RequestContext, + ApiDescription, HandlerTaskMode, HttpError, HttpResponseOk, + RequestContext, endpoint, }; use internal_dns_types::config::DnsConfigBuilder; use internal_dns_types::config::DnsConfigParams; - use internal_dns_types::names::ServiceName; use internal_dns_types::names::DNS_ZONE; + use internal_dns_types::names::ServiceName; use omicron_test_utils::dev::test_setup_log; use omicron_uuid_kinds::OmicronZoneUuid; - use slog::{o, Logger}; + use slog::{Logger, o}; use std::collections::HashMap; use std::net::Ipv6Addr; use std::net::SocketAddr; @@ -641,9 +641,9 @@ mod test { .lookup_socket_v6(ServiceName::Cockroach) .await .expect("Should have been able to look up IP address"); - assert!(cockroach_addrs - .iter() - .any(|addr| addr.ip() == resolved_addr.ip())); + assert!( + cockroach_addrs.iter().any(|addr| addr.ip() == resolved_addr.ip()) + ); // Look up all the Cockroach addresses. let mut ips = diff --git a/internal-dns/types/src/config.rs b/internal-dns/types/src/config.rs index 27129d1fcec..0717bcdc840 100644 --- a/internal-dns/types/src/config.rs +++ b/internal-dns/types/src/config.rs @@ -60,7 +60,7 @@ //! //! This module provides types used to assemble that configuration. -use crate::names::{ServiceName, BOUNDARY_NTP_DNS_NAME, DNS_ZONE}; +use crate::names::{BOUNDARY_NTP_DNS_NAME, DNS_ZONE, ServiceName}; use anyhow::{anyhow, ensure}; use core::fmt; use omicron_common::address::{CLICKHOUSE_ADMIN_PORT, CLICKHOUSE_TCP_PORT}; diff --git a/internal-dns/types/src/diff.rs b/internal-dns/types/src/diff.rs index 868d7aee57c..8d33be038d9 100644 --- a/internal-dns/types/src/diff.rs +++ b/internal-dns/types/src/diff.rs @@ -40,7 +40,9 @@ impl<'a> DnsDiff<'a> { ensure!( left_zone.zone_name == right_zone.zone_name, "cannot compare DNS configuration from zones with different names: \ - {:?} vs. {:?}", left_zone.zone_name, right_zone.zone_name, + {:?} vs. {:?}", + left_zone.zone_name, + right_zone.zone_name, ); let all_names = @@ -82,11 +84,7 @@ impl<'a> DnsDiff<'a> { /// absent in the `left` one (i.e., added between `left` and `right`) pub fn names_added(&self) -> impl Iterator { self.iter_names().filter_map(|nd| { - if let NameDiff::Added(k, v) = nd { - Some((k, v)) - } else { - None - } + if let NameDiff::Added(k, v) = nd { Some((k, v)) } else { None } }) } @@ -94,11 +92,7 @@ impl<'a> DnsDiff<'a> { /// absent in the `right` one (i.e., removed between `left` and `right`) pub fn names_removed(&self) -> impl Iterator { self.iter_names().filter_map(|nd| { - if let NameDiff::Removed(k, v) = nd { - Some((k, v)) - } else { - None - } + if let NameDiff::Removed(k, v) = nd { Some((k, v)) } else { None } }) } @@ -121,11 +115,7 @@ impl<'a> DnsDiff<'a> { &self, ) -> impl Iterator { self.iter_names().filter_map(|nd| { - if let NameDiff::Unchanged(k, v) = nd { - Some((k, v)) - } else { - None - } + if let NameDiff::Unchanged(k, v) = nd { Some((k, v)) } else { None } }) } diff --git a/key-manager/src/lib.rs b/key-manager/src/lib.rs index f512d2486f1..f4b3b745bd8 100644 --- a/key-manager/src/lib.rs +++ b/key-manager/src/lib.rs @@ -11,7 +11,7 @@ use async_trait::async_trait; use hkdf::Hkdf; use secrecy::{ExposeSecret, Secret}; use sha3::Sha3_256; -use slog::{o, warn, Logger}; +use slog::{Logger, o, warn}; use tokio::sync::{mpsc, oneshot}; use zeroize::{Zeroize, ZeroizeOnDrop}; diff --git a/live-tests/macros/src/lib.rs b/live-tests/macros/src/lib.rs index cb41abc54b9..d878898fab1 100644 --- a/live-tests/macros/src/lib.rs +++ b/live-tests/macros/src/lib.rs @@ -7,7 +7,7 @@ use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, ItemFn}; +use syn::{ItemFn, parse_macro_input}; /// Define a test function that uses `LiveTestContext` /// diff --git a/live-tests/tests/common/mod.rs b/live-tests/tests/common/mod.rs index 8a60b332b63..8750da06641 100644 --- a/live-tests/tests/common/mod.rs +++ b/live-tests/tests/common/mod.rs @@ -4,7 +4,7 @@ pub mod reconfigurator; -use anyhow::{anyhow, ensure, Context}; +use anyhow::{Context, anyhow, ensure}; use dropshot::test_util::LogContext; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; diff --git a/live-tests/tests/common/reconfigurator.rs b/live-tests/tests/common/reconfigurator.rs index d2c1235f8a7..040bbec81f8 100644 --- a/live-tests/tests/common/reconfigurator.rs +++ b/live-tests/tests/common/reconfigurator.rs @@ -4,7 +4,7 @@ //! Helpers common to Reconfigurator tests -use anyhow::{ensure, Context}; +use anyhow::{Context, ensure}; use nexus_client::types::BlueprintTargetSet; use nexus_reconfigurator_planning::blueprint_builder::BlueprintBuilder; use nexus_types::deployment::{Blueprint, PlanningInput}; diff --git a/live-tests/tests/test_nexus_add_remove.rs b/live-tests/tests/test_nexus_add_remove.rs index f3c35182a93..30ae7ea1c4c 100644 --- a/live-tests/tests/test_nexus_add_remove.rs +++ b/live-tests/tests/test_nexus_add_remove.rs @@ -5,8 +5,8 @@ mod common; use anyhow::Context; -use common::reconfigurator::blueprint_edit_current_target; use common::LiveTestContext; +use common::reconfigurator::blueprint_edit_current_target; use futures::TryStreamExt; use live_tests_macros::live_test; use nexus_client::types::Saga; @@ -17,8 +17,8 @@ use nexus_reconfigurator_preparation::PlanningInputFromDb; use nexus_sled_agent_shared::inventory::ZoneKind; use nexus_types::deployment::SledFilter; use omicron_common::address::NEXUS_INTERNAL_PORT; -use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; +use omicron_test_utils::dev::poll::wait_for_condition; use slog::{debug, info}; use std::net::SocketAddrV6; use std::time::Duration; diff --git a/nexus-config/src/nexus_config.rs b/nexus-config/src/nexus_config.rs index 1f1ed10fc79..5d6748a57bf 100644 --- a/nexus-config/src/nexus_config.rs +++ b/nexus-config/src/nexus_config.rs @@ -17,11 +17,11 @@ use omicron_common::api::internal::shared::SwitchLocation; use omicron_uuid_kinds::OmicronZoneUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use serde_with::serde_as; use serde_with::DeserializeFromStr; use serde_with::DisplayFromStr; use serde_with::DurationSeconds; use serde_with::SerializeDisplay; +use serde_with::serde_as; use std::collections::HashMap; use std::fmt; use std::net::IpAddr; @@ -331,8 +331,7 @@ impl Tunables { tunable: String::from("max_vpc_ipv4_subnet_prefix"), message: format!( "IPv4 subnet prefix must be in the range [0, {}], found: {}", - absolute_max, - prefix, + absolute_max, prefix, ), }) } @@ -822,7 +821,7 @@ mod test { use super::*; use omicron_common::address::{ - Ipv6Subnet, CLICKHOUSE_TCP_PORT, RACK_PREFIX, + CLICKHOUSE_TCP_PORT, Ipv6Subnet, RACK_PREFIX, }; use omicron_common::api::internal::shared::SwitchLocation; diff --git a/nexus-config/src/postgres_config.rs b/nexus-config/src/postgres_config.rs index 0c72d2ba9e6..e9f57ea3f4f 100644 --- a/nexus-config/src/postgres_config.rs +++ b/nexus-config/src/postgres_config.rs @@ -95,9 +95,9 @@ mod test { let error = "postgresql://example.com?sslmode=not-a-real-ssl-mode" .parse::() .unwrap_err(); - assert!(error - .to_string() - .contains("invalid value for option `sslmode`")); + assert!( + error.to_string().contains("invalid value for option `sslmode`") + ); } #[test] diff --git a/nexus/auth/src/authn/external/mod.rs b/nexus/auth/src/authn/external/mod.rs index 3150fece283..2f09e73f790 100644 --- a/nexus/auth/src/authn/external/mod.rs +++ b/nexus/auth/src/authn/external/mod.rs @@ -80,7 +80,7 @@ where // NOT that they simply didn't try), should we try the others // instead of returning the failure here? SchemeResult::Failed(reason) => { - return Err(authn::Error { reason, schemes_tried }) + return Err(authn::Error { reason, schemes_tried }); } SchemeResult::Authenticated(details) => { return match ctx.silo_authn_policy_for(&details.actor).await @@ -147,9 +147,9 @@ mod test { use super::*; use anyhow::anyhow; use omicron_common::api::external::Error; + use std::sync::Arc; use std::sync::atomic::AtomicU8; use std::sync::atomic::Ordering; - use std::sync::Arc; // We don't need much from the testing "context" object. But it's handy to // be able to inject different values for `silo_authn_policy_for()`. diff --git a/nexus/auth/src/authn/external/session_cookie.rs b/nexus/auth/src/authn/external/session_cookie.rs index 3a407bc6982..74ae1e13666 100644 --- a/nexus/auth/src/authn/external/session_cookie.rs +++ b/nexus/auth/src/authn/external/session_cookie.rs @@ -192,9 +192,9 @@ fn get_token_from_cookie( #[cfg(test)] mod test { use super::{ - get_token_from_cookie, session_cookie_header_value, Details, - HttpAuthnScheme, HttpAuthnSessionCookie, Reason, SchemeResult, Session, - SessionStore, + Details, HttpAuthnScheme, HttpAuthnSessionCookie, Reason, SchemeResult, + Session, SessionStore, get_token_from_cookie, + session_cookie_header_value, }; use async_trait::async_trait; use chrono::{DateTime, Duration, Utc}; diff --git a/nexus/auth/src/authn/external/spoof.rs b/nexus/auth/src/authn/external/spoof.rs index 4aa2b1b443d..7aba530e63c 100644 --- a/nexus/auth/src/authn/external/spoof.rs +++ b/nexus/auth/src/authn/external/spoof.rs @@ -13,11 +13,11 @@ use super::SchemeResult; use super::SiloUserSilo; use crate::authn; use crate::authn::Actor; -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use async_trait::async_trait; -use headers::authorization::{Authorization, Bearer}; use headers::HeaderMapExt; +use headers::authorization::{Authorization, Bearer}; use slog::debug; use uuid::Uuid; @@ -189,10 +189,10 @@ mod test { use super::make_header_value; use super::make_header_value_raw; use super::make_header_value_str; - use headers::authorization::Bearer; - use headers::authorization::Credentials; use headers::Authorization; use headers::HeaderMapExt; + use headers::authorization::Bearer; + use headers::authorization::Credentials; use uuid::Uuid; #[test] diff --git a/nexus/auth/src/authn/external/token.rs b/nexus/auth/src/authn/external/token.rs index 32fedd1bc74..2cdeef91173 100644 --- a/nexus/auth/src/authn/external/token.rs +++ b/nexus/auth/src/authn/external/token.rs @@ -11,8 +11,8 @@ use super::SchemeResult; use super::SiloUserSilo; use crate::authn; use async_trait::async_trait; -use headers::authorization::{Authorization, Bearer}; use headers::HeaderMapExt; +use headers::authorization::{Authorization, Bearer}; // This scheme is intended for clients such as the API, CLI, etc. // @@ -96,12 +96,12 @@ pub trait TokenContext { #[cfg(test)] mod test { - use super::{parse_token, TOKEN_PREFIX}; + use super::{TOKEN_PREFIX, parse_token}; use anyhow::Context; - use headers::authorization::Bearer; - use headers::authorization::Credentials; use headers::Authorization; use headers::HeaderMapExt; + use headers::authorization::Bearer; + use headers::authorization::Credentials; /// Returns a value of the `Authorization` header for this actor that will be /// accepted using this scheme. diff --git a/nexus/auth/src/authn/silos.rs b/nexus/auth/src/authn/silos.rs index b451149d03d..c5b1214f83f 100644 --- a/nexus/auth/src/authn/silos.rs +++ b/nexus/auth/src/authn/silos.rs @@ -4,14 +4,14 @@ //! Silo related authentication types and functions -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use base64::Engine; use dropshot::HttpError; use samael::metadata::ContactPerson; use samael::metadata::ContactType; use samael::metadata::EntityDescriptor; -use samael::metadata::NameIdFormat; use samael::metadata::HTTP_REDIRECT_BINDING; +use samael::metadata::NameIdFormat; use samael::schema::Response as SAMLResponse; use samael::service_provider::ServiceProvider; use samael::service_provider::ServiceProviderBuilder; diff --git a/nexus/auth/src/authz/api_resources.rs b/nexus/auth/src/authz/api_resources.rs index 64fac91a4e1..f440f592084 100644 --- a/nexus/auth/src/authz/api_resources.rs +++ b/nexus/auth/src/authz/api_resources.rs @@ -28,17 +28,17 @@ use std::sync::LazyLock; +use super::Action; use super::actor::AnyActor; use super::context::AuthorizedResource; use super::oso_generic::Init; -use super::roles::{load_roles_for_resource_tree, RoleSet}; -use super::Action; -use super::{actor::AuthenticatedActor, Authz}; +use super::roles::{RoleSet, load_roles_for_resource_tree}; +use super::{Authz, actor::AuthenticatedActor}; use crate::authn; use crate::context::OpContext; use authz_macros::authz_resource; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_fixed_data::FLEET_ID; use nexus_types::external_api::shared::{FleetRole, ProjectRole, SiloRole}; use omicron_common::api::external::{Error, LookupType, ResourceType}; diff --git a/nexus/auth/src/authz/context.rs b/nexus/auth/src/authz/context.rs index bd375321e32..20437b7f535 100644 --- a/nexus/auth/src/authz/context.rs +++ b/nexus/auth/src/authz/context.rs @@ -7,8 +7,8 @@ use super::actor::AnyActor; use super::roles::RoleSet; use crate::authn; -use crate::authz::oso_generic; use crate::authz::Action; +use crate::authz::oso_generic; use crate::context::OpContext; use crate::storage::Storage; use futures::future::BoxFuture; diff --git a/nexus/auth/src/authz/mod.rs b/nexus/auth/src/authz/mod.rs index 36235b96b36..b39704af849 100644 --- a/nexus/auth/src/authz/mod.rs +++ b/nexus/auth/src/authz/mod.rs @@ -181,8 +181,8 @@ pub use context::Context; mod oso_generic; pub use oso_generic::Action; -pub use oso_generic::Database; pub use oso_generic::DATABASE; +pub use oso_generic::Database; mod roles; pub use roles::RoleSet; diff --git a/nexus/auth/src/authz/oso_generic.rs b/nexus/auth/src/authz/oso_generic.rs index 321bb98b1c6..cb1d9edc599 100644 --- a/nexus/auth/src/authz/oso_generic.rs +++ b/nexus/auth/src/authz/oso_generic.rs @@ -4,18 +4,18 @@ //! Oso integration +use super::Authz; use super::actor::AnyActor; use super::actor::AuthenticatedActor; use super::api_resources::*; use super::context::AuthorizedResource; use super::roles::RoleSet; -use super::Authz; use crate::authn; use crate::context::OpContext; -use anyhow::ensure; use anyhow::Context; -use futures::future::BoxFuture; +use anyhow::ensure; use futures::FutureExt; +use futures::future::BoxFuture; use omicron_common::api::external::Error; use oso::Oso; use oso::PolarClass; diff --git a/nexus/auth/src/context.rs b/nexus/auth/src/context.rs index 161ce6493b1..02785f9247c 100644 --- a/nexus/auth/src/context.rs +++ b/nexus/auth/src/context.rs @@ -5,8 +5,8 @@ //! Shared state used by API request handlers use super::authn; use super::authz; -use crate::authn::external::session_cookie::Session; use crate::authn::ConsoleSessionWithSiloId; +use crate::authn::external::session_cookie::Session; use crate::authz::AuthorizedResource; use crate::storage::Storage; use chrono::{DateTime, Utc}; diff --git a/nexus/benches/setup_benchmark.rs b/nexus/benches/setup_benchmark.rs index 21d876fa4b0..29a89465044 100644 --- a/nexus/benches/setup_benchmark.rs +++ b/nexus/benches/setup_benchmark.rs @@ -4,7 +4,7 @@ //! Benchmarks test setup/teardown. -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use dropshot::test_util::LogContext; use nexus_db_queries::db::pub_test_utils::TestDatabase; use omicron_test_utils::dev; diff --git a/nexus/db-fixed-data/src/lib.rs b/nexus/db-fixed-data/src/lib.rs index 0bfc0127ff2..062760afc97 100644 --- a/nexus/db-fixed-data/src/lib.rs +++ b/nexus/db-fixed-data/src/lib.rs @@ -67,9 +67,9 @@ fn assert_valid_uuid(id: &uuid::Uuid) { #[cfg(test)] mod test { + use super::FLEET_ID; use super::allow_list::USER_FACING_SERVICES_ALLOW_LIST_ID; use super::assert_valid_uuid; - use super::FLEET_ID; #[test] fn test_builtin_fleet_id_is_valid() { diff --git a/nexus/db-fixed-data/src/role_assignment.rs b/nexus/db-fixed-data/src/role_assignment.rs index 03ba63853b7..049ae5ff63f 100644 --- a/nexus/db-fixed-data/src/role_assignment.rs +++ b/nexus/db-fixed-data/src/role_assignment.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Built-in assignments for built-in users and built-in roles +use super::FLEET_ID; use super::role_builtin; use super::user_builtin; -use super::FLEET_ID; use nexus_db_model::IdentityType; use nexus_db_model::RoleAssignment; use std::sync::LazyLock; diff --git a/nexus/db-fixed-data/src/silo.rs b/nexus/db-fixed-data/src/silo.rs index d98fda3ef8f..b5dd6b41aad 100644 --- a/nexus/db-fixed-data/src/silo.rs +++ b/nexus/db-fixed-data/src/silo.rs @@ -6,8 +6,8 @@ use nexus_db_model as model; use nexus_types::{ external_api::{params, shared}, silo::{ - default_silo_name, internal_silo_name, DEFAULT_SILO_ID, - INTERNAL_SILO_ID, + DEFAULT_SILO_ID, INTERNAL_SILO_ID, default_silo_name, + internal_silo_name, }, }; use omicron_common::api::external::IdentityMetadataCreateParams; diff --git a/nexus/db-macros/src/lib.rs b/nexus/db-macros/src/lib.rs index d49cf89956d..872b96a1ebb 100644 --- a/nexus/db-macros/src/lib.rs +++ b/nexus/db-macros/src/lib.rs @@ -18,7 +18,7 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use serde_tokenstream::ParseWrapper; use syn::spanned::Spanned; -use syn::{parse_quote, Data, DataStruct, DeriveInput, Error, Fields, Ident}; +use syn::{Data, DataStruct, DeriveInput, Error, Fields, Ident, parse_quote}; mod lookup; #[cfg(test)] @@ -118,11 +118,7 @@ fn get_field_with_name<'a>( ) -> Option<&'a syn::Field> { if let Fields::Named(ref data_fields) = data.fields { data_fields.named.iter().find(|field| { - if let Some(ident) = &field.ident { - ident == name - } else { - false - } + if let Some(ident) = &field.ident { ident == name } else { false } }) } else { None diff --git a/nexus/db-model/src/affinity.rs b/nexus/db-model/src/affinity.rs index 5309ac95275..f5840ba00dd 100644 --- a/nexus/db-model/src/affinity.rs +++ b/nexus/db-model/src/affinity.rs @@ -6,8 +6,8 @@ //! Database representation of affinity and anti-affinity groups -use super::impl_enum_type; use super::Name; +use super::impl_enum_type; use crate::schema::affinity_group; use crate::schema::affinity_group_instance_membership; use crate::schema::anti_affinity_group; diff --git a/nexus/db-model/src/bfd.rs b/nexus/db-model/src/bfd.rs index 8a41c4c4ad6..9234fd95704 100644 --- a/nexus/db-model/src/bfd.rs +++ b/nexus/db-model/src/bfd.rs @@ -1,5 +1,5 @@ use crate::schema::bfd_session; -use crate::{impl_enum_type, SqlU32}; +use crate::{SqlU32, impl_enum_type}; use chrono::DateTime; use chrono::Utc; use ipnetwork::IpNetwork; diff --git a/nexus/db-model/src/clickhouse_policy.rs b/nexus/db-model/src/clickhouse_policy.rs index 55b50d903a2..8152430cf54 100644 --- a/nexus/db-model/src/clickhouse_policy.rs +++ b/nexus/db-model/src/clickhouse_policy.rs @@ -6,7 +6,7 @@ use super::impl_enum_type; use crate::SqlU32; -use crate::{schema::clickhouse_policy, SqlU8}; +use crate::{SqlU8, schema::clickhouse_policy}; use chrono::{DateTime, Utc}; use nexus_types::deployment; use serde::{Deserialize, Serialize}; diff --git a/nexus/db-model/src/collection.rs b/nexus/db-model/src/collection.rs index 964aaad2489..9441880dbd1 100644 --- a/nexus/db-model/src/collection.rs +++ b/nexus/db-model/src/collection.rs @@ -2,10 +2,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use diesel::pg::Pg; use diesel::Column; use diesel::ExpressionMethods; use diesel::Selectable; +use diesel::pg::Pg; use std::fmt::Debug; /// Trait to be implemented by any structs representing a collection. diff --git a/nexus/db-model/src/dataset_kind.rs b/nexus/db-model/src/dataset_kind.rs index e90f0d1db3f..9ae359c5235 100644 --- a/nexus/db-model/src/dataset_kind.rs +++ b/nexus/db-model/src/dataset_kind.rs @@ -51,10 +51,10 @@ impl DatasetKind { (Self::Debug, None) => ApiKind::Debug, (Self::Update, None) => ApiKind::Update, (Self::TransientZone, None) => { - return Err(Error::internal_error("Zone kind needs name")) + return Err(Error::internal_error("Zone kind needs name")); } (_, Some(_)) => { - return Err(Error::internal_error("Only zone kind needs name")) + return Err(Error::internal_error("Only zone kind needs name")); } }; diff --git a/nexus/db-model/src/db_metadata.rs b/nexus/db-model/src/db_metadata.rs index 48520a64d1d..25a43f5b384 100644 --- a/nexus/db-model/src/db_metadata.rs +++ b/nexus/db-model/src/db_metadata.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::schema::db_metadata; use crate::SemverVersion; +use crate::schema::db_metadata; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; diff --git a/nexus/db-model/src/deployment.rs b/nexus/db-model/src/deployment.rs index 367e3c4fd5a..cfc2147181c 100644 --- a/nexus/db-model/src/deployment.rs +++ b/nexus/db-model/src/deployment.rs @@ -17,15 +17,14 @@ use crate::schema::{ }; use crate::typed_uuid::DbTypedUuid; use crate::{ - impl_enum_type, ipv6, ByteCount, Generation, MacAddr, Name, SledState, - SqlU16, SqlU32, SqlU8, + ByteCount, Generation, MacAddr, Name, SledState, SqlU8, SqlU16, SqlU32, + impl_enum_type, ipv6, }; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use chrono::{DateTime, Utc}; use clickhouse_admin_types::{KeeperId, ServerId}; use ipnetwork::IpNetwork; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::deployment::BlueprintDatasetsConfig; @@ -39,6 +38,7 @@ use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::BlueprintZonesConfig; use nexus_types::deployment::ClickhouseClusterConfig; use nexus_types::deployment::CockroachDbPreserveDowngrade; +use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::{ OmicronZoneExternalFloatingAddr, OmicronZoneExternalFloatingIp, OmicronZoneExternalSnatIp, diff --git a/nexus/db-model/src/device_auth.rs b/nexus/db-model/src/device_auth.rs index 827e9ad54e7..86481898d2f 100644 --- a/nexus/db-model/src/device_auth.rs +++ b/nexus/db-model/src/device_auth.rs @@ -11,7 +11,7 @@ use crate::schema::{device_access_token, device_auth_request}; use chrono::{DateTime, Duration, Utc}; use nexus_types::external_api::views; -use rand::{distributions::Slice, rngs::StdRng, Rng, RngCore, SeedableRng}; +use rand::{Rng, RngCore, SeedableRng, distributions::Slice, rngs::StdRng}; use uuid::Uuid; /// Default timeout in seconds for client to authenticate for a token request. @@ -179,10 +179,12 @@ mod test { assert!( user_code.chars().nth(USER_CODE_WORD_LENGTH).unwrap() == '-' ); - assert!(user_code - .chars() - .filter(|x| *x != '-') - .all(|x| { USER_CODE_ALPHABET.iter().any(|y| *y == x) })); + assert!( + user_code + .chars() + .filter(|x| *x != '-') + .all(|x| { USER_CODE_ALPHABET.iter().any(|y| *y == x) }) + ); assert!(!codes_seen.contains(&user_code)); codes_seen.insert(user_code); } diff --git a/nexus/db-model/src/dns.rs b/nexus/db-model/src/dns.rs index 56dd1e05478..bef634adabb 100644 --- a/nexus/db-model/src/dns.rs +++ b/nexus/db-model/src/dns.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{impl_enum_type, Generation}; +use super::{Generation, impl_enum_type}; use crate::schema::{dns_name, dns_version, dns_zone}; use chrono::{DateTime, Utc}; use nexus_types::internal_api::params; diff --git a/nexus/db-model/src/external_ip.rs b/nexus/db-model/src/external_ip.rs index bfa7c73d3d9..424967a8b78 100644 --- a/nexus/db-model/src/external_ip.rs +++ b/nexus/db-model/src/external_ip.rs @@ -5,12 +5,12 @@ //! Model types for external IPs, both for instances and externally-facing //! services. -use crate::impl_enum_type; -use crate::schema::external_ip; -use crate::schema::floating_ip; use crate::Name; use crate::ServiceNetworkInterface; use crate::SqlU16; +use crate::impl_enum_type; +use crate::schema::external_ip; +use crate::schema::floating_ip; use chrono::DateTime; use chrono::Utc; use db_macros::Resource; diff --git a/nexus/db-model/src/instance.rs b/nexus/db-model/src/instance.rs index 19886c5f677..f915ac7cb14 100644 --- a/nexus/db-model/src/instance.rs +++ b/nexus/db-model/src/instance.rs @@ -10,7 +10,7 @@ use crate::collection::DatastoreAttachTargetConfig; use crate::schema::{disk, external_ip, instance}; use chrono::{DateTime, TimeDelta, Utc}; use db_macros::Resource; -use diesel::expression::{is_aggregate, ValidGrouping}; +use diesel::expression::{ValidGrouping, is_aggregate}; use diesel::pg; use diesel::prelude::*; use diesel::sql_types::{Bool, Nullable}; @@ -399,16 +399,16 @@ impl InstanceAutoRestart { /// Yes, this should probably be in `nexus-db-queries`, but it seemed nice /// for it to be defined on the same struct as the in-memory logic /// (`can_reincarnate`). - pub fn filter_reincarnatable( - ) -> impl diesel::query_builder::QueryFragment - + diesel::query_builder::QueryId - // All elements in this expression appear on the `instance` table, so - // it's a valid `filter` for that table, and the expression evaluates - // to a bool (or NULL), making it a valid WHERE clause. - + AppearsOnTable> - // I think this trait tells diesel that the query fragment has no - // GROUP BY clause, so that it knows it can be used as a WHERE clause - + ValidGrouping<(), IsAggregate = is_aggregate::No> { + pub fn filter_reincarnatable() + -> impl diesel::query_builder::QueryFragment + + diesel::query_builder::QueryId + // All elements in this expression appear on the `instance` table, so + // it's a valid `filter` for that table, and the expression evaluates + // to a bool (or NULL), making it a valid WHERE clause. + + AppearsOnTable> + // I think this trait tells diesel that the query fragment has no + // GROUP BY clause, so that it knows it can be used as a WHERE clause + + ValidGrouping<(), IsAggregate = is_aggregate::No> { use instance::dsl; let now = diesel::dsl::now.into_sql::(); diff --git a/nexus/db-model/src/instance_cpu_count.rs b/nexus/db-model/src/instance_cpu_count.rs index dfa524a452d..b03dc5028d1 100644 --- a/nexus/db-model/src/instance_cpu_count.rs +++ b/nexus/db-model/src/instance_cpu_count.rs @@ -55,6 +55,6 @@ where impl From for sled_agent_client::types::InstanceCpuCount { fn from(i: InstanceCpuCount) -> Self { - Self(i.0 .0) + Self(i.0.0) } } diff --git a/nexus/db-model/src/internet_gateway.rs b/nexus/db-model/src/internet_gateway.rs index 6ead292fc52..05a764e347a 100644 --- a/nexus/db-model/src/internet_gateway.rs +++ b/nexus/db-model/src/internet_gateway.rs @@ -1,8 +1,8 @@ use super::Generation; +use crate::DatastoreCollectionConfig; use crate::schema::{ internet_gateway, internet_gateway_ip_address, internet_gateway_ip_pool, }; -use crate::DatastoreCollectionConfig; use db_macros::Resource; use ipnetwork::IpNetwork; use nexus_types::external_api::{params, views}; diff --git a/nexus/db-model/src/inventory.rs b/nexus/db-model/src/inventory.rs index 2061618c82a..371f0c2456a 100644 --- a/nexus/db-model/src/inventory.rs +++ b/nexus/db-model/src/inventory.rs @@ -4,6 +4,7 @@ //! Types for representing the hardware/software inventory in the database +use crate::PhysicalDiskKind; use crate::omicron_zone_config::{self, OmicronZoneNic}; use crate::schema::{ hw_baseboard_id, inv_caboose, inv_clickhouse_keeper_membership, @@ -14,12 +15,11 @@ use crate::schema::{ sw_root_of_trust_page, }; use crate::typed_uuid::DbTypedUuid; -use crate::PhysicalDiskKind; use crate::{ - impl_enum_type, ipv6, ByteCount, Generation, MacAddr, Name, ServiceKind, - SqlU16, SqlU32, SqlU8, + ByteCount, Generation, MacAddr, Name, ServiceKind, SqlU8, SqlU16, SqlU32, + impl_enum_type, ipv6, }; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use chrono::DateTime; use chrono::Utc; use clickhouse_admin_types::{ClickhouseKeeperClusterMembership, KeeperId}; @@ -1788,7 +1788,7 @@ mod test { use nexus_types::inventory::NvmeFirmware; use omicron_uuid_kinds::{CollectionKind, SledUuid, TypedUuid}; - use crate::{typed_uuid, InvNvmeDiskFirmware, InvNvmeDiskFirmwareError}; + use crate::{InvNvmeDiskFirmware, InvNvmeDiskFirmwareError, typed_uuid}; #[test] fn test_inv_nvme_disk_firmware() { @@ -1988,12 +1988,14 @@ mod test { Some("4567".to_string()), ], }; - assert!(InvNvmeDiskFirmware::new( - inv_collection_id, - sled_id, - slot, - firmware, + assert!( + InvNvmeDiskFirmware::new( + inv_collection_id, + sled_id, + slot, + firmware, + ) + .is_ok() ) - .is_ok()) } } diff --git a/nexus/db-model/src/ip_pool.rs b/nexus/db-model/src/ip_pool.rs index 030d052c224..82ff1ca0d20 100644 --- a/nexus/db-model/src/ip_pool.rs +++ b/nexus/db-model/src/ip_pool.rs @@ -4,12 +4,12 @@ //! Model types for IP Pools and the CIDR blocks therein. +use crate::Name; use crate::collection::DatastoreCollectionConfig; use crate::impl_enum_type; use crate::schema::ip_pool; use crate::schema::ip_pool_range; use crate::schema::ip_pool_resource; -use crate::Name; use chrono::DateTime; use chrono::Utc; use db_macros::Resource; diff --git a/nexus/db-model/src/ipv4_nat_entry.rs b/nexus/db-model/src/ipv4_nat_entry.rs index c60c37a0bff..4c5337d966c 100644 --- a/nexus/db-model/src/ipv4_nat_entry.rs +++ b/nexus/db-model/src/ipv4_nat_entry.rs @@ -1,7 +1,7 @@ use super::MacAddr; use crate::{ - schema::ipv4_nat_changes, schema::ipv4_nat_entry, Ipv4Net, Ipv6Net, SqlU16, - Vni, + Ipv4Net, Ipv6Net, SqlU16, Vni, schema::ipv4_nat_changes, + schema::ipv4_nat_entry, }; use chrono::{DateTime, Utc}; use nexus_types::internal_api::views::Ipv4NatEntryView; diff --git a/nexus/db-model/src/ipv6net.rs b/nexus/db-model/src/ipv6net.rs index a045982f0d4..128be268735 100644 --- a/nexus/db-model/src/ipv6net.rs +++ b/nexus/db-model/src/ipv6net.rs @@ -9,7 +9,7 @@ use diesel::serialize::{self, ToSql}; use diesel::sql_types; use ipnetwork::IpNetwork; use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; -use rand::{rngs::StdRng, SeedableRng}; +use rand::{SeedableRng, rngs::StdRng}; use serde::Deserialize; use serde::Serialize; use std::net::Ipv6Addr; diff --git a/nexus/db-model/src/lib.rs b/nexus/db-model/src/lib.rs index 939388174e8..ae6ada02ac6 100644 --- a/nexus/db-model/src/lib.rs +++ b/nexus/db-model/src/lib.rs @@ -488,48 +488,70 @@ mod tests { ipv6_block, ); // Within subnet - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv4Addr::new( - 192, 168, 1, 10 - ))) - .is_ok()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv4Addr::new( + 192, 168, 1, 10 + ))) + .is_ok() + ); // Network address is reserved - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv4Addr::new(192, 168, 0, 0))) - .is_err()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv4Addr::new( + 192, 168, 0, 0 + ))) + .is_err() + ); // Broadcast address is reserved - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv4Addr::new( - 192, 168, 255, 255 - ))) - .is_err()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv4Addr::new( + 192, 168, 255, 255 + ))) + .is_err() + ); // Within subnet, but reserved - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv4Addr::new(192, 168, 0, 1))) - .is_err()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv4Addr::new( + 192, 168, 0, 1 + ))) + .is_err() + ); // Not within subnet - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv4Addr::new(192, 160, 1, 1))) - .is_err()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv4Addr::new( + 192, 160, 1, 1 + ))) + .is_err() + ); // Within subnet - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv6Addr::new( - 0xfd00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 - ))) - .is_ok()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv6Addr::new( + 0xfd00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 + ))) + .is_ok() + ); // Within subnet, but reserved - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv6Addr::new( - 0xfd00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 - ))) - .is_err()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv6Addr::new( + 0xfd00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + ))) + .is_err() + ); // Not within subnet - assert!(subnet - .check_requestable_addr(IpAddr::from(Ipv6Addr::new( - 0xfc00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 - ))) - .is_err()); + assert!( + subnet + .check_requestable_addr(IpAddr::from(Ipv6Addr::new( + 0xfc00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 + ))) + .is_err() + ); } #[test] diff --git a/nexus/db-model/src/migration.rs b/nexus/db-model/src/migration.rs index d7c18ae5dd5..8fc7e0b1e04 100644 --- a/nexus/db-model/src/migration.rs +++ b/nexus/db-model/src/migration.rs @@ -3,8 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::Generation; -use crate::schema::migration; use crate::MigrationState; +use crate::schema::migration; use chrono::DateTime; use chrono::Utc; use omicron_common::api::internal::nexus; diff --git a/nexus/db-model/src/network_interface.rs b/nexus/db-model/src/network_interface.rs index 15404524c5e..a764d25e4b3 100644 --- a/nexus/db-model/src/network_interface.rs +++ b/nexus/db-model/src/network_interface.rs @@ -3,12 +3,12 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::{MacAddr, VpcSubnet}; +use crate::Name; +use crate::SqlU8; use crate::impl_enum_type; use crate::schema::instance_network_interface; use crate::schema::network_interface; use crate::schema::service_network_interface; -use crate::Name; -use crate::SqlU8; use chrono::DateTime; use chrono::Utc; use db_macros::Resource; @@ -178,7 +178,9 @@ impl ServiceNetworkInterface { } #[derive(Debug, thiserror::Error)] -#[error("Service NIC {nic_id} has a range of IPs ({ip}); only a single IP is supported")] +#[error( + "Service NIC {nic_id} has a range of IPs ({ip}); only a single IP is supported" +)] pub struct ServiceNicNotSingleIpError { pub nic_id: Uuid, pub ip: ipnetwork::IpNetwork, diff --git a/nexus/db-model/src/omicron_zone_config.rs b/nexus/db-model/src/omicron_zone_config.rs index 44396d7a2a2..74e2b9637b9 100644 --- a/nexus/db-model/src/omicron_zone_config.rs +++ b/nexus/db-model/src/omicron_zone_config.rs @@ -12,8 +12,8 @@ //! collecting extra metadata like uptime). This module provides conversion //! helpers for the parts of those tables that are common between the two. -use crate::{MacAddr, Name, SqlU16, SqlU32, SqlU8}; -use anyhow::{anyhow, bail, ensure, Context}; +use crate::{MacAddr, Name, SqlU8, SqlU16, SqlU32}; +use anyhow::{Context, anyhow, bail, ensure}; use ipnetwork::IpNetwork; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; use nexus_types::inventory::NetworkInterface; diff --git a/nexus/db-model/src/project.rs b/nexus/db-model/src/project.rs index 2079751a1c4..a7f0d154904 100644 --- a/nexus/db-model/src/project.rs +++ b/nexus/db-model/src/project.rs @@ -6,12 +6,12 @@ use super::{ AffinityGroup, AntiAffinityGroup, Disk, Generation, Instance, Name, Snapshot, Vpc, }; +use crate::Image; use crate::collection::DatastoreCollectionConfig; use crate::schema::{ affinity_group, anti_affinity_group, disk, image, instance, project, snapshot, vpc, }; -use crate::Image; use chrono::{DateTime, Utc}; use db_macros::Resource; use nexus_types::external_api::params; diff --git a/nexus/db-model/src/region.rs b/nexus/db-model/src/region.rs index b6d51c9a379..c39301b1b83 100644 --- a/nexus/db-model/src/region.rs +++ b/nexus/db-model/src/region.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::ByteCount; +use crate::SqlU16; use crate::schema::region; use crate::typed_uuid::DbTypedUuid; -use crate::SqlU16; use db_macros::Asset; use omicron_common::api::external; use omicron_uuid_kinds::DatasetKind; diff --git a/nexus/db-model/src/region_replacement.rs b/nexus/db-model/src/region_replacement.rs index 817563fa937..03e1af6bb13 100644 --- a/nexus/db-model/src/region_replacement.rs +++ b/nexus/db-model/src/region_replacement.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::impl_enum_type; +use crate::Region; use crate::schema::region_replacement; use crate::typed_uuid::DbTypedUuid; -use crate::Region; use chrono::DateTime; use chrono::Utc; use omicron_uuid_kinds::VolumeKind; diff --git a/nexus/db-model/src/region_replacement_step.rs b/nexus/db-model/src/region_replacement_step.rs index c0a61b958cf..677ed559587 100644 --- a/nexus/db-model/src/region_replacement_step.rs +++ b/nexus/db-model/src/region_replacement_step.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::impl_enum_type; +use crate::SqlU16; use crate::ipv6; use crate::schema::region_replacement_step; -use crate::SqlU16; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::net::SocketAddrV6; diff --git a/nexus/db-model/src/region_snapshot_replacement.rs b/nexus/db-model/src/region_snapshot_replacement.rs index 4a92d7287bf..6abb9d64a44 100644 --- a/nexus/db-model/src/region_snapshot_replacement.rs +++ b/nexus/db-model/src/region_snapshot_replacement.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::impl_enum_type; +use crate::RegionSnapshot; use crate::schema::region_snapshot_replacement; use crate::typed_uuid::DbTypedUuid; -use crate::RegionSnapshot; use chrono::DateTime; use chrono::Utc; use omicron_uuid_kinds::DatasetKind; diff --git a/nexus/db-model/src/role_assignment.rs b/nexus/db-model/src/role_assignment.rs index fbbe18579e6..af70f3b3100 100644 --- a/nexus/db-model/src/role_assignment.rs +++ b/nexus/db-model/src/role_assignment.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{impl_enum_type, DatabaseString}; +use super::{DatabaseString, impl_enum_type}; use crate::schema::role_assignment; use anyhow::anyhow; use nexus_types::external_api::shared; diff --git a/nexus/db-model/src/schema_versions.rs b/nexus/db-model/src/schema_versions.rs index b6511ec1924..85886b01473 100644 --- a/nexus/db-model/src/schema_versions.rs +++ b/nexus/db-model/src/schema_versions.rs @@ -6,7 +6,7 @@ //! //! For details, see schema/crdb/README.adoc in the root of this repository. -use anyhow::{bail, ensure, Context}; +use anyhow::{Context, bail, ensure}; use camino::Utf8Path; use omicron_common::api::external::SemverVersion; use std::{collections::BTreeMap, sync::LazyLock}; diff --git a/nexus/db-model/src/silo.rs b/nexus/db-model/src/silo.rs index 66520fccb1f..3e7a3f4de77 100644 --- a/nexus/db-model/src/silo.rs +++ b/nexus/db-model/src/silo.rs @@ -5,7 +5,7 @@ use super::{Generation, Project}; use crate::collection::DatastoreCollectionConfig; use crate::schema::{image, project, silo}; -use crate::{impl_enum_type, DatabaseString, Image}; +use crate::{DatabaseString, Image, impl_enum_type}; use db_macros::Resource; use nexus_types::external_api::shared::{ FleetRole, SiloIdentityMode, SiloRole, diff --git a/nexus/db-model/src/sled_instance.rs b/nexus/db-model/src/sled_instance.rs index 1415c38eea8..6364b1d7a9d 100644 --- a/nexus/db-model/src/sled_instance.rs +++ b/nexus/db-model/src/sled_instance.rs @@ -1,6 +1,6 @@ -use crate::schema::sled_instance; use crate::Name; use crate::VmmState; +use crate::schema::sled_instance; use db_macros::Asset; use nexus_types::external_api::views; use nexus_types::identity::Asset; diff --git a/nexus/db-model/src/snapshot.rs b/nexus/db-model/src/snapshot.rs index 66fc2589cb9..c7fcf1d7f06 100644 --- a/nexus/db-model/src/snapshot.rs +++ b/nexus/db-model/src/snapshot.rs @@ -2,11 +2,11 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{impl_enum_type, ByteCount}; -use crate::schema::snapshot; -use crate::typed_uuid::DbTypedUuid; +use super::{ByteCount, impl_enum_type}; use crate::BlockSize; use crate::Generation; +use crate::schema::snapshot; +use crate::typed_uuid::DbTypedUuid; use db_macros::Resource; use nexus_types::external_api::views; use nexus_types::identity::Resource; diff --git a/nexus/db-model/src/switch.rs b/nexus/db-model/src/switch.rs index d5c523e9c43..556577f076f 100644 --- a/nexus/db-model/src/switch.rs +++ b/nexus/db-model/src/switch.rs @@ -3,7 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::Generation; -use crate::{schema::switch, SqlU32}; +use crate::{SqlU32, schema::switch}; use chrono::{DateTime, Utc}; use db_macros::Asset; use nexus_types::{external_api::shared, external_api::views, identity::Asset}; diff --git a/nexus/db-model/src/switch_interface.rs b/nexus/db-model/src/switch_interface.rs index 78f502ed4c8..2954aaa77ad 100644 --- a/nexus/db-model/src/switch_interface.rs +++ b/nexus/db-model/src/switch_interface.rs @@ -1,9 +1,9 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::SqlU16; use crate::impl_enum_type; use crate::schema::{loopback_address, switch_vlan_interface_config}; -use crate::SqlU16; use db_macros::Asset; use ipnetwork::IpNetwork; use nexus_types::external_api::params; diff --git a/nexus/db-model/src/switch_port.rs b/nexus/db-model/src/switch_port.rs index 8d44c0fb20c..d7bcb2412be 100644 --- a/nexus/db-model/src/switch_port.rs +++ b/nexus/db-model/src/switch_port.rs @@ -13,8 +13,8 @@ use crate::schema::{ switch_port_settings_port_config, switch_port_settings_route_config, tx_eq_config, }; -use crate::{impl_enum_type, SqlU32}; -use crate::{SqlU16, SqlU8}; +use crate::{SqlU8, SqlU16}; +use crate::{SqlU32, impl_enum_type}; use chrono::{DateTime, Utc}; use db_macros::Resource; use diesel::AsChangeset; diff --git a/nexus/db-model/src/tuf_repo.rs b/nexus/db-model/src/tuf_repo.rs index f603e681887..88cd704ddac 100644 --- a/nexus/db-model/src/tuf_repo.rs +++ b/nexus/db-model/src/tuf_repo.rs @@ -5,9 +5,9 @@ use std::str::FromStr; use crate::{ + SemverVersion, schema::{tuf_artifact, tuf_repo, tuf_repo_artifact}, typed_uuid::DbTypedUuid, - SemverVersion, }; use chrono::{DateTime, Utc}; use diesel::{deserialize::FromSql, serialize::ToSql, sql_types::Text}; diff --git a/nexus/db-model/src/upstairs_repair.rs b/nexus/db-model/src/upstairs_repair.rs index ed281b6c64e..8c0b1fe7939 100644 --- a/nexus/db-model/src/upstairs_repair.rs +++ b/nexus/db-model/src/upstairs_repair.rs @@ -3,11 +3,11 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::impl_enum_type; +use crate::SqlU16; use crate::ipv6; use crate::schema::upstairs_repair_notification; use crate::schema::upstairs_repair_progress; use crate::typed_uuid::DbTypedUuid; -use crate::SqlU16; use chrono::{DateTime, Utc}; use omicron_common::api::internal; use omicron_uuid_kinds::DownstairsRegionKind; diff --git a/nexus/db-model/src/utilization.rs b/nexus/db-model/src/utilization.rs index e82600d64dc..9742851a61c 100644 --- a/nexus/db-model/src/utilization.rs +++ b/nexus/db-model/src/utilization.rs @@ -1,5 +1,5 @@ use crate::ByteCount; -use crate::{schema::silo_utilization, Name}; +use crate::{Name, schema::silo_utilization}; use nexus_types::external_api::views; use serde::{Deserialize, Serialize}; use uuid::Uuid; diff --git a/nexus/db-model/src/virtual_provisioning_collection.rs b/nexus/db-model/src/virtual_provisioning_collection.rs index 6e2202a67a1..2a4bba141ea 100644 --- a/nexus/db-model/src/virtual_provisioning_collection.rs +++ b/nexus/db-model/src/virtual_provisioning_collection.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::schema::virtual_provisioning_collection; use crate::ByteCount; +use crate::schema::virtual_provisioning_collection; use chrono::{DateTime, Utc}; use omicron_common::api::external; use parse_display::Display; diff --git a/nexus/db-model/src/virtual_provisioning_resource.rs b/nexus/db-model/src/virtual_provisioning_resource.rs index 237e37b17b4..1421124b7ae 100644 --- a/nexus/db-model/src/virtual_provisioning_resource.rs +++ b/nexus/db-model/src/virtual_provisioning_resource.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::schema::virtual_provisioning_resource; use crate::ByteCount; +use crate::schema::virtual_provisioning_resource; use chrono::{DateTime, Utc}; use omicron_common::api::external; use uuid::Uuid; diff --git a/nexus/db-model/src/vmm.rs b/nexus/db-model/src/vmm.rs index 45411f587ac..b0f7bf22fe6 100644 --- a/nexus/db-model/src/vmm.rs +++ b/nexus/db-model/src/vmm.rs @@ -13,8 +13,8 @@ //! sled agent or that sled agent will never update (like the sled ID). use super::{Generation, VmmState}; -use crate::schema::vmm; use crate::SqlU16; +use crate::schema::vmm; use chrono::{DateTime, Utc}; use omicron_uuid_kinds::{GenericUuid, InstanceUuid, PropolisUuid, SledUuid}; use serde::{Deserialize, Serialize}; diff --git a/nexus/db-model/src/vpc.rs b/nexus/db-model/src/vpc.rs index 88879a0436e..e590bf589e2 100644 --- a/nexus/db-model/src/vpc.rs +++ b/nexus/db-model/src/vpc.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::{Generation, Ipv6Net, Name, VpcFirewallRule, VpcSubnet}; +use crate::Vni; use crate::collection::DatastoreCollectionConfig; use crate::schema::{vpc, vpc_firewall_rule, vpc_subnet}; -use crate::Vni; use chrono::{DateTime, Utc}; use db_macros::Resource; use ipnetwork::IpNetwork; diff --git a/nexus/db-model/src/vpc_firewall_rule.rs b/nexus/db-model/src/vpc_firewall_rule.rs index 4601de66c5d..67ad7e5462a 100644 --- a/nexus/db-model/src/vpc_firewall_rule.rs +++ b/nexus/db-model/src/vpc_firewall_rule.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{impl_enum_wrapper, L4PortRange, SqlU16}; +use super::{L4PortRange, SqlU16, impl_enum_wrapper}; use crate::schema::vpc_firewall_rule; use db_macros::Resource; use diesel::backend::Backend; @@ -166,7 +166,7 @@ impl ToSql for VpcFirewallRulePriority { out: &mut serialize::Output<'a, '_, Pg>, ) -> serialize::Result { >::to_sql( - &SqlU16(self.0 .0), + &SqlU16(self.0.0), &mut out.reborrow(), ) } diff --git a/nexus/db-model/src/vpc_route.rs b/nexus/db-model/src/vpc_route.rs index dbbf8e16bb4..bd739e32bc1 100644 --- a/nexus/db-model/src/vpc_route.rs +++ b/nexus/db-model/src/vpc_route.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{impl_enum_wrapper, Name}; +use super::{Name, impl_enum_wrapper}; use crate::schema::router_route; use chrono::{DateTime, Utc}; use db_macros::Resource; diff --git a/nexus/db-model/src/vpc_router.rs b/nexus/db-model/src/vpc_router.rs index ee8988ae69d..0df3427e289 100644 --- a/nexus/db-model/src/vpc_router.rs +++ b/nexus/db-model/src/vpc_router.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{impl_enum_type, Generation, Name, RouterRoute}; +use super::{Generation, Name, RouterRoute, impl_enum_type}; use crate::collection::DatastoreCollectionConfig; use crate::schema::{router_route, vpc_router, vpc_subnet}; use crate::{DatastoreAttachTargetConfig, VpcSubnet}; diff --git a/nexus/db-model/src/vpc_subnet.rs b/nexus/db-model/src/vpc_subnet.rs index 26aa192dfec..a4ec906cdff 100644 --- a/nexus/db-model/src/vpc_subnet.rs +++ b/nexus/db-model/src/vpc_subnet.rs @@ -4,10 +4,10 @@ use super::Generation; use super::{Ipv4Net, Ipv6Net, Name}; +use crate::NetworkInterface; use crate::collection::DatastoreCollectionConfig; use crate::schema::network_interface; use crate::schema::vpc_subnet; -use crate::NetworkInterface; use chrono::{DateTime, Utc}; use db_macros::Resource; use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; diff --git a/nexus/db-queries/src/db/collection_attach.rs b/nexus/db-queries/src/db/collection_attach.rs index 01ad7001771..644eef919dc 100644 --- a/nexus/db-queries/src/db/collection_attach.rs +++ b/nexus/db-queries/src/db/collection_attach.rs @@ -135,7 +135,6 @@ pub trait DatastoreAttachTarget: // Treat the collection and resource as boxed tables. CollectionTable: BoxableTable, ResourceTable: BoxableTable, - // Allows treating "collection_exists_query" as a boxed "dyn QueryFragment". QueryFromClause>: QueryFragment + Send, @@ -154,7 +153,6 @@ pub trait DatastoreAttachTarget: + FilterBy> + FilterBy> + FilterBy>, - // Allows calling "update.into_boxed()" UpdateStatement< ResourceTable, @@ -166,7 +164,6 @@ pub trait DatastoreAttachTarget: // boxed update statement. BoxedUpdateStatement<'static, Pg, ResourceTable, V>: FilterBy, Self::Id>>, - // Allows using "id" in expressions (e.g. ".eq(...)") with... Self::Id: AsExpression< // ... The Collection table's PK @@ -181,7 +178,6 @@ pub trait DatastoreAttachTarget: ExprSqlType>: SingleValue, ExprSqlType>: SingleValue, ExprSqlType: SingleValue, - // Necessary to actually select the resource in the output type. ResourceType: Selectable, { @@ -354,10 +350,10 @@ where where // We require this bound to ensure that "Self" is runnable as query. Self: query_methods::LoadQuery< - 'static, - DbConnection, - RawOutput, - >, + 'static, + DbConnection, + RawOutput, + >, { self.get_result_async::>(conn) .await @@ -582,10 +578,10 @@ mod test { use async_bb8_diesel::{AsyncRunQueryDsl, AsyncSimpleConnection}; use chrono::Utc; use db_macros::Resource; - use diesel::expression_methods::ExpressionMethods; - use diesel::pg::Pg; use diesel::QueryDsl; use diesel::SelectableHelper; + use diesel::expression_methods::ExpressionMethods; + use diesel::pg::Pg; use omicron_common::api::external::{IdentityMetadataCreateParams, Name}; use omicron_test_utils::dev; use uuid::Uuid; @@ -1386,10 +1382,9 @@ mod test { get_resource(resource_id1, &conn).await.collection_id.unwrap(), collection_id ); - assert!(get_resource(resource_id2, &conn) - .await - .collection_id - .is_none()); + assert!( + get_resource(resource_id2, &conn).await.collection_id.is_none() + ); db.terminate().await; logctx.cleanup_successful(); diff --git a/nexus/db-queries/src/db/collection_detach.rs b/nexus/db-queries/src/db/collection_detach.rs index 618663c3316..23b761a2eed 100644 --- a/nexus/db-queries/src/db/collection_detach.rs +++ b/nexus/db-queries/src/db/collection_detach.rs @@ -82,7 +82,6 @@ pub trait DatastoreDetachTarget: // Treat the collection and resource as boxed tables. CollectionTable: BoxableTable, ResourceTable: BoxableTable, - // Allows treating "collection_exists_query" as a boxed "dyn QueryFragment". QueryFromClause>: QueryFragment + Send, @@ -91,7 +90,6 @@ pub trait DatastoreDetachTarget: QueryFromClause>: QueryFragment + Send, QuerySqlType>: Send, - // Allows calling ".filter()" on the boxed collection table. BoxedQuery>: FilterBy, Self::Id>> + FilterBy>, @@ -99,20 +97,17 @@ pub trait DatastoreDetachTarget: BoxedQuery>: FilterBy, Self::Id>> + FilterBy> + FilterBy>, - // Allows calling "update.into_boxed()" UpdateStatement< ResourceTable, ResourceTableDefaultWhereClause, V, >: BoxableUpdateStatement, V>, - // Allows calling // ".filter(resource_table().primary_key().eq(resource_id)" on the // boxed update statement. BoxedUpdateStatement<'static, Pg, ResourceTable, V>: FilterBy, Self::Id>>, - // Allows using "id" in expressions (e.g. ".eq(...)") with... Self::Id: AsExpression< // ... The Collection table's PK @@ -127,7 +122,6 @@ pub trait DatastoreDetachTarget: ExprSqlType>: SingleValue, ExprSqlType>: SingleValue, ExprSqlType: SingleValue, - // Necessary to actually select the resource in the output type. ResourceType: Selectable, { @@ -271,10 +265,10 @@ where where // We require this bound to ensure that "Self" is runnable as query. Self: query_methods::LoadQuery< - 'static, - DbConnection, - RawOutput, - >, + 'static, + DbConnection, + RawOutput, + >, { self.get_result_async::>(conn) .await @@ -486,10 +480,10 @@ mod test { use async_bb8_diesel::{AsyncRunQueryDsl, AsyncSimpleConnection}; use chrono::Utc; use db_macros::Resource; - use diesel::expression_methods::ExpressionMethods; - use diesel::pg::Pg; use diesel::QueryDsl; use diesel::SelectableHelper; + use diesel::expression_methods::ExpressionMethods; + use diesel::pg::Pg; use omicron_common::api::external::{IdentityMetadataCreateParams, Name}; use omicron_test_utils::dev; use uuid::Uuid; @@ -1023,14 +1017,12 @@ mod test { // Note that only "resource1" should be detached. // "resource2" should have automatically been filtered away from the // update statement, regardless of user input. - assert!(get_resource(resource_id1, &conn) - .await - .collection_id - .is_none()); - assert!(get_resource(resource_id2, &conn) - .await - .collection_id - .is_some()); + assert!( + get_resource(resource_id1, &conn).await.collection_id.is_none() + ); + assert!( + get_resource(resource_id2, &conn).await.collection_id.is_some() + ); db.terminate().await; logctx.cleanup_successful(); diff --git a/nexus/db-queries/src/db/collection_detach_many.rs b/nexus/db-queries/src/db/collection_detach_many.rs index c1056046793..00f5f58b83e 100644 --- a/nexus/db-queries/src/db/collection_detach_many.rs +++ b/nexus/db-queries/src/db/collection_detach_many.rs @@ -79,7 +79,6 @@ pub trait DatastoreDetachManyTarget: // Treat the collection and resource as boxed tables. CollectionTable: BoxableTable, ResourceTable: BoxableTable, - // Allows treating "collection_exists_query" as a boxed "dyn QueryFragment". QueryFromClause>: QueryFragment + Send, @@ -88,14 +87,12 @@ pub trait DatastoreDetachManyTarget: QueryFromClause>: QueryFragment + Send, QuerySqlType>: Send, - // Allows calling ".filter()" on the boxed collection table. BoxedQuery>: FilterBy, Self::Id>> + FilterBy>, // Allows calling ".filter()" on the boxed resource table. BoxedQuery>: FilterBy> + FilterBy>, - // Allows calling "update.into_boxed()" UpdateStatement< CollectionTable, @@ -107,7 +104,6 @@ pub trait DatastoreDetachManyTarget: ResourceTableDefaultWhereClause, VR, >: BoxableUpdateStatement, VR>, - // Allows calling // ".filter(collection_table().primary_key().eq(collection_id)" on the // boxed update statement. @@ -126,7 +122,6 @@ pub trait DatastoreDetachManyTarget: VR, >: FilterBy> + FilterBy>, - // Allows using "id" in expressions (e.g. ".eq(...)") with... Self::Id: AsExpression< // ... The Collection table's PK @@ -141,7 +136,6 @@ pub trait DatastoreDetachManyTarget: ExprSqlType>: SingleValue, ExprSqlType>: SingleValue, ExprSqlType: SingleValue, - ResourceType: Selectable, { let collection_table = @@ -484,10 +478,10 @@ mod test { use async_bb8_diesel::{AsyncRunQueryDsl, AsyncSimpleConnection}; use chrono::Utc; use db_macros::Resource; - use diesel::expression_methods::ExpressionMethods; - use diesel::pg::Pg; use diesel::QueryDsl; use diesel::SelectableHelper; + use diesel::expression_methods::ExpressionMethods; + use diesel::pg::Pg; use omicron_common::api::external::{IdentityMetadataCreateParams, Name}; use omicron_test_utils::dev; use uuid::Uuid; @@ -1131,14 +1125,12 @@ mod test { assert_eq!(returned_resource.description(), "Updated desc"); // Note that only "resource1" and "resource2" should be detached. - assert!(get_resource(resource_id1, &conn) - .await - .collection_id - .is_none()); - assert!(get_resource(resource_id2, &conn) - .await - .collection_id - .is_none()); + assert!( + get_resource(resource_id1, &conn).await.collection_id.is_none() + ); + assert!( + get_resource(resource_id2, &conn).await.collection_id.is_none() + ); // "resource3" should have been left alone. assert_eq!( diff --git a/nexus/db-queries/src/db/collection_insert.rs b/nexus/db-queries/src/db/collection_insert.rs index 1be10f4eba1..4f40113403d 100644 --- a/nexus/db-queries/src/db/collection_insert.rs +++ b/nexus/db-queries/src/db/collection_insert.rs @@ -80,8 +80,8 @@ pub trait DatastoreCollection: >, // Allows using "key" in in ".eq(...)". CollectionId: diesel::expression::AsExpression< - SerializedCollectionPrimaryKey, - >, + SerializedCollectionPrimaryKey, + >, as Expression>::SqlType: SingleValue, // Allows calling "is_null()" on the time deleted column. @@ -410,9 +410,9 @@ mod test { use async_bb8_diesel::{AsyncRunQueryDsl, AsyncSimpleConnection}; use chrono::{DateTime, Utc}; use db_macros::Resource; + use diesel::QueryDsl; use diesel::expression_methods::ExpressionMethods; use diesel::pg::Pg; - use diesel::QueryDsl; use omicron_test_utils::dev; table! { diff --git a/nexus/db-queries/src/db/config.rs b/nexus/db-queries/src/db/config.rs index dc938b07aca..d72b3010788 100644 --- a/nexus/db-queries/src/db/config.rs +++ b/nexus/db-queries/src/db/config.rs @@ -7,8 +7,8 @@ use nexus_config::PostgresConfigWithUrl; use serde::Deserialize; use serde::Serialize; -use serde_with::serde_as; use serde_with::DisplayFromStr; +use serde_with::serde_as; /// Nexus database configuration #[serde_as] diff --git a/nexus/db-queries/src/db/cte_utils.rs b/nexus/db-queries/src/db/cte_utils.rs index 42743647f7e..c14c12f36d9 100644 --- a/nexus/db-queries/src/db/cte_utils.rs +++ b/nexus/db-queries/src/db/cte_utils.rs @@ -66,10 +66,10 @@ impl FilterBy for T where /// Allows calling ".into_boxed" on an update statement. pub trait BoxableUpdateStatement: query_methods::BoxedDsl< - 'static, - Pg, - Output = BoxedUpdateStatement<'static, Pg, Table, V>, -> + 'static, + Pg, + Output = BoxedUpdateStatement<'static, Pg, Table, V>, + > where Table: QuerySource, { @@ -77,10 +77,10 @@ where impl BoxableUpdateStatement for T where T: query_methods::BoxedDsl< - 'static, - Pg, - Output = BoxedUpdateStatement<'static, Pg, Table, V>, - >, + 'static, + Pg, + Output = BoxedUpdateStatement<'static, Pg, Table, V>, + >, Table: QuerySource, { } diff --git a/nexus/db-queries/src/db/datastore/address_lot.rs b/nexus/db-queries/src/db/datastore/address_lot.rs index 459c2a4c361..ee722c359fb 100644 --- a/nexus/db-queries/src/db/datastore/address_lot.rs +++ b/nexus/db-queries/src/db/datastore/address_lot.rs @@ -7,9 +7,9 @@ use crate::authz; use crate::context::OpContext; use crate::db; use crate::db::datastore::PgConnection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; use crate::db::error::TransactionError; +use crate::db::error::public_error_from_diesel; use crate::db::model::Name; use crate::db::model::{AddressLot, AddressLotBlock, AddressLotReservedBlock}; use crate::db::pagination::paginated; diff --git a/nexus/db-queries/src/db/datastore/allow_list.rs b/nexus/db-queries/src/db/datastore/allow_list.rs index 335edf2f23f..b161331e52f 100644 --- a/nexus/db-queries/src/db/datastore/allow_list.rs +++ b/nexus/db-queries/src/db/datastore/allow_list.rs @@ -6,16 +6,16 @@ use crate::authz; use crate::context::OpContext; -use crate::db::error::public_error_from_diesel; -use crate::db::error::ErrorHandler; use crate::db::DbConnection; +use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::SelectableHelper; use nexus_db_fixed_data::allow_list::USER_FACING_SERVICES_ALLOW_LIST_ID; -use nexus_db_model::schema::allow_list; use nexus_db_model::AllowList; +use nexus_db_model::schema::allow_list; use omicron_common::api::external::AllowedSourceIps; use omicron_common::api::external::Error; use omicron_common::api::external::LookupType; diff --git a/nexus/db-queries/src/db/datastore/auth.rs b/nexus/db-queries/src/db/datastore/auth.rs index 3b1d1d18e32..7647bce214e 100644 --- a/nexus/db-queries/src/db/datastore/auth.rs +++ b/nexus/db-queries/src/db/datastore/auth.rs @@ -5,8 +5,8 @@ //! Implements the [Storage] interface for [nexus_auth] integration. use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; diff --git a/nexus/db-queries/src/db/datastore/bfd.rs b/nexus/db-queries/src/db/datastore/bfd.rs index fba19259a68..e1f76bd36a6 100644 --- a/nexus/db-queries/src/db/datastore/bfd.rs +++ b/nexus/db-queries/src/db/datastore/bfd.rs @@ -5,8 +5,8 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ExpressionMethods, QueryDsl, SelectableHelper}; diff --git a/nexus/db-queries/src/db/datastore/bgp.rs b/nexus/db-queries/src/db/datastore/bgp.rs index 7f0607bf724..23a4e35b77d 100644 --- a/nexus/db-queries/src/db/datastore/bgp.rs +++ b/nexus/db-queries/src/db/datastore/bgp.rs @@ -5,7 +5,7 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::{public_error_from_diesel, ErrorHandler}; +use crate::db::error::{ErrorHandler, public_error_from_diesel}; use crate::db::model::{BgpAnnounceSet, BgpAnnouncement, BgpConfig, Name}; use crate::db::pagination::paginated; use crate::transaction_retry::OptionalError; diff --git a/nexus/db-queries/src/db/datastore/bootstore.rs b/nexus/db-queries/src/db/datastore/bootstore.rs index 9384a1e13f4..84b22682d1a 100644 --- a/nexus/db-queries/src/db/datastore/bootstore.rs +++ b/nexus/db-queries/src/db/datastore/bootstore.rs @@ -1,11 +1,11 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::{public_error_from_diesel, ErrorHandler}; +use crate::db::error::{ErrorHandler, public_error_from_diesel}; use async_bb8_diesel::AsyncRunQueryDsl; -use diesel::prelude::*; use diesel::ExpressionMethods; use diesel::SelectableHelper; +use diesel::prelude::*; use nexus_db_model::{BootstoreConfig, BootstoreKeys}; use omicron_common::api::external::{CreateResult, LookupResult}; diff --git a/nexus/db-queries/src/db/datastore/certificate.rs b/nexus/db-queries/src/db/datastore/certificate.rs index 4b043becd81..c4969fc7fc4 100644 --- a/nexus/db-queries/src/db/datastore/certificate.rs +++ b/nexus/db-queries/src/db/datastore/certificate.rs @@ -8,8 +8,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::Certificate; use crate::db::model::Name; use crate::db::model::ServiceKind; @@ -18,12 +18,12 @@ use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::InternalContext; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::ResourceType; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; impl DataStore { diff --git a/nexus/db-queries/src/db/datastore/clickhouse_policy.rs b/nexus/db-queries/src/db/datastore/clickhouse_policy.rs index e207adab376..3d0280d4867 100644 --- a/nexus/db-queries/src/db/datastore/clickhouse_policy.rs +++ b/nexus/db-queries/src/db/datastore/clickhouse_policy.rs @@ -8,21 +8,21 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; -use diesel::dsl::sql_query; -use diesel::expression::SelectableHelper; -use diesel::sql_types; use diesel::ExpressionMethods; use diesel::OptionalExtension; use diesel::QueryDsl; +use diesel::dsl::sql_query; +use diesel::expression::SelectableHelper; +use diesel::sql_types; use nexus_db_model::ClickhouseModeEnum; use nexus_db_model::ClickhousePolicy as DbClickhousePolicy; use nexus_db_model::DbClickhouseMode; -use nexus_db_model::SqlU32; use nexus_db_model::SqlU8; +use nexus_db_model::SqlU32; use nexus_types::deployment::ClickhousePolicy; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::Error; @@ -189,11 +189,13 @@ mod tests { // Listing an empty table should return an empty vec - assert!(datastore - .clickhouse_policy_list(opctx, &DataPageParams::max_page()) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .clickhouse_policy_list(opctx, &DataPageParams::max_page()) + .await + .unwrap() + .is_empty() + ); // Fail to insert a policy with version 0 let mut policy = ClickhousePolicy { @@ -202,60 +204,74 @@ mod tests { time_created: now_db_precision(), }; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .unwrap_err() - .to_string() - .contains("policy version must be greater than 0")); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .unwrap_err() + .to_string() + .contains("policy version must be greater than 0") + ); // Inserting version 2 before version 1 should not work policy.version = 2; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .unwrap_err() - .to_string() - .contains("policy version 2 is not the most recent")); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .unwrap_err() + .to_string() + .contains("policy version 2 is not the most recent") + ); // Inserting version 1 should work policy.version = 1; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .is_ok()); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .is_ok() + ); // Inserting version 2 should work policy.version = 2; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .is_ok()); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .is_ok() + ); // Inserting version 4 should not work, since the prior version is 2 policy.version = 4; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .unwrap_err() - .to_string() - .contains("policy version 4 is not the most recent")); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .unwrap_err() + .to_string() + .contains("policy version 4 is not the most recent") + ); // Inserting version 3 should work policy.version = 3; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .is_ok()); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .is_ok() + ); // Inserting version 4 should work policy.version = 4; policy.mode = ClickhouseMode::Both { target_servers: 3, target_keepers: 5 }; - assert!(datastore - .clickhouse_policy_insert_latest_version(opctx, &policy) - .await - .is_ok()); + assert!( + datastore + .clickhouse_policy_insert_latest_version(opctx, &policy) + .await + .is_ok() + ); let history = datastore .clickhouse_policy_list(opctx, &DataPageParams::max_page()) diff --git a/nexus/db-queries/src/db/datastore/cockroachdb_node_id.rs b/nexus/db-queries/src/db/datastore/cockroachdb_node_id.rs index 4de50a67110..86937a6e14b 100644 --- a/nexus/db-queries/src/db/datastore/cockroachdb_node_id.rs +++ b/nexus/db-queries/src/db/datastore/cockroachdb_node_id.rs @@ -6,16 +6,16 @@ use super::DataStore; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::ExpressionMethods; use diesel::OptionalExtension; use diesel::QueryDsl; use nexus_auth::authz; use nexus_auth::context::OpContext; -use nexus_db_model::to_db_typed_uuid; use nexus_db_model::CockroachZoneIdToNodeId; +use nexus_db_model::to_db_typed_uuid; use omicron_common::api::external::Error; use omicron_common::api::external::LookupResult; use omicron_uuid_kinds::OmicronZoneUuid; diff --git a/nexus/db-queries/src/db/datastore/cockroachdb_settings.rs b/nexus/db-queries/src/db/datastore/cockroachdb_settings.rs index e979b68a19c..798ba015291 100644 --- a/nexus/db-queries/src/db/datastore/cockroachdb_settings.rs +++ b/nexus/db-queries/src/db/datastore/cockroachdb_settings.rs @@ -7,8 +7,8 @@ use super::DataStore; use crate::context::OpContext; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::raw_query_builder::QueryBuilder; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::deserialize::Queryable; diff --git a/nexus/db-queries/src/db/datastore/crucible_dataset.rs b/nexus/db-queries/src/db/datastore/crucible_dataset.rs index d5aa967dc9e..187c445a50d 100644 --- a/nexus/db-queries/src/db/datastore/crucible_dataset.rs +++ b/nexus/db-queries/src/db/datastore/crucible_dataset.rs @@ -9,20 +9,20 @@ use super::SQL_BATCH_SIZE; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; +use crate::db::error::ErrorHandler; use crate::db::error::public_error_from_diesel; use crate::db::error::retryable; -use crate::db::error::ErrorHandler; use crate::db::identity::Asset; -use crate::db::model::to_db_typed_uuid; use crate::db::model::CrucibleDataset; use crate::db::model::PhysicalDisk; use crate::db::model::PhysicalDiskPolicy; use crate::db::model::Zpool; -use crate::db::pagination::paginated; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::Paginator; -use crate::db::TransactionError; +use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; diff --git a/nexus/db-queries/src/db/datastore/db_metadata.rs b/nexus/db-queries/src/db/datastore/db_metadata.rs index 985a0453c6a..5c53bc46a18 100644 --- a/nexus/db-queries/src/db/datastore/db_metadata.rs +++ b/nexus/db-queries/src/db/datastore/db_metadata.rs @@ -6,19 +6,19 @@ use super::DataStore; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use anyhow::{bail, ensure, Context}; +use crate::db::error::public_error_from_diesel; +use anyhow::{Context, bail, ensure}; use async_bb8_diesel::{AsyncRunQueryDsl, AsyncSimpleConnection}; use chrono::Utc; use diesel::prelude::*; use nexus_db_model::AllSchemaVersions; +use nexus_db_model::EARLIEST_SUPPORTED_VERSION; use nexus_db_model::SchemaUpgradeStep; use nexus_db_model::SchemaVersion; -use nexus_db_model::EARLIEST_SUPPORTED_VERSION; use omicron_common::api::external::Error; use omicron_common::api::external::SemverVersion; -use slog::{error, info, o, Logger}; +use slog::{Logger, error, info, o}; use std::ops::Bound; use std::str::FromStr; diff --git a/nexus/db-queries/src/db/datastore/deployment.rs b/nexus/db-queries/src/db/datastore/deployment.rs index cc3a92214d2..cd63a48c968 100644 --- a/nexus/db-queries/src/db/datastore/deployment.rs +++ b/nexus/db-queries/src/db/datastore/deployment.rs @@ -7,13 +7,13 @@ use crate::authz; use crate::authz::ApiResource; use crate::context::OpContext; use crate::db; +use crate::db::DbConnection; +use crate::db::TransactionError; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::pagination::paginated; +use crate::db::error::public_error_from_diesel; use crate::db::pagination::Paginator; -use crate::db::DbConnection; -use crate::db::TransactionError; +use crate::db::pagination::paginated; use crate::transaction_retry::OptionalError; use anyhow::Context; use async_bb8_diesel::AsyncRunQueryDsl; @@ -22,6 +22,13 @@ use chrono::Utc; use clickhouse_admin_types::{KeeperId, ServerId}; use core::future::Future; use core::pin::Pin; +use diesel::Column; +use diesel::ExpressionMethods; +use diesel::Insertable; +use diesel::IntoSql; +use diesel::OptionalExtension; +use diesel::QueryDsl; +use diesel::RunQueryDsl; use diesel::expression::SelectableHelper; use diesel::pg::Pg; use diesel::query_builder::AstPass; @@ -30,15 +37,7 @@ use diesel::query_builder::QueryId; use diesel::result::DatabaseErrorKind; use diesel::result::Error as DieselError; use diesel::sql_types; -use diesel::Column; -use diesel::ExpressionMethods; -use diesel::Insertable; -use diesel::IntoSql; -use diesel::OptionalExtension; -use diesel::QueryDsl; -use diesel::RunQueryDsl; use futures::FutureExt; -use nexus_db_model::to_db_typed_uuid; use nexus_db_model::Blueprint as DbBlueprint; use nexus_db_model::BpClickhouseClusterConfig; use nexus_db_model::BpClickhouseKeeperZoneIdToNodeId; @@ -52,7 +51,7 @@ use nexus_db_model::BpSledOmicronPhysicalDisks; use nexus_db_model::BpSledOmicronZones; use nexus_db_model::BpSledState; use nexus_db_model::BpTarget; -use nexus_types::deployment::id_map::IdMap; +use nexus_db_model::to_db_typed_uuid; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintDatasetsConfig; use nexus_types::deployment::BlueprintMetadata; @@ -61,6 +60,7 @@ use nexus_types::deployment::BlueprintTarget; use nexus_types::deployment::BlueprintZonesConfig; use nexus_types::deployment::ClickhouseClusterConfig; use nexus_types::deployment::CockroachDbPreserveDowngrade; +use nexus_types::deployment::id_map::IdMap; use nexus_types::external_api::views::SledState; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::Error; @@ -1805,11 +1805,9 @@ const NO_SUCH_BLUEPRINT_SENTINEL: &str = "no-such-blueprint"; const PARENT_NOT_TARGET_SENTINEL: &str = "parent-not-target"; // Error messages generated from the above sentinel values. -const NO_SUCH_BLUEPRINT_ERROR_MESSAGE: &str = - "could not parse \"no-such-blueprint\" as type uuid: \ +const NO_SUCH_BLUEPRINT_ERROR_MESSAGE: &str = "could not parse \"no-such-blueprint\" as type uuid: \ uuid: incorrect UUID length: no-such-blueprint"; -const PARENT_NOT_TARGET_ERROR_MESSAGE: &str = - "could not parse \"parent-not-target\" as type uuid: \ +const PARENT_NOT_TARGET_ERROR_MESSAGE: &str = "could not parse \"parent-not-target\" as type uuid: \ uuid: incorrect UUID length: parent-not-target"; impl InsertTargetQuery { @@ -2000,14 +1998,13 @@ mod tests { use crate::db::pub_test_utils::TestDatabase; use crate::db::raw_query_builder::QueryBuilder; - use nexus_inventory::now_db_precision; use nexus_inventory::CollectionBuilder; + use nexus_inventory::now_db_precision; use nexus_reconfigurator_planning::blueprint_builder::BlueprintBuilder; use nexus_reconfigurator_planning::blueprint_builder::Ensure; use nexus_reconfigurator_planning::blueprint_builder::EnsureMultiple; - use nexus_reconfigurator_planning::example::example; use nexus_reconfigurator_planning::example::ExampleSystemBuilder; - use nexus_types::deployment::blueprint_zone_type; + use nexus_reconfigurator_planning::example::example; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; @@ -2019,6 +2016,7 @@ mod tests { use nexus_types::deployment::SledDisk; use nexus_types::deployment::SledFilter; use nexus_types::deployment::SledResources; + use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::views::PhysicalDiskPolicy; use nexus_types::external_api::views::PhysicalDiskState; use nexus_types::external_api::views::SledPolicy; @@ -2032,8 +2030,8 @@ mod tests { use omicron_common::api::internal::shared::NetworkInterfaceKind; use omicron_common::disk::DiskIdentity; use omicron_test_utils::dev; - use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; + use omicron_test_utils::dev::poll::wait_for_condition; use omicron_uuid_kinds::ExternalIpUuid; use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::PhysicalDiskUuid; @@ -2041,8 +2039,8 @@ mod tests { use omicron_uuid_kinds::ZpoolUuid; use oxnet::IpNet; use pretty_assertions::assert_eq; - use rand::thread_rng; use rand::Rng; + use rand::thread_rng; use slog::Logger; use std::mem; use std::net::IpAddr; @@ -2050,10 +2048,10 @@ mod tests { use std::net::Ipv6Addr; use std::net::SocketAddrV6; use std::str::FromStr; - use std::sync::atomic::AtomicBool; - use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::LazyLock; + use std::sync::atomic::AtomicBool; + use std::sync::atomic::Ordering; use std::time::Duration; static EMPTY_PLANNING_INPUT: LazyLock = @@ -2737,9 +2735,9 @@ mod tests { .blueprint_target_set_current_enabled(&opctx, bp2_target) .await .unwrap_err(); - assert!(err - .to_string() - .contains("is not the current target blueprint")); + assert!( + err.to_string().contains("is not the current target blueprint") + ); // ...but we can make it the target via `blueprint_target_set_current`. datastore @@ -2756,9 +2754,9 @@ mod tests { .blueprint_target_set_current_enabled(&opctx, bp1_target) .await .unwrap_err(); - assert!(err - .to_string() - .contains("is not the current target blueprint")); + assert!( + err.to_string().contains("is not the current target blueprint") + ); // We can toggle bp2_target.enabled an arbitrary number of times. for _ in 0..10 { diff --git a/nexus/db-queries/src/db/datastore/deployment/external_networking.rs b/nexus/db-queries/src/db/datastore/deployment/external_networking.rs index 9dc1ecb1f50..8158ecdf32d 100644 --- a/nexus/db-queries/src/db/datastore/deployment/external_networking.rs +++ b/nexus/db-queries/src/db/datastore/deployment/external_networking.rs @@ -6,11 +6,11 @@ //! required for blueprint realization use crate::context::OpContext; +use crate::db::DataStore; +use crate::db::DbConnection; use crate::db::fixed_data::vpc_subnet::DNS_VPC_SUBNET; use crate::db::fixed_data::vpc_subnet::NEXUS_VPC_SUBNET; use crate::db::fixed_data::vpc_subnet::NTP_VPC_SUBNET; -use crate::db::DataStore; -use crate::db::DbConnection; use nexus_db_model::IncompleteNetworkInterface; use nexus_db_model::IpPool; use nexus_sled_agent_shared::inventory::ZoneKind; @@ -22,11 +22,11 @@ use omicron_common::api::internal::shared::NetworkInterface; use omicron_common::api::internal::shared::NetworkInterfaceKind; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::OmicronZoneUuid; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; impl DataStore { @@ -417,18 +417,18 @@ mod tests { use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; use nexus_db_model::SqlU16; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; - use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::OmicronZoneExternalFloatingAddr; use nexus_types::deployment::OmicronZoneExternalFloatingIp; use nexus_types::deployment::OmicronZoneExternalSnatIp; + use nexus_types::deployment::blueprint_zone_type; use nexus_types::identity::Resource; use nexus_types::inventory::SourceNatConfig; + use omicron_common::address::DNS_OPTE_IPV4_SUBNET; use omicron_common::address::IpRange; use omicron_common::address::IpRangeIter; - use omicron_common::address::DNS_OPTE_IPV4_SUBNET; use omicron_common::address::NEXUS_OPTE_IPV4_SUBNET; use omicron_common::address::NTP_OPTE_IPV4_SUBNET; use omicron_common::address::NUM_SOURCE_NAT_PORTS; @@ -886,9 +886,9 @@ mod tests { assert!(nics.iter().any(|(id, _)| *id == self.ntp_nic.id)); // All rows should indicate deleted records. - assert!(nics - .iter() - .all(|(_, time_deleted)| time_deleted.is_some())); + assert!( + nics.iter().all(|(_, time_deleted)| time_deleted.is_some()) + ); } } diff --git a/nexus/db-queries/src/db/datastore/device_auth.rs b/nexus/db-queries/src/db/datastore/device_auth.rs index 8d8e09744c3..467ecdaa6ae 100644 --- a/nexus/db-queries/src/db/datastore/device_auth.rs +++ b/nexus/db-queries/src/db/datastore/device_auth.rs @@ -8,8 +8,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::DeviceAccessToken; use crate::db::model::DeviceAuthRequest; use async_bb8_diesel::AsyncRunQueryDsl; diff --git a/nexus/db-queries/src/db/datastore/disk.rs b/nexus/db-queries/src/db/datastore/disk.rs index d3678daa531..af9fd8c270c 100644 --- a/nexus/db-queries/src/db/datastore/disk.rs +++ b/nexus/db-queries/src/db/datastore/disk.rs @@ -15,11 +15,10 @@ use crate::db::collection_detach::DatastoreDetachTarget; use crate::db::collection_detach::DetachError; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Resource; use crate::db::lookup::LookupPath; -use crate::db::model::to_db_typed_uuid; use crate::db::model::Disk; use crate::db::model::DiskRuntimeState; use crate::db::model::DiskUpdate; @@ -28,6 +27,7 @@ use crate::db::model::Name; use crate::db::model::Project; use crate::db::model::VirtualProvisioningResource; use crate::db::model::Volume; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::paginated; use crate::db::queries::disk::DiskSetClauseForAttach; use crate::db::update_and_check::UpdateAndCheck; @@ -37,7 +37,6 @@ use chrono::DateTime; use chrono::Utc; use diesel::prelude::*; use omicron_common::api; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; @@ -45,6 +44,7 @@ use omicron_common::api::external::LookupResult; use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::bail_unless; use omicron_uuid_kinds::VolumeUuid; use ref_cast::RefCast; diff --git a/nexus/db-queries/src/db/datastore/dns.rs b/nexus/db-queries/src/db/datastore/dns.rs index 60f677cf358..247de5a4be3 100644 --- a/nexus/db-queries/src/db/datastore/dns.rs +++ b/nexus/db-queries/src/db/datastore/dns.rs @@ -6,24 +6,24 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::DnsGroup; use crate::db::model::DnsName; use crate::db::model::DnsVersion; use crate::db::model::DnsZone; use crate::db::model::Generation; use crate::db::model::InitialDnsGroup; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::pool::DbConnection; -use crate::db::TransactionError; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_types::internal_api::params::DnsConfigParams; use nexus_types::internal_api::params::DnsConfigZone; use nexus_types::internal_api::params::DnsRecord; @@ -34,9 +34,9 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::bail_unless; use slog::debug; -use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; +use std::collections::hash_map::Entry; use std::num::NonZeroU32; use uuid::Uuid; @@ -745,10 +745,10 @@ impl DataStoreDnsTest for DataStore { #[cfg(test)] mod test { - use crate::db::datastore::DnsVersionUpdateBuilder; - use crate::db::pub_test_utils::TestDatabase; use crate::db::DataStore; use crate::db::TransactionError; + use crate::db::datastore::DnsVersionUpdateBuilder; + use crate::db::pub_test_utils::TestDatabase; use assert_matches::assert_matches; use async_bb8_diesel::AsyncConnection; use async_bb8_diesel::AsyncRunQueryDsl; @@ -1360,9 +1360,11 @@ mod test { ) .await .unwrap_err(); - assert!(error - .to_string() - .contains("duplicate key value violates unique constraint")); + assert!( + error + .to_string() + .contains("duplicate key value violates unique constraint") + ); } // There cannot be two DNS version records with the same group and @@ -1391,9 +1393,11 @@ mod test { ) .await .unwrap_err(); - assert!(error - .to_string() - .contains("duplicate key value violates unique constraint")); + assert!( + error + .to_string() + .contains("duplicate key value violates unique constraint") + ); } // There cannot be two DNS names in the same zone with the same name @@ -1425,9 +1429,11 @@ mod test { ) .await .unwrap_err(); - assert!(error - .to_string() - .contains("duplicate key value violates unique constraint")); + assert!( + error + .to_string() + .contains("duplicate key value violates unique constraint") + ); } db.terminate().await; @@ -1956,9 +1962,11 @@ mod test { .dns_update_from_version(&opctx, update2.clone(), gen1) .await .expect_err("update unexpectedly succeeded"); - assert!(error - .to_string() - .contains("expected current DNS version to be 1, found 2")); + assert!( + error + .to_string() + .contains("expected current DNS version to be 1, found 2") + ); // At this point, the database state should reflect the first update but // not the second. diff --git a/nexus/db-queries/src/db/datastore/external_ip.rs b/nexus/db-queries/src/db/datastore/external_ip.rs index 9447d552e4d..fce692ac5f0 100644 --- a/nexus/db-queries/src/db/datastore/external_ip.rs +++ b/nexus/db-queries/src/db/datastore/external_ip.rs @@ -14,10 +14,10 @@ use crate::db::collection_attach::AttachError; use crate::db::collection_attach::DatastoreAttachTarget; use crate::db::collection_detach::DatastoreDetachTarget; use crate::db::collection_detach::DetachError; -use crate::db::error::public_error_from_diesel; -use crate::db::error::retryable; use crate::db::error::ErrorHandler; use crate::db::error::TransactionError; +use crate::db::error::public_error_from_diesel; +use crate::db::error::retryable; use crate::db::lookup::LookupPath; use crate::db::model::ExternalIp; use crate::db::model::FloatingIp; @@ -25,11 +25,11 @@ use crate::db::model::IncompleteExternalIp; use crate::db::model::IpKind; use crate::db::model::IpPool; use crate::db::model::Name; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::pool::DbConnection; -use crate::db::queries::external_ip::NextExternalIp; use crate::db::queries::external_ip::MAX_EXTERNAL_IPS_PER_INSTANCE; +use crate::db::queries::external_ip::NextExternalIp; use crate::db::queries::external_ip::SAFE_TO_ATTACH_INSTANCE_STATES; use crate::db::queries::external_ip::SAFE_TO_ATTACH_INSTANCE_STATES_CREATING; use crate::db::update_and_check::UpdateAndCheck; @@ -43,7 +43,6 @@ use nexus_db_model::IpAttachState; use nexus_sled_agent_shared::inventory::ZoneKind; use nexus_types::deployment::OmicronZoneExternalIp; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; @@ -53,6 +52,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::InstanceUuid; use omicron_uuid_kinds::OmicronZoneUuid; @@ -925,9 +925,13 @@ impl DataStore { match result.status { // Verify this FIP is not attached to any instances/services. - UpdateStatus::NotUpdatedButExists if result.found.parent_id.is_some() => Err(Error::invalid_request( - "Floating IP cannot be deleted while attached to an instance", - )), + UpdateStatus::NotUpdatedButExists + if result.found.parent_id.is_some() => + { + Err(Error::invalid_request( + "Floating IP cannot be deleted while attached to an instance", + )) + } // Only remaining cause of `NotUpdated` is earlier soft-deletion. // Return success in this case to maintain idempotency. UpdateStatus::Updated | UpdateStatus::NotUpdatedButExists => Ok(()), @@ -1053,10 +1057,12 @@ impl DataStore { let now = Utc::now(); let conn = self.pool_connection_authorized(opctx).await?; match (ip_kind, expected_state, target_state) { - (IpKind::SNat, _, _) => return Err(Error::internal_error( - "SNAT should not be removed via `external_ip_complete_op`, \ + (IpKind::SNat, _, _) => { + return Err(Error::internal_error( + "SNAT should not be removed via `external_ip_complete_op`, \ use `deallocate_external_ip`", - )), + )); + } (IpKind::Ephemeral, _, IpAttachState::Detached) => { part_out @@ -1110,7 +1116,7 @@ impl DataStore { )) } UpdateStatus::NotUpdatedButExists => Ok(0), - }) + }); } // Unwind from failed detach. diff --git a/nexus/db-queries/src/db/datastore/identity_provider.rs b/nexus/db-queries/src/db/datastore/identity_provider.rs index e7ab9bde16b..d5e99db4829 100644 --- a/nexus/db-queries/src/db/datastore/identity_provider.rs +++ b/nexus/db-queries/src/db/datastore/identity_provider.rs @@ -8,8 +8,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Resource; use crate::db::lookup::LookupPath; use crate::db::model; @@ -19,11 +19,11 @@ use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; use nexus_auth::authn::silos::IdentityProviderType; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::ResourceType; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; impl DataStore { diff --git a/nexus/db-queries/src/db/datastore/image.rs b/nexus/db-queries/src/db/datastore/image.rs index 759b5230100..4557d45dcfc 100644 --- a/nexus/db-queries/src/db/datastore/image.rs +++ b/nexus/db-queries/src/db/datastore/image.rs @@ -4,8 +4,8 @@ use crate::context::OpContext; use crate::db; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::Image; use crate::db::model::Project; use crate::db::model::ProjectImage; @@ -17,12 +17,12 @@ use chrono::Utc; use diesel::prelude::*; use nexus_db_model::Name; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/datastore/instance.rs b/nexus/db-queries/src/db/datastore/instance.rs index b2358c0d291..9accb1fc506 100644 --- a/nexus/db-queries/src/db/datastore/instance.rs +++ b/nexus/db-queries/src/db/datastore/instance.rs @@ -14,8 +14,8 @@ use crate::db::collection_detach_many::DetachManyError; use crate::db::collection_detach_many::DetachManyFromCollectionStatement; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Resource; use crate::db::lookup::LookupPath; use crate::db::model::ByteCount; @@ -48,7 +48,6 @@ use nexus_db_model::Disk; use nexus_types::internal_api::background::ReincarnationReason; use omicron_common::api; use omicron_common::api::external; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; @@ -59,6 +58,7 @@ use omicron_common::api::external::LookupType; use omicron_common::api::external::MessagePair; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::bail_unless; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::InstanceUuid; @@ -2020,8 +2020,7 @@ impl DataStore { // did not match. UpdateAndQueryResult { ref found, .. } => match found.updater_id { Some(actual_id) => { - const MSG: &'static str = - "cannot commit instance updates: the instance is \ + const MSG: &'static str = "cannot commit instance updates: the instance is \ locked by another saga!"; error!( &opctx.log, @@ -2035,8 +2034,7 @@ impl DataStore { Err(Error::internal_error(MSG)) } None => { - const MSG: &'static str = - "cannot commit instance updates: the instance is \ + const MSG: &'static str = "cannot commit instance updates: the instance is \ not locked"; error!( &opctx.log, @@ -3144,7 +3142,8 @@ mod tests { ); // Now, mark the previous migration as Failed. - let updated = dbg!(datastore + let updated = + dbg!(datastore .migration_mark_failed(&opctx, migration.id) .await .expect( diff --git a/nexus/db-queries/src/db/datastore/inventory.rs b/nexus/db-queries/src/db/datastore/inventory.rs index 08c64a32543..fa516fdae5b 100644 --- a/nexus/db-queries/src/db/datastore/inventory.rs +++ b/nexus/db-queries/src/db/datastore/inventory.rs @@ -6,18 +6,16 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::error::ErrorHandler; use crate::db::error::public_error_from_diesel; use crate::db::error::public_error_from_diesel_lookup; -use crate::db::error::ErrorHandler; -use crate::db::pagination::{paginated, paginated_multicolumn, Paginator}; +use crate::db::pagination::{Paginator, paginated, paginated_multicolumn}; use crate::db::queries::ALLOW_FULL_TABLE_SCAN_SQL; use anyhow::Context; use async_bb8_diesel::AsyncConnection; use async_bb8_diesel::AsyncRunQueryDsl; use async_bb8_diesel::AsyncSimpleConnection; use clickhouse_admin_types::ClickhouseKeeperClusterMembership; -use diesel::expression::SelectableHelper; -use diesel::sql_types::Nullable; use diesel::BoolExpressionMethods; use diesel::ExpressionMethods; use diesel::IntoSql; @@ -26,9 +24,10 @@ use diesel::NullableExpressionMethods; use diesel::OptionalExtension; use diesel::QueryDsl; use diesel::Table; -use futures::future::BoxFuture; +use diesel::expression::SelectableHelper; +use diesel::sql_types::Nullable; use futures::FutureExt; -use nexus_db_model::to_db_typed_uuid; +use futures::future::BoxFuture; use nexus_db_model::CabooseWhichEnum; use nexus_db_model::HwBaseboardId; use nexus_db_model::HwPowerState; @@ -61,6 +60,7 @@ use nexus_db_model::SqlU16; use nexus_db_model::SqlU32; use nexus_db_model::SwCaboose; use nexus_db_model::SwRotPage; +use nexus_db_model::to_db_typed_uuid; use nexus_sled_agent_shared::inventory::OmicronZonesConfig; use nexus_types::inventory::BaseboardId; use nexus_types::inventory::Collection; @@ -2445,20 +2445,20 @@ impl DataStoreInventoryTest for DataStore { #[cfg(test)] mod test { - use crate::db::datastore::inventory::DataStoreInventoryTest; + use crate::db::DataStore; use crate::db::datastore::DataStoreConnection; + use crate::db::datastore::inventory::DataStoreInventoryTest; use crate::db::pub_test_utils::TestDatabase; use crate::db::raw_query_builder::{QueryBuilder, TrustedStr}; use crate::db::schema; - use crate::db::DataStore; - use anyhow::{bail, Context}; + use anyhow::{Context, bail}; use async_bb8_diesel::AsyncConnection; use async_bb8_diesel::AsyncRunQueryDsl; use async_bb8_diesel::AsyncSimpleConnection; use diesel::QueryDsl; use gateway_client::types::SpType; - use nexus_inventory::examples::representative; use nexus_inventory::examples::Representative; + use nexus_inventory::examples::representative; use nexus_test_utils::db::ALLOW_FULL_TABLE_SCAN_SQL; use nexus_types::inventory::BaseboardId; use nexus_types::inventory::CabooseWhich; @@ -2720,8 +2720,10 @@ mod test { .inventory_insert_collection(&opctx, &collection5) .await .expect_err("unexpectedly succeeded in inserting collection"); - assert!(format!("{:#}", error) - .contains("duplicate key value violates unique constraint")); + assert!( + format!("{:#}", error) + .contains("duplicate key value violates unique constraint") + ); // Now that we've inserted a bunch of collections, we can test pruning. // diff --git a/nexus/db-queries/src/db/datastore/ip_pool.rs b/nexus/db-queries/src/db/datastore/ip_pool.rs index 2409839eb40..480dc3fb532 100644 --- a/nexus/db-queries/src/db/datastore/ip_pool.rs +++ b/nexus/db-queries/src/db/datastore/ip_pool.rs @@ -9,12 +9,13 @@ use super::SQL_BATCH_SIZE; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; use crate::db::datastore::SERVICE_IP_POOL_NAME; +use crate::db::error::ErrorHandler; use crate::db::error::public_error_from_diesel; use crate::db::error::public_error_from_diesel_lookup; -use crate::db::error::ErrorHandler; use crate::db::identity::Resource; use crate::db::lookup::LookupPath; use crate::db::model::ExternalIp; @@ -25,11 +26,10 @@ use crate::db::model::IpPoolResource; use crate::db::model::IpPoolResourceType; use crate::db::model::IpPoolUpdate; use crate::db::model::Name; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::pool::DbConnection; use crate::db::queries::ip_pool::FilterOverlappingIpRanges; -use crate::db::TransactionError; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; @@ -41,7 +41,6 @@ use nexus_db_model::InternetGatewayIpPool; use nexus_db_model::Project; use nexus_db_model::Vpc; use nexus_types::external_api::shared::IpRange; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; @@ -53,6 +52,7 @@ use omicron_common::api::external::LookupResult; use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/datastore/ipv4_nat_entry.rs b/nexus/db-queries/src/db/datastore/ipv4_nat_entry.rs index 2415c2d654d..50f618e222d 100644 --- a/nexus/db-queries/src/db/datastore/ipv4_nat_entry.rs +++ b/nexus/db-queries/src/db/datastore/ipv4_nat_entry.rs @@ -1,8 +1,8 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::{Ipv4NatEntry, Ipv4NatValues}; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::{DateTime, Utc}; @@ -886,9 +886,11 @@ mod test { while !changes.is_empty() { // check ordering - assert!(changes - .windows(2) - .all(|entries| entries[0].gen < entries[1].gen)); + assert!( + changes + .windows(2) + .all(|entries| entries[0].gen < entries[1].gen) + ); // check deleted status and version numbers changes.iter().for_each(|change| match change.deleted { diff --git a/nexus/db-queries/src/db/datastore/lldp.rs b/nexus/db-queries/src/db/datastore/lldp.rs index 40f55b3f846..7ccc04c418f 100644 --- a/nexus/db-queries/src/db/datastore/lldp.rs +++ b/nexus/db-queries/src/db/datastore/lldp.rs @@ -7,8 +7,8 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::LldpLinkConfig; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; diff --git a/nexus/db-queries/src/db/datastore/migration.rs b/nexus/db-queries/src/db/datastore/migration.rs index 320146ae785..be20717bfe3 100644 --- a/nexus/db-queries/src/db/datastore/migration.rs +++ b/nexus/db-queries/src/db/datastore/migration.rs @@ -7,8 +7,8 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::Generation; use crate::db::model::Migration; use crate::db::model::MigrationState; diff --git a/nexus/db-queries/src/db/datastore/mod.rs b/nexus/db-queries/src/db/datastore/mod.rs index b2d9f8f2471..a13b5e26655 100644 --- a/nexus/db-queries/src/db/datastore/mod.rs +++ b/nexus/db-queries/src/db/datastore/mod.rs @@ -18,16 +18,16 @@ // vs. there were no disks in it. This seems likely to be a fair bit more // complicated to do safely and generally compared to what we have now. -use super::pool::DbConnection; use super::Pool; +use super::pool::DbConnection; use crate::authz; use crate::context::OpContext; use crate::db::{ self, - error::{public_error_from_diesel, ErrorHandler}, + error::{ErrorHandler, public_error_from_diesel}, }; use ::oximeter::types::ProducerRegistry; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::pg::Pg; use diesel::prelude::*; @@ -40,7 +40,7 @@ use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; use omicron_common::api::external::SemverVersion; use omicron_common::backoff::{ - retry_notify, retry_policy_internal_service, BackoffError, + BackoffError, retry_notify, retry_policy_internal_service, }; use omicron_uuid_kinds::{GenericUuid, SledUuid}; use slog::Logger; @@ -464,12 +464,12 @@ mod test { use crate::db::pub_test_utils::TestDatabase; use crate::db::queries::vpc_subnet::InsertVpcSubnetQuery; use chrono::{Duration, Utc}; - use futures::stream; use futures::StreamExt; + use futures::stream; use nexus_config::RegionAllocationStrategy; use nexus_db_fixed_data::silo::DEFAULT_SILO; use nexus_db_model::IpAttachState; - use nexus_db_model::{to_db_typed_uuid, Generation}; + use nexus_db_model::{Generation, to_db_typed_uuid}; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintTarget; use nexus_types::external_api::params; @@ -1643,16 +1643,18 @@ mod test { let params = create_test_disk_create_params("disk1", alloc_size); let volume1_id = VolumeUuid::new_v4(); - assert!(datastore - .disk_region_allocate( - &opctx, - volume1_id, - ¶ms.disk_source, - params.size, - &RegionAllocationStrategy::Random { seed: Some(0) }, - ) - .await - .is_err()); + assert!( + datastore + .disk_region_allocate( + &opctx, + volume1_id, + ¶ms.disk_source, + params.size, + &RegionAllocationStrategy::Random { seed: Some(0) }, + ) + .await + .is_err() + ); db.terminate().await; logctx.cleanup_successful(); @@ -2030,10 +2032,12 @@ mod test { ); // Deleting a non-existing record fails - assert!(datastore - .deallocate_external_ip(&opctx, Uuid::nil()) - .await - .is_err()); + assert!( + datastore + .deallocate_external_ip(&opctx, Uuid::nil()) + .await + .is_err() + ); db.terminate().await; logctx.cleanup_successful(); diff --git a/nexus/db-queries/src/db/datastore/network_interface.rs b/nexus/db-queries/src/db/datastore/network_interface.rs index 24f10afb406..18181c2395e 100644 --- a/nexus/db-queries/src/db/datastore/network_interface.rs +++ b/nexus/db-queries/src/db/datastore/network_interface.rs @@ -12,8 +12,8 @@ use crate::db; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; use crate::db::cte_utils::BoxedQuery; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::IncompleteNetworkInterface; use crate::db::model::Instance; use crate::db::model::InstanceNetworkInterface; @@ -22,8 +22,8 @@ use crate::db::model::NetworkInterface; use crate::db::model::NetworkInterfaceKind; use crate::db::model::NetworkInterfaceUpdate; use crate::db::model::VpcSubnet; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::pool::DbConnection; use crate::db::queries::network_interface; use crate::transaction_retry::OptionalError; @@ -33,7 +33,6 @@ use diesel::prelude::*; use diesel::result::Error as DieselError; use nexus_db_model::ServiceNetworkInterface; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -42,6 +41,7 @@ use omicron_common::api::external::LookupResult; use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/datastore/oximeter.rs b/nexus/db-queries/src/db/datastore/oximeter.rs index 2654e8f2d5d..1d45182895b 100644 --- a/nexus/db-queries/src/db/datastore/oximeter.rs +++ b/nexus/db-queries/src/db/datastore/oximeter.rs @@ -8,13 +8,13 @@ use super::DataStore; use super::SQL_BATCH_SIZE; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Asset; use crate::db::model::OximeterInfo; use crate::db::model::ProducerEndpoint; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::queries; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::DateTime; diff --git a/nexus/db-queries/src/db/datastore/physical_disk.rs b/nexus/db-queries/src/db/datastore/physical_disk.rs index 1d1c6286a6d..3f7382bb11d 100644 --- a/nexus/db-queries/src/db/datastore/physical_disk.rs +++ b/nexus/db-queries/src/db/datastore/physical_disk.rs @@ -8,11 +8,11 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_typed_uuid; +use crate::db::error::public_error_from_diesel; use crate::db::model::ApplySledFilterExt; use crate::db::model::InvPhysicalDisk; use crate::db::model::PhysicalDisk; @@ -21,8 +21,8 @@ use crate::db::model::PhysicalDiskPolicy; use crate::db::model::PhysicalDiskState; use crate::db::model::Sled; use crate::db::model::Zpool; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::paginated; -use crate::db::TransactionError; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; diff --git a/nexus/db-queries/src/db/datastore/probe.rs b/nexus/db-queries/src/db/datastore/probe.rs index 434bf25760f..6b305de613b 100644 --- a/nexus/db-queries/src/db/datastore/probe.rs +++ b/nexus/db-queries/src/db/datastore/probe.rs @@ -2,8 +2,8 @@ use crate::authz; use crate::context::OpContext; use crate::db; use crate::db::datastore::DataStoreConnection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::lookup::LookupPath; use crate::db::model::Name; use crate::db::pagination::paginated; @@ -15,7 +15,6 @@ use nexus_db_model::Probe; use nexus_db_model::VpcSubnet; use nexus_types::external_api::shared::ProbeInfo; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; @@ -25,6 +24,7 @@ use omicron_common::api::external::LookupResult; use omicron_common::api::external::LookupType; use omicron_common::api::external::NameOrId; use omicron_common::api::external::ResourceType; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::internal::shared::NetworkInterface; use ref_cast::RefCast; use schemars::JsonSchema; diff --git a/nexus/db-queries/src/db/datastore/project.rs b/nexus/db-queries/src/db/datastore/project.rs index 58b7b315c1c..8391c2e5aba 100644 --- a/nexus/db-queries/src/db/datastore/project.rs +++ b/nexus/db-queries/src/db/datastore/project.rs @@ -11,8 +11,8 @@ use crate::context::OpContext; use crate::db; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Resource; use crate::db::model::CollectionTypeProvisioned; use crate::db::model::Name; @@ -27,7 +27,6 @@ use chrono::Utc; use diesel::prelude::*; use nexus_db_fixed_data::project::SERVICES_PROJECT; use nexus_types::silo::INTERNAL_SILO_ID; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -36,6 +35,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; // Generates internal functions used for validation during project deletion. diff --git a/nexus/db-queries/src/db/datastore/quota.rs b/nexus/db-queries/src/db/datastore/quota.rs index 2066781e6b1..8f5bc95fc1c 100644 --- a/nexus/db-queries/src/db/datastore/quota.rs +++ b/nexus/db-queries/src/db/datastore/quota.rs @@ -2,8 +2,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::pagination::paginated; use crate::db::pool::DbConnection; use async_bb8_diesel::AsyncRunQueryDsl; diff --git a/nexus/db-queries/src/db/datastore/rack.rs b/nexus/db-queries/src/db/datastore/rack.rs index d2dd84063ae..140e68e8fdd 100644 --- a/nexus/db-queries/src/db/datastore/rack.rs +++ b/nexus/db-queries/src/db/datastore/rack.rs @@ -4,18 +4,19 @@ //! [`DataStore`] methods on [`Rack`]s. -use super::dns::DnsVersionUpdateBuilder; use super::DataStore; use super::SERVICE_IP_POOL_NAME; +use super::dns::DnsVersionUpdateBuilder; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; -use crate::db::error::retryable; use crate::db::error::ErrorHandler; use crate::db::error::MaybeRetryable::*; +use crate::db::error::public_error_from_diesel; +use crate::db::error::retryable; use crate::db::identity::Asset; use crate::db::lookup::LookupPath; use crate::db::model::CrucibleDataset; @@ -25,7 +26,6 @@ use crate::db::model::Rack; use crate::db::model::Zpool; use crate::db::pagination::paginated; use crate::db::pool::DbConnection; -use crate::db::TransactionError; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; @@ -42,13 +42,13 @@ use nexus_db_model::SiloUser; use nexus_db_model::SiloUserPasswordHash; use nexus_db_model::SledState; use nexus_db_model::SledUnderlaySubnetAllocation; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintTarget; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::OmicronZoneExternalIp; +use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::params as external_params; use nexus_types::external_api::shared; use nexus_types::external_api::shared::IdentityType; @@ -118,11 +118,7 @@ enum RackInitError { // can also label errors as retryable. impl From for RackInitError { fn from(e: DieselError) -> Self { - if retryable(&e) { - Self::Retryable(e) - } else { - Self::Database(e) - } + if retryable(&e) { Self::Retryable(e) } else { Self::Database(e) } } } @@ -994,10 +990,10 @@ impl DataStore { #[cfg(test)] mod test { use super::*; + use crate::db::datastore::Discoverability; use crate::db::datastore::test::{ sled_baseboard_for_test, sled_system_hardware_for_test, }; - use crate::db::datastore::Discoverability; use crate::db::model::ExternalIp; use crate::db::model::IpKind; use crate::db::model::IpPoolRange; @@ -1323,11 +1319,13 @@ mod test { let sled2 = create_test_sled(&datastore, Uuid::new_v4()).await; let sled3 = create_test_sled(&datastore, Uuid::new_v4()).await; - let service_ip_pool_ranges = vec![IpRange::try_from(( - Ipv4Addr::new(1, 2, 3, 4), - Ipv4Addr::new(1, 2, 3, 6), - )) - .unwrap()]; + let service_ip_pool_ranges = vec![ + IpRange::try_from(( + Ipv4Addr::new(1, 2, 3, 4), + Ipv4Addr::new(1, 2, 3, 6), + )) + .unwrap(), + ]; let mut system = SystemDescription::new(); system @@ -1597,9 +1595,11 @@ mod test { .iter() .find(|e| e.parent_id == Some(ntp2_id.into_untyped_uuid())) .unwrap(); - assert!(!observed_external_ips - .iter() - .any(|e| e.parent_id == Some(ntp3_id.into_untyped_uuid()))); + assert!( + !observed_external_ips + .iter() + .any(|e| e.parent_id == Some(ntp3_id.into_untyped_uuid())) + ); assert!(dns_external_ip.is_service); assert_eq!(dns_external_ip.kind, IpKind::Floating); @@ -1675,9 +1675,10 @@ mod test { // Ask for two Nexus services, with different external IPs. let nexus_ip_start = Ipv4Addr::new(1, 2, 3, 4); let nexus_ip_end = Ipv4Addr::new(1, 2, 3, 5); - let service_ip_pool_ranges = - vec![IpRange::try_from((nexus_ip_start, nexus_ip_end)) - .expect("Cannot create IP Range")]; + let service_ip_pool_ranges = vec![ + IpRange::try_from((nexus_ip_start, nexus_ip_end)) + .expect("Cannot create IP Range"), + ]; let mut system = SystemDescription::new(); system diff --git a/nexus/db-queries/src/db/datastore/region.rs b/nexus/db-queries/src/db/datastore/region.rs index bacba45a683..2e27ed6a17d 100644 --- a/nexus/db-queries/src/db/datastore/region.rs +++ b/nexus/db-queries/src/db/datastore/region.rs @@ -10,16 +10,16 @@ use crate::context::OpContext; use crate::db; use crate::db::datastore::REGION_REDUNDANCY_THRESHOLD; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::lookup::LookupPath; -use crate::db::model::to_db_typed_uuid; use crate::db::model::CrucibleDataset; use crate::db::model::PhysicalDiskPolicy; use crate::db::model::Region; use crate::db::model::SqlU16; -use crate::db::pagination::paginated; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::queries::region_allocation::RegionParameters; use crate::db::update_and_check::UpdateAndCheck; use crate::db::update_and_check::UpdateStatus; diff --git a/nexus/db-queries/src/db/datastore/region_replacement.rs b/nexus/db-queries/src/db/datastore/region_replacement.rs index 72afbac3198..87bcb92912c 100644 --- a/nexus/db-queries/src/db/datastore/region_replacement.rs +++ b/nexus/db-queries/src/db/datastore/region_replacement.rs @@ -7,21 +7,21 @@ use super::DataStore; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_typed_uuid; +use crate::db::error::public_error_from_diesel; use crate::db::model::Region; use crate::db::model::RegionReplacement; use crate::db::model::RegionReplacementState; use crate::db::model::RegionReplacementStep; use crate::db::model::UpstairsRepairNotification; use crate::db::model::UpstairsRepairNotificationType; -use crate::db::pagination::paginated; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::update_and_check::UpdateAndCheck; use crate::db::update_and_check::UpdateStatus; -use crate::db::TransactionError; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; @@ -464,10 +464,10 @@ impl DataStore { } else { Err(Error::conflict(format!( "region replacement {} set to {:?} (operating saga id {:?})", - region_replacement_id, - record.replacement_state, - record.operating_saga_id, - ))) + region_replacement_id, + record.replacement_state, + record.operating_saga_id, + ))) } } }, @@ -512,10 +512,10 @@ impl DataStore { } else { Err(Error::conflict(format!( "region replacement {} set to {:?} (operating saga id {:?})", - region_replacement_id, - record.replacement_state, - record.operating_saga_id, - ))) + region_replacement_id, + record.replacement_state, + record.operating_saga_id, + ))) } } }, diff --git a/nexus/db-queries/src/db/datastore/region_snapshot.rs b/nexus/db-queries/src/db/datastore/region_snapshot.rs index 36576422d45..86a1e8f6f07 100644 --- a/nexus/db-queries/src/db/datastore/region_snapshot.rs +++ b/nexus/db-queries/src/db/datastore/region_snapshot.rs @@ -7,14 +7,14 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_typed_uuid; +use crate::db::error::public_error_from_diesel; use crate::db::model::PhysicalDiskPolicy; use crate::db::model::RegionSnapshot; +use crate::db::model::to_db_typed_uuid; use async_bb8_diesel::AsyncRunQueryDsl; -use diesel::prelude::*; use diesel::OptionalExtension; +use diesel::prelude::*; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::LookupResult; diff --git a/nexus/db-queries/src/db/datastore/region_snapshot_replacement.rs b/nexus/db-queries/src/db/datastore/region_snapshot_replacement.rs index a2139b24d14..ade68202041 100644 --- a/nexus/db-queries/src/db/datastore/region_snapshot_replacement.rs +++ b/nexus/db-queries/src/db/datastore/region_snapshot_replacement.rs @@ -8,10 +8,10 @@ use super::DataStore; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_typed_uuid; +use crate::db::error::public_error_from_diesel; use crate::db::model::ReadOnlyTargetReplacement; use crate::db::model::ReadOnlyTargetReplacementType; use crate::db::model::RegionSnapshot; @@ -19,11 +19,11 @@ use crate::db::model::RegionSnapshotReplacement; use crate::db::model::RegionSnapshotReplacementState; use crate::db::model::RegionSnapshotReplacementStep; use crate::db::model::RegionSnapshotReplacementStepState; -use crate::db::pagination::paginated; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::update_and_check::UpdateAndCheck; use crate::db::update_and_check::UpdateStatus; -use crate::db::TransactionError; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; @@ -84,7 +84,7 @@ impl DataStore { Some(db_snapshot) => db_snapshot, None => { return Err(Error::internal_error( - "cannot perform region snapshot replacement without snapshot volume" + "cannot perform region snapshot replacement without snapshot volume", )); } }; @@ -1717,11 +1717,13 @@ mod test { 0, ); - assert!(datastore - .get_requested_region_snapshot_replacement_steps(&opctx) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .get_requested_region_snapshot_replacement_steps(&opctx) + .await + .unwrap() + .is_empty() + ); // Insert some replacement steps, and make sure counting works @@ -2025,13 +2027,15 @@ mod test { .await .unwrap(); - assert!(datastore - .region_snapshot_replacement_steps_requiring_garbage_collection( - &opctx - ) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .region_snapshot_replacement_steps_requiring_garbage_collection( + &opctx + ) + .await + .unwrap() + .is_empty() + ); let step_volume_id = VolumeUuid::new_v4(); diff --git a/nexus/db-queries/src/db/datastore/rendezvous_debug_dataset.rs b/nexus/db-queries/src/db/datastore/rendezvous_debug_dataset.rs index 3d2c2aac3ff..9236ce858b1 100644 --- a/nexus/db-queries/src/db/datastore/rendezvous_debug_dataset.rs +++ b/nexus/db-queries/src/db/datastore/rendezvous_debug_dataset.rs @@ -9,15 +9,15 @@ use super::SQL_BATCH_SIZE; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::pagination::paginated; +use crate::db::error::public_error_from_diesel; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; -use nexus_db_model::to_db_typed_uuid; use nexus_db_model::RendezvousDebugDataset; +use nexus_db_model::to_db_typed_uuid; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::Error; diff --git a/nexus/db-queries/src/db/datastore/role.rs b/nexus/db-queries/src/db/datastore/role.rs index 757658351b1..c4e106705d5 100644 --- a/nexus/db-queries/src/db/datastore/role.rs +++ b/nexus/db-queries/src/db/datastore/role.rs @@ -11,9 +11,9 @@ use crate::context::OpContext; use crate::db; use crate::db::datastore::RunnableQuery; use crate::db::datastore::RunnableQueryNoReturn; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; use crate::db::error::TransactionError; +use crate::db::error::public_error_from_diesel; use crate::db::model::DatabaseString; use crate::db::model::IdentityType; use crate::db::model::RoleAssignment; diff --git a/nexus/db-queries/src/db/datastore/saga.rs b/nexus/db-queries/src/db/datastore/saga.rs index 87d94e23771..1e9e24b68ad 100644 --- a/nexus/db-queries/src/db/datastore/saga.rs +++ b/nexus/db-queries/src/db/datastore/saga.rs @@ -7,11 +7,11 @@ use super::DataStore; use super::SQL_BATCH_SIZE; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; +use crate::db::pagination::Paginator; use crate::db::pagination::paginated; use crate::db::pagination::paginated_multicolumn; -use crate::db::pagination::Paginator; use crate::db::update_and_check::UpdateAndCheck; use crate::db::update_and_check::UpdateStatus; use async_bb8_diesel::AsyncRunQueryDsl; diff --git a/nexus/db-queries/src/db/datastore/silo.rs b/nexus/db-queries/src/db/datastore/silo.rs index c963e13ae45..cde6a2bd34a 100644 --- a/nexus/db-queries/src/db/datastore/silo.rs +++ b/nexus/db-queries/src/db/datastore/silo.rs @@ -4,25 +4,25 @@ //! [`DataStore`] methods related to [`Silo`]s. -use super::dns::DnsVersionUpdateBuilder; use super::DataStore; use super::SQL_BATCH_SIZE; +use super::dns::DnsVersionUpdateBuilder; use crate::authz; use crate::context::OpContext; use crate::db; use crate::db::datastore::RunnableQuery; -use crate::db::error::public_error_from_diesel; -use crate::db::error::retryable; use crate::db::error::ErrorHandler; use crate::db::error::TransactionError; +use crate::db::error::public_error_from_diesel; +use crate::db::error::retryable; use crate::db::identity::Resource; use crate::db::model::CollectionTypeProvisioned; use crate::db::model::IpPoolResourceType; use crate::db::model::Name; use crate::db::model::Silo; use crate::db::model::VirtualProvisioningCollection; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::pool::DbConnection; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; @@ -34,7 +34,6 @@ use nexus_db_model::SiloQuotas; use nexus_types::external_api::params; use nexus_types::external_api::shared; use nexus_types::external_api::shared::SiloRole; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; @@ -42,6 +41,7 @@ use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/datastore/silo_group.rs b/nexus/db-queries/src/db/datastore/silo_group.rs index 4d5543cc9cc..a6a6b1e0443 100644 --- a/nexus/db-queries/src/db/datastore/silo_group.rs +++ b/nexus/db-queries/src/db/datastore/silo_group.rs @@ -8,14 +8,14 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::IncompleteOnConflictExt; use crate::db::datastore::RunnableQueryNoReturn; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; use crate::db::error::TransactionError; +use crate::db::error::public_error_from_diesel; use crate::db::model::SiloGroup; use crate::db::model::SiloGroupMembership; use crate::db::pagination::paginated; -use crate::db::IncompleteOnConflictExt; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; diff --git a/nexus/db-queries/src/db/datastore/silo_user.rs b/nexus/db-queries/src/db/datastore/silo_user.rs index 40f6b3f0bed..6505dbdf1bc 100644 --- a/nexus/db-queries/src/db/datastore/silo_user.rs +++ b/nexus/db-queries/src/db/datastore/silo_user.rs @@ -10,8 +10,8 @@ use crate::authz; use crate::context::OpContext; use crate::db; use crate::db::datastore::IdentityMetadataCreateParams; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::Name; use crate::db::model::Silo; use crate::db::model::SiloUser; diff --git a/nexus/db-queries/src/db/datastore/sled.rs b/nexus/db-queries/src/db/datastore/sled.rs index ee4e6c31cf7..2fad63aa4be 100644 --- a/nexus/db-queries/src/db/datastore/sled.rs +++ b/nexus/db-queries/src/db/datastore/sled.rs @@ -9,19 +9,19 @@ use super::SQL_BATCH_SIZE; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::TransactionError; use crate::db::datastore::ValidateTransition; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_sled_policy; +use crate::db::error::public_error_from_diesel; use crate::db::model::Sled; use crate::db::model::SledResource; use crate::db::model::SledState; use crate::db::model::SledUpdate; -use crate::db::pagination::paginated; +use crate::db::model::to_db_sled_policy; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::pool::DbConnection; use crate::db::update_and_check::{UpdateAndCheck, UpdateStatus}; -use crate::db::TransactionError; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; @@ -845,12 +845,12 @@ pub(in crate::db::datastore) mod test { sled_baseboard_for_test, sled_system_hardware_for_test, }; use crate::db::datastore::test_utils::{ - sled_set_policy, sled_set_state, Expected, IneligibleSleds, + Expected, IneligibleSleds, sled_set_policy, sled_set_state, }; use crate::db::lookup::LookupPath; - use crate::db::model::to_db_typed_uuid; use crate::db::model::ByteCount; use crate::db::model::SqlU32; + use crate::db::model::to_db_typed_uuid; use crate::db::pub_test_utils::TestDatabase; use anyhow::{Context, Result}; use itertools::Itertools; @@ -865,7 +865,7 @@ pub(in crate::db::datastore) mod test { use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::SledUuid; - use predicates::{prelude::*, BoxPredicate}; + use predicates::{BoxPredicate, prelude::*}; use std::net::{Ipv6Addr, SocketAddrV6}; fn rack_id() -> Uuid { diff --git a/nexus/db-queries/src/db/datastore/sled_instance.rs b/nexus/db-queries/src/db/datastore/sled_instance.rs index dbdd696d702..63c42c6f528 100644 --- a/nexus/db-queries/src/db/datastore/sled_instance.rs +++ b/nexus/db-queries/src/db/datastore/sled_instance.rs @@ -3,8 +3,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; diff --git a/nexus/db-queries/src/db/datastore/snapshot.rs b/nexus/db-queries/src/db/datastore/snapshot.rs index a6fe0345ac0..018220374a7 100644 --- a/nexus/db-queries/src/db/datastore/snapshot.rs +++ b/nexus/db-queries/src/db/datastore/snapshot.rs @@ -8,27 +8,26 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; +use crate::db::IncompleteOnConflictExt; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_typed_uuid; +use crate::db::error::public_error_from_diesel; use crate::db::model::Generation; use crate::db::model::Name; use crate::db::model::Project; use crate::db::model::Snapshot; use crate::db::model::SnapshotState; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::paginated; use crate::db::update_and_check::UpdateAndCheck; use crate::db::update_and_check::UpdateStatus; -use crate::db::IncompleteOnConflictExt; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; -use diesel::prelude::*; use diesel::OptionalExtension; +use diesel::prelude::*; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; @@ -36,6 +35,7 @@ use omicron_common::api::external::LookupResult; use omicron_common::api::external::LookupType; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::bail_unless; use omicron_uuid_kinds::VolumeUuid; use ref_cast::RefCast; @@ -288,8 +288,7 @@ impl DataStore { } else if snapshot.gen != gen { Err(Error::invalid_request(&format!( "snapshot cannot be deleted: mismatched generation {:?} != {:?}", - gen, - snapshot.gen, + gen, snapshot.gen, ))) } else { error!( diff --git a/nexus/db-queries/src/db/datastore/ssh_key.rs b/nexus/db-queries/src/db/datastore/ssh_key.rs index 9e9b6230b7a..ed560772388 100644 --- a/nexus/db-queries/src/db/datastore/ssh_key.rs +++ b/nexus/db-queries/src/db/datastore/ssh_key.rs @@ -8,8 +8,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Resource; use crate::db::model::Name; use crate::db::model::SshKey; @@ -18,7 +18,6 @@ use crate::db::update_and_check::UpdateAndCheck; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -27,6 +26,7 @@ use omicron_common::api::external::LookupType; use omicron_common::api::external::NameOrId; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::InstanceUuid; use ref_cast::RefCast; diff --git a/nexus/db-queries/src/db/datastore/support_bundle.rs b/nexus/db-queries/src/db/datastore/support_bundle.rs index 8b6d4bfb0ae..fff7e0a17bc 100644 --- a/nexus/db-queries/src/db/datastore/support_bundle.rs +++ b/nexus/db-queries/src/db/datastore/support_bundle.rs @@ -8,8 +8,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::lookup::LookupPath; use crate::db::model::RendezvousDebugDataset; use crate::db::model::SupportBundle; @@ -31,8 +31,7 @@ use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::SupportBundleUuid; use uuid::Uuid; -const CANNOT_ALLOCATE_ERR_MSG: &'static str = -"Current policy limits support bundle creation to 'one per external disk', and \ +const CANNOT_ALLOCATE_ERR_MSG: &'static str = "Current policy limits support bundle creation to 'one per external disk', and \ no disks are available. You must delete old support bundles before new ones \ can be created"; @@ -636,7 +635,9 @@ mod test { .await .expect_err("Shouldn't provision bundle without datasets"); let Error::InsufficientCapacity { message } = err else { - panic!("Unexpected error: {err:?} - we expected 'InsufficientCapacity'"); + panic!( + "Unexpected error: {err:?} - we expected 'InsufficientCapacity'" + ); }; assert_eq!( CANNOT_ALLOCATE_ERR_MSG, @@ -1087,10 +1088,12 @@ mod test { .await .expect("Should be able to get bundle we just failed"); assert_eq!(SupportBundleState::Failed, observed_bundle.state); - assert!(observed_bundle - .reason_for_failure - .unwrap() - .contains(FAILURE_REASON_NO_DATASET)); + assert!( + observed_bundle + .reason_for_failure + .unwrap() + .contains(FAILURE_REASON_NO_DATASET) + ); db.terminate().await; logctx.cleanup_successful(); @@ -1286,10 +1289,12 @@ mod test { .await .expect("Should be able to get bundle we just failed"); assert_eq!(SupportBundleState::Failed, observed_bundle.state); - assert!(observed_bundle - .reason_for_failure - .unwrap() - .contains(FAILURE_REASON_NO_DATASET)); + assert!( + observed_bundle + .reason_for_failure + .unwrap() + .contains(FAILURE_REASON_NO_DATASET) + ); // Expunge the bundle's Nexus let bp3 = { @@ -1316,10 +1321,12 @@ mod test { .await .expect("Should be able to get bundle we just failed"); assert_eq!(SupportBundleState::Failed, observed_bundle.state); - assert!(observed_bundle - .reason_for_failure - .unwrap() - .contains(FAILURE_REASON_NO_DATASET)); + assert!( + observed_bundle + .reason_for_failure + .unwrap() + .contains(FAILURE_REASON_NO_DATASET) + ); let authz_bundle = authz_support_bundle_from_id(bundle.id.into()); datastore @@ -1421,10 +1428,12 @@ mod test { .await .expect("Should be able to get bundle we just failed"); assert_eq!(SupportBundleState::Failing, observed_bundle.state); - assert!(observed_bundle - .reason_for_failure - .unwrap() - .contains(FAILURE_REASON_NO_NEXUS)); + assert!( + observed_bundle + .reason_for_failure + .unwrap() + .contains(FAILURE_REASON_NO_NEXUS) + ); db.terminate().await; logctx.cleanup_successful(); diff --git a/nexus/db-queries/src/db/datastore/switch.rs b/nexus/db-queries/src/db/datastore/switch.rs index 148f4577de9..2dc0f04804a 100644 --- a/nexus/db-queries/src/db/datastore/switch.rs +++ b/nexus/db-queries/src/db/datastore/switch.rs @@ -2,8 +2,8 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Asset; use crate::db::model::Switch; use crate::db::pagination::paginated; diff --git a/nexus/db-queries/src/db/datastore/switch_interface.rs b/nexus/db-queries/src/db/datastore/switch_interface.rs index aa4f6747fd0..2a85ff569ba 100644 --- a/nexus/db-queries/src/db/datastore/switch_interface.rs +++ b/nexus/db-queries/src/db/datastore/switch_interface.rs @@ -9,8 +9,8 @@ use crate::db; use crate::db::datastore::address_lot::{ ReserveBlockError, ReserveBlockTxnError, }; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::LoopbackAddress; use crate::db::pagination::paginated; use crate::transaction_retry::OptionalError; diff --git a/nexus/db-queries/src/db/datastore/switch_port.rs b/nexus/db-queries/src/db/datastore/switch_port.rs index 6b282434cd8..546974d56d6 100644 --- a/nexus/db-queries/src/db/datastore/switch_port.rs +++ b/nexus/db-queries/src/db/datastore/switch_port.rs @@ -8,12 +8,12 @@ use std::net::IpAddr; use super::DataStore; use crate::context::OpContext; use crate::db; +use crate::db::datastore::UpdatePrecondition; use crate::db::datastore::address_lot::{ ReserveBlockError, ReserveBlockTxnError, }; -use crate::db::datastore::UpdatePrecondition; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::{ LldpLinkConfig, Name, SwitchInterfaceConfig, SwitchPort, SwitchPortAddressConfig, SwitchPortBgpPeerConfig, SwitchPortConfig, @@ -31,7 +31,7 @@ use diesel::{ use diesel_dtrace::DTraceConnection; use ipnetwork::IpNetwork; use nexus_db_model::{ - BgpConfig, SqlU16, SqlU32, SqlU8, SwitchPortBgpPeerConfigAllowExport, + BgpConfig, SqlU8, SqlU16, SqlU32, SwitchPortBgpPeerConfigAllowExport, SwitchPortBgpPeerConfigAllowImport, SwitchPortBgpPeerConfigCommunity, }; use nexus_types::external_api::params; diff --git a/nexus/db-queries/src/db/datastore/test_utils.rs b/nexus/db-queries/src/db/datastore/test_utils.rs index c3e9137ac85..4dc870ae1d7 100644 --- a/nexus/db-queries/src/db/datastore/test_utils.rs +++ b/nexus/db-queries/src/db/datastore/test_utils.rs @@ -6,13 +6,13 @@ use crate::authz; use crate::context::OpContext; +use crate::db::DataStore; use crate::db::datastore::ValidateTransition; use crate::db::lookup::LookupPath; -use crate::db::DataStore; -use anyhow::bail; -use anyhow::ensure; use anyhow::Context; use anyhow::Result; +use anyhow::bail; +use anyhow::ensure; use futures::future::try_join_all; use nexus_db_model::SledState; use nexus_types::external_api::views::SledPolicy; diff --git a/nexus/db-queries/src/db/datastore/update.rs b/nexus/db-queries/src/db/datastore/update.rs index 8abddc8ada0..d0a59020e2c 100644 --- a/nexus/db-queries/src/db/datastore/update.rs +++ b/nexus/db-queries/src/db/datastore/update.rs @@ -10,7 +10,7 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::{public_error_from_diesel, ErrorHandler}; +use crate::db::error::{ErrorHandler, public_error_from_diesel}; use crate::db::model::SemverVersion; use crate::db::pagination::paginated; use crate::transaction_retry::OptionalError; @@ -24,7 +24,7 @@ use omicron_common::api::external::{ }; use omicron_uuid_kinds::TufRepoKind; use omicron_uuid_kinds::TypedUuid; -use swrite::{swrite, SWrite}; +use swrite::{SWrite, swrite}; use uuid::Uuid; /// The return value of [`DataStore::update_tuf_repo_insert`]. diff --git a/nexus/db-queries/src/db/datastore/utilization.rs b/nexus/db-queries/src/db/datastore/utilization.rs index 826c66043a9..b1ade6d606c 100644 --- a/nexus/db-queries/src/db/datastore/utilization.rs +++ b/nexus/db-queries/src/db/datastore/utilization.rs @@ -2,17 +2,17 @@ use super::DataStore; use crate::authz; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::Name; use crate::db::model::SiloUtilization; use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::BoolExpressionMethods; use diesel::{ExpressionMethods, QueryDsl, SelectableHelper}; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; impl DataStore { diff --git a/nexus/db-queries/src/db/datastore/v2p_mapping.rs b/nexus/db-queries/src/db/datastore/v2p_mapping.rs index 3c6acd3df3a..fa9f058e88b 100644 --- a/nexus/db-queries/src/db/datastore/v2p_mapping.rs +++ b/nexus/db-queries/src/db/datastore/v2p_mapping.rs @@ -6,11 +6,11 @@ use super::DataStore; use crate::context::OpContext; use crate::db; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::{public_error_from_diesel, ErrorHandler}; +use crate::db::error::{ErrorHandler, public_error_from_diesel}; use crate::db::model::ApplySledFilterExt; use crate::db::model::V2PMappingView; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ExpressionMethods, QueryDsl, SelectableHelper}; use diesel::{JoinOnDsl, NullableExpressionMethods}; diff --git a/nexus/db-queries/src/db/datastore/virtual_provisioning_collection.rs b/nexus/db-queries/src/db/datastore/virtual_provisioning_collection.rs index d7639205ded..688884df070 100644 --- a/nexus/db-queries/src/db/datastore/virtual_provisioning_collection.rs +++ b/nexus/db-queries/src/db/datastore/virtual_provisioning_collection.rs @@ -7,8 +7,8 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::ByteCount; use crate::db::model::VirtualProvisioningCollection; use crate::db::pool::DbConnection; diff --git a/nexus/db-queries/src/db/datastore/vmm.rs b/nexus/db-queries/src/db/datastore/vmm.rs index 15d8404fd63..b1e070b4fdc 100644 --- a/nexus/db-queries/src/db/datastore/vmm.rs +++ b/nexus/db-queries/src/db/datastore/vmm.rs @@ -7,8 +7,8 @@ use super::DataStore; use crate::context::OpContext; use crate::db; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::model::Vmm; use crate::db::model::VmmRuntimeState; use crate::db::model::VmmState as DbVmmState; diff --git a/nexus/db-queries/src/db/datastore/volume.rs b/nexus/db-queries/src/db/datastore/volume.rs index 7c7afbfce06..008d7fdeb9f 100644 --- a/nexus/db-queries/src/db/datastore/volume.rs +++ b/nexus/db-queries/src/db/datastore/volume.rs @@ -6,14 +6,14 @@ use super::DataStore; use crate::db; +use crate::db::DbConnection; use crate::db::datastore::OpContext; -use crate::db::datastore::RunnableQuery; use crate::db::datastore::REGION_REDUNDANCY_THRESHOLD; +use crate::db::datastore::RunnableQuery; use crate::db::datastore::SQL_BATCH_SIZE; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Asset; -use crate::db::model::to_db_typed_uuid; use crate::db::model::CrucibleDataset; use crate::db::model::Disk; use crate::db::model::DownstairsClientStopRequestNotification; @@ -28,16 +28,16 @@ use crate::db::model::Volume; use crate::db::model::VolumeResourceUsage; use crate::db::model::VolumeResourceUsageRecord; use crate::db::model::VolumeResourceUsageType; -use crate::db::pagination::paginated; +use crate::db::model::to_db_typed_uuid; use crate::db::pagination::Paginator; -use crate::db::DbConnection; +use crate::db::pagination::paginated; use crate::transaction_retry::OptionalError; use anyhow::anyhow; use anyhow::bail; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; -use diesel::prelude::*; use diesel::OptionalExtension; +use diesel::prelude::*; use nexus_types::identity::Resource; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; @@ -666,12 +666,12 @@ impl DataStore { return Err( VolumeGetError::CheckoutConditionFailed( format!( - "InstanceStart {}: instance {} propolis \ + "InstanceStart {}: instance {} propolis \ id {} mismatch", - vmm_id, - instance.id(), - propolis_id, - ), + vmm_id, + instance.id(), + propolis_id, + ), ), ); } @@ -4067,8 +4067,8 @@ impl DataStore { mod tests { use super::*; - use crate::db::datastore::test::TestDatasets; use crate::db::datastore::REGION_REDUNDANCY_THRESHOLD; + use crate::db::datastore::test::TestDatasets; use crate::db::pub_test_utils::TestDatabase; use nexus_config::RegionAllocationStrategy; use nexus_db_model::SqlU16; @@ -5101,11 +5101,13 @@ mod tests { )), }; - assert!(read_only_target_in_vcr( - &vcr, - &"[fd00:1122:3344:104::1]:400".parse().unwrap(), - ) - .unwrap()); + assert!( + read_only_target_in_vcr( + &vcr, + &"[fd00:1122:3344:104::1]:400".parse().unwrap(), + ) + .unwrap() + ); // read_only_target_in_vcr should _not_ find read-write targets @@ -5137,11 +5139,13 @@ mod tests { read_only_parent: None, }; - assert!(!read_only_target_in_vcr( - &vcr, - &"[fd00:1122:3344:104::1]:400".parse().unwrap(), - ) - .unwrap()); + assert!( + !read_only_target_in_vcr( + &vcr, + &"[fd00:1122:3344:104::1]:400".parse().unwrap(), + ) + .unwrap() + ); // read_only_target_in_vcr should bail on incorrect VCRs (currently it // only detects a read/write region under a read-only parent) diff --git a/nexus/db-queries/src/db/datastore/volume_repair.rs b/nexus/db-queries/src/db/datastore/volume_repair.rs index 4e561f94758..70c47403c60 100644 --- a/nexus/db-queries/src/db/datastore/volume_repair.rs +++ b/nexus/db-queries/src/db/datastore/volume_repair.rs @@ -6,13 +6,13 @@ use super::DataStore; use crate::db; +use crate::db::DbConnection; use crate::db::datastore::OpContext; use crate::db::datastore::RunnableQuery; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; -use crate::db::model::to_db_typed_uuid; +use crate::db::error::public_error_from_diesel; use crate::db::model::VolumeRepair; -use crate::db::DbConnection; +use crate::db::model::to_db_typed_uuid; use crate::transaction_retry::OptionalError; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::prelude::*; diff --git a/nexus/db-queries/src/db/datastore/vpc.rs b/nexus/db-queries/src/db/datastore/vpc.rs index dbccde8c500..eae004a7703 100644 --- a/nexus/db-queries/src/db/datastore/vpc.rs +++ b/nexus/db-queries/src/db/datastore/vpc.rs @@ -13,8 +13,8 @@ use crate::db::collection_attach::AttachError; use crate::db::collection_attach::DatastoreAttachTarget; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Resource; use crate::db::model::ApplySledFilterExt; use crate::db::model::IncompleteVpc; @@ -35,8 +35,8 @@ use crate::db::model::VpcSubnet; use crate::db::model::VpcSubnetUpdate; use crate::db::model::VpcUpdate; use crate::db::model::{Ipv4Net, Ipv6Net}; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; +use crate::db::pagination::paginated; use crate::db::queries::vpc::InsertVpcQuery; use crate::db::queries::vpc::VniSearchIter; use crate::db::queries::vpc_subnet::InsertVpcSubnetError; @@ -47,8 +47,8 @@ use chrono::Utc; use diesel::prelude::*; use diesel::result::DatabaseErrorKind; use diesel::result::Error as DieselError; -use futures::stream::{self, StreamExt}; use futures::TryStreamExt; +use futures::stream::{self, StreamExt}; use ipnetwork::IpNetwork; use nexus_auth::authz::ApiResource; use nexus_db_fixed_data::vpc::SERVICES_INTERNET_GATEWAY_DEFAULT_ROUTE_V4; @@ -63,7 +63,6 @@ use nexus_db_model::InternetGatewayIpPool; use nexus_db_model::IpPoolRange; use nexus_db_model::NetworkInterfaceKind; use nexus_types::deployment::SledFilter; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -78,6 +77,7 @@ use omicron_common::api::external::RouteTarget; use omicron_common::api::external::RouterRouteKind as ExternalRouteKind; use omicron_common::api::external::UpdateResult; use omicron_common::api::external::Vni as ExternalVni; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::internal::shared::InternetGatewayRouterTarget; use omicron_common::api::internal::shared::ResolvedVpcRoute; use omicron_common::api::internal::shared::RouterTarget; @@ -1068,7 +1068,7 @@ impl DataStore { return Err(err.bail_retryable_or_else( e, SubnetError::SubnetModify, - )) + )); } }; @@ -2439,7 +2439,7 @@ impl DataStore { Err(e) => { return Err(Error::non_resourcetype_not_found(&format!( "unable to find IGW mappings for sled {sled_id}: {e}" - ))) + ))); } } @@ -2472,7 +2472,7 @@ impl DataStore { Err(e) => { return Err(Error::non_resourcetype_not_found(&format!( "unable to find IGW mappings for sled {sled_id}: {e}" - ))) + ))); } } @@ -2998,7 +2998,9 @@ mod tests { .project_create_vpc_raw(&opctx, &authz_project, query) .await else { - panic!("Expected Ok(None) when creating a VPC without any available VNIs"); + panic!( + "Expected Ok(None) when creating a VPC without any available VNIs" + ); }; db.terminate().await; logctx.cleanup_successful(); diff --git a/nexus/db-queries/src/db/datastore/zpool.rs b/nexus/db-queries/src/db/datastore/zpool.rs index 373b9074956..8960459d07d 100644 --- a/nexus/db-queries/src/db/datastore/zpool.rs +++ b/nexus/db-queries/src/db/datastore/zpool.rs @@ -8,20 +8,20 @@ use super::DataStore; use super::SQL_BATCH_SIZE; use crate::authz; use crate::db; +use crate::db::TransactionError; use crate::db::collection_insert::AsyncInsertError; use crate::db::collection_insert::DatastoreCollection; use crate::db::datastore::OpContext; -use crate::db::error::public_error_from_diesel; use crate::db::error::ErrorHandler; +use crate::db::error::public_error_from_diesel; use crate::db::identity::Asset; use crate::db::model::PhysicalDisk; use crate::db::model::PhysicalDiskPolicy; use crate::db::model::PhysicalDiskState; use crate::db::model::Sled; use crate::db::model::Zpool; -use crate::db::pagination::paginated; use crate::db::pagination::Paginator; -use crate::db::TransactionError; +use crate::db::pagination::paginated; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::Utc; use diesel::prelude::*; @@ -246,9 +246,9 @@ impl DataStore { .await .map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?; if region_snapshot_count > 0 { - return Err( - Error::unavail(&format!("Cannot delete this zpool; it has {region_snapshot_count} region snapshots")) - ); + return Err(Error::unavail(&format!( + "Cannot delete this zpool; it has {region_snapshot_count} region snapshots" + ))); } // Ensure the datasets are deleted diff --git a/nexus/db-queries/src/db/lookup.rs b/nexus/db-queries/src/db/lookup.rs index 402e56c0ed7..a91f38df273 100644 --- a/nexus/db-queries/src/db/lookup.rs +++ b/nexus/db-queries/src/db/lookup.rs @@ -11,7 +11,7 @@ use crate::{ authz, context::OpContext, db, - db::error::{public_error_from_diesel, ErrorHandler}, + db::error::{ErrorHandler, public_error_from_diesel}, }; use async_bb8_diesel::AsyncRunQueryDsl; use db_macros::lookup_resource; diff --git a/nexus/db-queries/src/db/pagination.rs b/nexus/db-queries/src/db/pagination.rs index 1929632980d..2adeda44267 100644 --- a/nexus/db-queries/src/db/pagination.rs +++ b/nexus/db-queries/src/db/pagination.rs @@ -4,6 +4,8 @@ //! Interface for paginating database queries. +use diesel::AppearsOnTable; +use diesel::Column; use diesel::dsl::{Asc, Desc, Gt, Lt}; use diesel::expression::{AsExpression, Expression}; use diesel::expression_methods::BoolExpressionMethods; @@ -13,8 +15,6 @@ use diesel::query_builder::AsQuery; use diesel::query_dsl::methods as query_methods; use diesel::query_source::QuerySource; use diesel::sql_types::{Bool, SqlType}; -use diesel::AppearsOnTable; -use diesel::Column; use diesel::{ExpressionMethods, QueryDsl}; use omicron_common::api::external::DataPageParams; use std::num::NonZeroU32; @@ -85,76 +85,76 @@ pub fn paginated_multicolumn( pagparams: &DataPageParams<'_, (M1, M2)>, ) -> >::Output where - // T is a table^H^H^H^H^Hquery source which can create a BoxedQuery. +// T is a table^H^H^H^H^Hquery source which can create a BoxedQuery. T: QuerySource, T: AsQuery, ::DefaultSelection: Expression::SqlType>, T::Query: query_methods::BoxedDsl<'static, Pg>, - // Required for...everything. +// Required for...everything. >::Output: QueryDsl, - // C1 & C2 are columns which appear in T. +// C1 & C2 are columns which appear in T. C1: 'static + Column + Copy + ExpressionMethods, C2: 'static + Column + Copy + ExpressionMethods, - // Required to compare the columns with the marker types. +// Required to compare the columns with the marker types. C1::SqlType: SqlType, C2::SqlType: SqlType, M1: Clone + AsExpression, M2: Clone + AsExpression, - // Necessary for `query.limit(...)` +// Necessary for `query.limit(...)` >::Output: query_methods::LimitDsl< Output = >::Output, >, - // Necessary for "query.order(c1.desc())" +// Necessary for "query.order(c1.desc())" >::Output: query_methods::OrderDsl< Desc, Output = >::Output, >, - // Necessary for "query.order(...).then_order_by(c2.desc())" +// Necessary for "query.order(...).then_order_by(c2.desc())" >::Output: query_methods::ThenOrderDsl< Desc, Output = >::Output, >, - // Necessary for "query.order(c1.asc())" +// Necessary for "query.order(c1.asc())" >::Output: query_methods::OrderDsl< Asc, Output = >::Output, >, - // Necessary for "query.order(...).then_order_by(c2.asc())" +// Necessary for "query.order(...).then_order_by(c2.asc())" >::Output: query_methods::ThenOrderDsl< Asc, Output = >::Output, >, - // We'd like to be able to call: - // - // c1.eq(v1).and(c2.gt(v2)) - // - // This means "c1.eq(v1)" must implement BoolExpressionMethods, and - // satisfy the requirements of the ".and" method. - // - // The LHS (c1.eq(v1)) must be a boolean expression: +// We'd like to be able to call: +// +// c1.eq(v1).and(c2.gt(v2)) +// +// This means "c1.eq(v1)" must implement BoolExpressionMethods, and +// satisfy the requirements of the ".and" method. +// +// The LHS (c1.eq(v1)) must be a boolean expression: Eq: Expression, - // The RHS (c2.gt(v2)) must be a boolean expression: +// The RHS (c2.gt(v2)) must be a boolean expression: Gt: Expression, - // Putting it together, we should be able to filter by LHS.and(RHS): +// Putting it together, we should be able to filter by LHS.and(RHS): >::Output: query_methods::FilterDsl< And, Gt>, Output = >::Output, >, - // We'd also like to be able to call: - // - // c1.eq(v1).and(c2.lt(v2)) - // - // We've already defined the bound on the LHS, so we add the equivalent - // bounds on the RHS for the "Less than" variant. +// We'd also like to be able to call: +// +// c1.eq(v1).and(c2.lt(v2)) +// +// We've already defined the bound on the LHS, so we add the equivalent +// bounds on the RHS for the "Less than" variant. Lt: Expression, >::Output: query_methods::FilterDsl< @@ -162,13 +162,13 @@ where Output = >::Output, >, - // Necessary for "query.or_filter(c1.gt(v1))" +// Necessary for "query.or_filter(c1.gt(v1))" >::Output: query_methods::OrFilterDsl< Gt, Output = >::Output, >, - // Necessary for "query.or_filter(c1.lt(v1))" +// Necessary for "query.or_filter(c1.lt(v1))" >::Output: query_methods::OrFilterDsl< Lt, diff --git a/nexus/db-queries/src/db/pub_test_utils/mod.rs b/nexus/db-queries/src/db/pub_test_utils/mod.rs index 3e184538030..ea1e8e2bddc 100644 --- a/nexus/db-queries/src/db/pub_test_utils/mod.rs +++ b/nexus/db-queries/src/db/pub_test_utils/mod.rs @@ -136,7 +136,9 @@ impl TestDatabaseBuilder { // This configuration isn't wrong, it's just weird - we need to // build a datastore to load the built-in data, so it's odd to // discard it immediately afterwards. - panic!("If you're fully populating a datastore, you probably want a connection to it"); + panic!( + "If you're fully populating a datastore, you probably want a connection to it" + ); } } } @@ -241,7 +243,9 @@ impl TestDatabase { TestKind::NoPool | TestKind::Pool { .. } | TestKind::RawDatastore { .. } => { - panic!("Wrong test type; try using `TestDatabase::new_with_datastore`"); + panic!( + "Wrong test type; try using `TestDatabase::new_with_datastore`" + ); } TestKind::Datastore { opctx, .. } => opctx, } @@ -250,7 +254,9 @@ impl TestDatabase { pub fn datastore(&self) -> &Arc { match &self.kind { TestKind::NoPool | TestKind::Pool { .. } => { - panic!("Wrong test type; try using `TestDatabase::new_with_datastore`"); + panic!( + "Wrong test type; try using `TestDatabase::new_with_datastore`" + ); } TestKind::RawDatastore { datastore } => datastore, TestKind::Datastore { datastore, .. } => datastore, diff --git a/nexus/db-queries/src/db/queries/disk.rs b/nexus/db-queries/src/db/queries/disk.rs index dc1a31dd01e..274ae5305e8 100644 --- a/nexus/db-queries/src/db/queries/disk.rs +++ b/nexus/db-queries/src/db/queries/disk.rs @@ -7,9 +7,10 @@ use crate::db; use crate::db::queries::next_item::{DefaultShiftGenerator, NextItem}; use diesel::{ + Column, QueryResult, pg::Pg, query_builder::{AstPass, QueryFragment, QueryId}, - sql_types, Column, QueryResult, + sql_types, }; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/queries/external_ip.rs b/nexus/db-queries/src/db/queries/external_ip.rs index 8cc33e96d95..9e81bfd6cfd 100644 --- a/nexus/db-queries/src/db/queries/external_ip.rs +++ b/nexus/db-queries/src/db/queries/external_ip.rs @@ -12,9 +12,13 @@ use crate::db::model::IpKindEnum; use crate::db::model::Name; use crate::db::pool::DbConnection; use crate::db::schema; -use crate::db::true_or_cast_error::{matches_sentinel, TrueOrCastError}; +use crate::db::true_or_cast_error::{TrueOrCastError, matches_sentinel}; use chrono::DateTime; use chrono::Utc; +use diesel::Column; +use diesel::Expression; +use diesel::QueryResult; +use diesel::RunQueryDsl; use diesel::pg::Pg; use diesel::query_builder::AstPass; use diesel::query_builder::Query; @@ -22,10 +26,6 @@ use diesel::query_builder::QueryFragment; use diesel::query_builder::QueryId; use diesel::result::Error as DieselError; use diesel::sql_types; -use diesel::Column; -use diesel::Expression; -use diesel::QueryResult; -use diesel::RunQueryDsl; use nexus_db_model::InstanceState as DbInstanceState; use nexus_db_model::IpAttachState; use nexus_db_model::IpAttachStateEnum; diff --git a/nexus/db-queries/src/db/queries/ip_pool.rs b/nexus/db-queries/src/db/queries/ip_pool.rs index 6a28854a24a..b6d14d1aa91 100644 --- a/nexus/db-queries/src/db/queries/ip_pool.rs +++ b/nexus/db-queries/src/db/queries/ip_pool.rs @@ -8,14 +8,14 @@ use crate::db::model::IpPoolRange; use crate::db::schema::ip_pool_range::dsl; use chrono::DateTime; use chrono::Utc; +use diesel::Column; +use diesel::Insertable; +use diesel::QueryResult; use diesel::pg::Pg; use diesel::query_builder::AstPass; use diesel::query_builder::QueryFragment; use diesel::query_builder::QueryId; use diesel::sql_types; -use diesel::Column; -use diesel::Insertable; -use diesel::QueryResult; use ipnetwork::IpNetwork; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/queries/mod.rs b/nexus/db-queries/src/db/queries/mod.rs index 5f34c7cfb3d..001a6775ec4 100644 --- a/nexus/db-queries/src/db/queries/mod.rs +++ b/nexus/db-queries/src/db/queries/mod.rs @@ -35,6 +35,5 @@ pub mod vpc_subnet; /// the same pooled connection after this SQL gets run. /// /// **BE VERY CAREFUL WHEN USING THIS.** -pub const ALLOW_FULL_TABLE_SCAN_SQL: &str = - "set local disallow_full_table_scans = off; \ +pub const ALLOW_FULL_TABLE_SCAN_SQL: &str = "set local disallow_full_table_scans = off; \ set local large_full_scan_rows = 1000;"; diff --git a/nexus/db-queries/src/db/queries/network_interface.rs b/nexus/db-queries/src/db/queries/network_interface.rs index 57868f32809..bfc4715b318 100644 --- a/nexus/db-queries/src/db/queries/network_interface.rs +++ b/nexus/db-queries/src/db/queries/network_interface.rs @@ -5,7 +5,7 @@ //! Queries for inserting and deleting network interfaces. use crate::db; -use crate::db::error::{public_error_from_diesel, retryable, ErrorHandler}; +use crate::db::error::{ErrorHandler, public_error_from_diesel, retryable}; use crate::db::model::IncompleteNetworkInterface; use crate::db::pool::DbConnection; use crate::db::queries::next_item::DefaultShiftGenerator; @@ -14,6 +14,9 @@ use crate::db::schema::network_interface::dsl; use async_bb8_diesel::AsyncRunQueryDsl; use chrono::DateTime; use chrono::Utc; +use diesel::Insertable; +use diesel::QueryResult; +use diesel::RunQueryDsl; use diesel::pg::Pg; use diesel::prelude::Column; use diesel::query_builder::QueryFragment; @@ -21,13 +24,10 @@ use diesel::query_builder::QueryId; use diesel::query_builder::{AstPass, Query}; use diesel::result::Error as DieselError; use diesel::sql_types::{self, Nullable}; -use diesel::Insertable; -use diesel::QueryResult; -use diesel::RunQueryDsl; use ipnetwork::IpNetwork; use ipnetwork::Ipv4Network; use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; -use nexus_db_model::{NetworkInterfaceKind, MAX_NICS_PER_INSTANCE}; +use nexus_db_model::{MAX_NICS_PER_INSTANCE, NetworkInterfaceKind}; use nexus_db_model::{NetworkInterfaceKindEnum, SqlU8}; use omicron_common::api::external; use omicron_common::api::external::MacAddr; @@ -75,8 +75,7 @@ const INSTANCE_BAD_STATE_SENTINEL: &'static str = "bad-state"; // Error message generated when we're attempting to operate on an instance, // either inserting or deleting an interface, and that instance exists but is // in a state we can't work on. -const INSTANCE_BAD_STATE_ERROR_MESSAGE: &'static str = - "could not parse \"bad-state\" as type uuid: uuid: incorrect UUID length: bad-state"; +const INSTANCE_BAD_STATE_ERROR_MESSAGE: &'static str = "could not parse \"bad-state\" as type uuid: uuid: incorrect UUID length: bad-state"; // Uncastable sentinel used to detect when an instance doesn't exist const NO_INSTANCE_SENTINEL: &'static str = "no-instance"; @@ -85,8 +84,7 @@ const NO_INSTANCE_SENTINEL: &'static str = "no-instance"; // either inserting or deleting an interface, and that instance does not exist // at all or has been destroyed. These are the same thing from the point of view // of the client's API call. -const NO_INSTANCE_ERROR_MESSAGE: &'static str = - "could not parse \"no-instance\" as type uuid: uuid: incorrect UUID length: no-instance"; +const NO_INSTANCE_ERROR_MESSAGE: &'static str = "could not parse \"no-instance\" as type uuid: uuid: incorrect UUID length: no-instance"; /// Errors related to inserting or attaching a NetworkInterface #[derive(Debug)] @@ -152,16 +150,23 @@ impl InsertError { /// Convert this error into an external one. pub fn into_external(self) -> external::Error { match self { - InsertError::InterfaceAlreadyExists(name, NetworkInterfaceKind::Instance) => { - external::Error::ObjectAlreadyExists { - type_name: external::ResourceType::InstanceNetworkInterface, - object_name: name, - } - } - InsertError::InterfaceAlreadyExists(_name, NetworkInterfaceKind::Service) => { + InsertError::InterfaceAlreadyExists( + name, + NetworkInterfaceKind::Instance, + ) => external::Error::ObjectAlreadyExists { + type_name: external::ResourceType::InstanceNetworkInterface, + object_name: name, + }, + InsertError::InterfaceAlreadyExists( + _name, + NetworkInterfaceKind::Service, + ) => { unimplemented!("service network interface") } - InsertError::InterfaceAlreadyExists(_name, NetworkInterfaceKind::Probe) => { + InsertError::InterfaceAlreadyExists( + _name, + NetworkInterfaceKind::Probe, + ) => { unimplemented!("probe network interface") } InsertError::NoAvailableIpAddresses => { @@ -205,16 +210,19 @@ impl InsertError { } InsertError::NonUniqueVpcSubnets => { external::Error::invalid_request( - "Each interface must be in a distinct VPC Subnet" + "Each interface must be in a distinct VPC Subnet", ) } InsertError::InstanceMustBeStopped(_) => { external::Error::invalid_request( - "Instance must be stopped to attach a new network interface" + "Instance must be stopped to attach a new network interface", ) } InsertError::InstanceNotFound(id) => { - external::Error::not_found_by_id(external::ResourceType::Instance, &id) + external::Error::not_found_by_id( + external::ResourceType::Instance, + &id, + ) } InsertError::Retryable(err) => { public_error_from_diesel(err, ErrorHandler::Server) @@ -1748,8 +1756,7 @@ fn decode_delete_network_interface_database_error( // Error message generated when we're attempting to delete a primary // interface, and that instance also has one or more secondary interfaces - const HAS_SECONDARIES_ERROR_MESSAGE: &'static str = - "could not parse \"secondaries\" as type uuid: uuid: \ + const HAS_SECONDARIES_ERROR_MESSAGE: &'static str = "could not parse \"secondaries\" as type uuid: uuid: \ incorrect UUID length: secondaries"; match err { @@ -1790,11 +1797,11 @@ fn decode_delete_network_interface_database_error( #[cfg(test)] mod tests { - use super::first_available_address; use super::DeleteError; use super::InsertError; use super::MAX_NICS_PER_INSTANCE; use super::NUM_INITIAL_RESERVED_IP_ADDRESSES; + use super::first_available_address; use crate::authz; use crate::context::OpContext; use crate::db::datastore::DataStore; @@ -2713,7 +2720,10 @@ mod tests { ) .await; assert!( - matches!(result, Err(InsertError::ResourceSpansMultipleVpcs(_))), + matches!( + result, + Err(InsertError::ResourceSpansMultipleVpcs(_)) + ), "Attaching an interface to a resource which already has one in a different VPC should fail" ); } diff --git a/nexus/db-queries/src/db/queries/next_item.rs b/nexus/db-queries/src/db/queries/next_item.rs index be9cc7a7152..d3690d4cdb7 100644 --- a/nexus/db-queries/src/db/queries/next_item.rs +++ b/nexus/db-queries/src/db/queries/next_item.rs @@ -5,6 +5,7 @@ //! A generic query for selecting a unique next item from a table. use crate::db::DbConnection; +use diesel::RunQueryDsl; use diesel::associations::HasTable; use diesel::pg::Pg; use diesel::prelude::Column; @@ -16,7 +17,6 @@ use diesel::query_builder::QueryId; use diesel::serialize::ToSql; use diesel::sql_types; use diesel::sql_types::HasSqlType; -use diesel::RunQueryDsl; use std::marker::PhantomData; use uuid::Uuid; @@ -186,23 +186,17 @@ impl where // Table is a database table whose name can be used in a query fragment Table: diesel::Table + HasTable + QueryFragment + Copy, - // Item can be converted to the SQL type of the ItemColumn Item: ToSql<::SqlType, Pg> + Copy, - // ItemColum is a column in the target table ItemColumn: Column
+ Copy, - // ScopeKey can be converted to the SQL type of the ScopeColumn ScopeKey: ScopeKeyType + ToSql<::SqlType, Pg>, - // ScopeColumn is a column on the target table ScopeColumn: ScopeColumnType + Column
, - // The Postgres backend supports the SQL types of both columns Pg: HasSqlType<::SqlType> + HasSqlType<::SqlType>, - // We need an implementation to create the shifts from the base Generator: ShiftGenerator, { @@ -696,19 +690,14 @@ impl where // Table is a database table whose name can be used in a query fragment Table: diesel::Table + HasTable
+ QueryFragment + Copy, - // Item can be converted to the SQL type of the ItemColumn Item: ToSql<::SqlType, Pg> + Copy, - // ItemColum is a column in the target table ItemColumn: Column
+ Copy, - // ScopeKey can be converted to the SQL type of the ScopeColumn ScopeKey: ScopeKeyType + ToSql<::SqlType, Pg>, - // ScopeColumn is a column on the target table ScopeColumn: ScopeColumnType + Column
, - // The Postgres backend supports the SQL types of both columns Pg: HasSqlType<::SqlType> + HasSqlType<::SqlType>, @@ -931,13 +920,13 @@ mod tests { use async_bb8_diesel::AsyncSimpleConnection; use chrono::DateTime; use chrono::Utc; + use diesel::Column; + use diesel::Insertable; + use diesel::SelectableHelper; use diesel::pg::Pg; use diesel::query_builder::AstPass; use diesel::query_builder::QueryFragment; use diesel::query_builder::QueryId; - use diesel::Column; - use diesel::Insertable; - use diesel::SelectableHelper; use omicron_test_utils::dev; use uuid::Uuid; diff --git a/nexus/db-queries/src/db/queries/vpc.rs b/nexus/db-queries/src/db/queries/vpc.rs index 2875ae6a05c..1e8bf620578 100644 --- a/nexus/db-queries/src/db/queries/vpc.rs +++ b/nexus/db-queries/src/db/queries/vpc.rs @@ -14,13 +14,13 @@ use crate::db::schema::vpc; use crate::db::schema::vpc::dsl; use chrono::DateTime; use chrono::Utc; +use diesel::Column; +use diesel::Insertable; use diesel::pg::Pg; use diesel::query_builder::AstPass; use diesel::query_builder::QueryFragment; use diesel::query_builder::QueryId; use diesel::sql_types; -use diesel::Column; -use diesel::Insertable; use ipnetwork::IpNetwork; use omicron_common::api::external; use uuid::Uuid; @@ -382,11 +382,11 @@ impl std::iter::Iterator for VniSearchIter { #[cfg(test)] mod tests { - use super::external; + use super::MAX_VNI_SEARCH_RANGE_SIZE; use super::Vni; use super::VniSearchIter; use super::VniShifts; - use super::MAX_VNI_SEARCH_RANGE_SIZE; + use super::external; // Ensure that when the search range lies entirely within the range of VNIs, // we search from the start VNI through the maximum allowed range size. @@ -440,11 +440,7 @@ mod tests { pub const fn div_ceil(x: u32, y: u32) -> u32 { let d = x / y; let r = x % y; - if r > 0 && y > 0 { - d + 1 - } else { - d - } + if r > 0 && y > 0 { d + 1 } else { d } } const N_EXPECTED: u32 = div_ceil( external::Vni::MAX_VNI - external::Vni::MIN_GUEST_VNI, diff --git a/nexus/db-queries/src/db/queries/vpc_subnet.rs b/nexus/db-queries/src/db/queries/vpc_subnet.rs index 54c03f592e0..d1e9e6b189f 100644 --- a/nexus/db-queries/src/db/queries/vpc_subnet.rs +++ b/nexus/db-queries/src/db/queries/vpc_subnet.rs @@ -5,10 +5,10 @@ //! Diesel query used for VPC Subnet allocation and insertion use crate::db; +use crate::db::DbConnection; use crate::db::identity::Resource; use crate::db::model::VpcSubnet; use crate::db::schema::vpc_subnet::dsl; -use crate::db::DbConnection; use diesel::pg::Pg; use diesel::prelude::*; use diesel::query_builder::*; diff --git a/nexus/db-queries/src/db/raw_query_builder.rs b/nexus/db-queries/src/db/raw_query_builder.rs index d1080628332..9714e71a7a4 100644 --- a/nexus/db-queries/src/db/raw_query_builder.rs +++ b/nexus/db-queries/src/db/raw_query_builder.rs @@ -8,10 +8,10 @@ //! and are recommended for more complex CTE use crate::db::pool::DbConnection; +use diesel::RunQueryDsl; use diesel::pg::Pg; use diesel::query_builder::{AstPass, Query, QueryFragment, QueryId}; use diesel::sql_types; -use diesel::RunQueryDsl; use std::cell::Cell; use std::marker::PhantomData; diff --git a/nexus/db-queries/src/db/test_utils/unpluggable_sec_store.rs b/nexus/db-queries/src/db/test_utils/unpluggable_sec_store.rs index b2092e7ef8a..2a92d61bd0d 100644 --- a/nexus/db-queries/src/db/test_utils/unpluggable_sec_store.rs +++ b/nexus/db-queries/src/db/test_utils/unpluggable_sec_store.rs @@ -7,8 +7,8 @@ use crate::db; use async_trait::async_trait; use std::sync::{ - atomic::{AtomicBool, Ordering}, Arc, + atomic::{AtomicBool, Ordering}, }; /// A thin wrapper around [`db::CockroachDbSecStore`] that lets diff --git a/nexus/db-queries/src/db/true_or_cast_error.rs b/nexus/db-queries/src/db/true_or_cast_error.rs index 6d7b2a1dbd9..656699aa873 100644 --- a/nexus/db-queries/src/db/true_or_cast_error.rs +++ b/nexus/db-queries/src/db/true_or_cast_error.rs @@ -4,14 +4,14 @@ //! An expression wrapper for forcing errors from CTEs. +use diesel::Expression; +use diesel::SelectableExpression; use diesel::expression::ValidGrouping; use diesel::pg::Pg; use diesel::query_builder::AstPass; use diesel::query_builder::QueryFragment; use diesel::query_builder::QueryId; use diesel::result::Error as DieselError; -use diesel::Expression; -use diesel::SelectableExpression; /// Generates a wrapper around a boolean expression. /// diff --git a/nexus/db-queries/src/db/update_and_check.rs b/nexus/db-queries/src/db/update_and_check.rs index fed79d5254a..dd90345138e 100644 --- a/nexus/db-queries/src/db/update_and_check.rs +++ b/nexus/db-queries/src/db/update_and_check.rs @@ -7,6 +7,7 @@ use super::column_walker::ColumnWalker; use super::pool::DbConnection; use async_bb8_diesel::AsyncRunQueryDsl; +use diesel::QuerySource; use diesel::associations::HasTable; use diesel::pg::Pg; use diesel::prelude::*; @@ -15,7 +16,6 @@ use diesel::query_dsl::methods::LoadQuery; use diesel::query_source::Table; use diesel::result::Error as DieselError; use diesel::sql_types::Nullable; -use diesel::QuerySource; use std::marker::PhantomData; /// A simple wrapper type for Diesel's [`UpdateStatement`], which diff --git a/nexus/db-queries/src/policy_test/resource_builder.rs b/nexus/db-queries/src/policy_test/resource_builder.rs index b6d7d97553e..b2391e4f0d3 100644 --- a/nexus/db-queries/src/policy_test/resource_builder.rs +++ b/nexus/db-queries/src/policy_test/resource_builder.rs @@ -8,8 +8,8 @@ use super::coverage::Coverage; use crate::db; use authz::ApiResource; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_auth::authz; use nexus_auth::authz::ApiResourceWithRolesType; use nexus_auth::authz::AuthorizedResource; diff --git a/nexus/db-queries/src/provisioning.rs b/nexus/db-queries/src/provisioning.rs index d686eaa32b9..31f8c5f99d0 100644 --- a/nexus/db-queries/src/provisioning.rs +++ b/nexus/db-queries/src/provisioning.rs @@ -5,7 +5,7 @@ //! Types to export metrics about provisioning information. use crate::db::model::VirtualProvisioningCollection; -use oximeter::{types::Sample, MetricsError}; +use oximeter::{MetricsError, types::Sample}; use std::sync::{Arc, Mutex}; oximeter::use_timeseries!("collection-target.toml"); diff --git a/nexus/db-queries/src/transaction_retry.rs b/nexus/db-queries/src/transaction_retry.rs index cf8ee223767..09cf8c240f6 100644 --- a/nexus/db-queries/src/transaction_retry.rs +++ b/nexus/db-queries/src/transaction_retry.rs @@ -7,9 +7,9 @@ use async_bb8_diesel::AsyncConnection; use chrono::Utc; use diesel::result::Error as DieselError; -use oximeter::{types::Sample, MetricsError}; -use rand::{thread_rng, Rng}; -use slog::{info, warn, Logger}; +use oximeter::{MetricsError, types::Sample}; +use rand::{Rng, thread_rng}; +use slog::{Logger, info, warn}; use std::sync::{Arc, Mutex}; use std::time::Duration; diff --git a/nexus/internal-api/src/lib.rs b/nexus/internal-api/src/lib.rs index 87a6bd7553b..bcf84fd5079 100644 --- a/nexus/internal-api/src/lib.rs +++ b/nexus/internal-api/src/lib.rs @@ -28,7 +28,7 @@ use nexus_types::{ }, }; use omicron_common::api::{ - external::{http_pagination::PaginatedById, Instance}, + external::{Instance, http_pagination::PaginatedById}, internal::nexus::{ DiskRuntimeState, DownstairsClientStopRequest, DownstairsClientStopped, ProducerEndpoint, ProducerRegistrationResponse, RepairFinishInfo, diff --git a/nexus/inventory/src/builder.rs b/nexus/inventory/src/builder.rs index e54b0c10ae3..3d4e94be1db 100644 --- a/nexus/inventory/src/builder.rs +++ b/nexus/inventory/src/builder.rs @@ -583,13 +583,13 @@ pub fn now_db_precision() -> DateTime { #[cfg(test)] mod test { - use super::now_db_precision; use super::CollectionBuilder; + use super::now_db_precision; + use crate::examples::Representative; use crate::examples::representative; use crate::examples::sp_state; - use crate::examples::Representative; - use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use base64::Engine; + use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use gateway_client::types::PowerState; use gateway_client::types::RotSlot; use gateway_client::types::RotState; @@ -651,7 +651,12 @@ mod test { switch, psc, sled_agents: - [sled_agent_id_basic, sled_agent_id_extra, sled_agent_id_pc, sled_agent_id_unknown], + [ + sled_agent_id_basic, + sled_agent_id_extra, + sled_agent_id_pc, + sled_agent_id_unknown, + ], } = representative(); let collection = builder.build(); let time_after = now_db_precision(); @@ -808,18 +813,24 @@ mod test { assert_eq!(rot.transient_boot_preference, Some(RotSlot::B)); // sled 2 did not have any RoT pages reported - assert!(collection - .rot_page_for(RotPageWhich::Cmpa, &sled2_bb) - .is_none()); - assert!(collection - .rot_page_for(RotPageWhich::CfpaActive, &sled2_bb) - .is_none()); - assert!(collection - .rot_page_for(RotPageWhich::CfpaInactive, &sled2_bb) - .is_none()); - assert!(collection - .rot_page_for(RotPageWhich::CfpaScratch, &sled2_bb) - .is_none()); + assert!( + collection.rot_page_for(RotPageWhich::Cmpa, &sled2_bb).is_none() + ); + assert!( + collection + .rot_page_for(RotPageWhich::CfpaActive, &sled2_bb) + .is_none() + ); + assert!( + collection + .rot_page_for(RotPageWhich::CfpaInactive, &sled2_bb) + .is_none() + ); + assert!( + collection + .rot_page_for(RotPageWhich::CfpaScratch, &sled2_bb) + .is_none() + ); // switch let sp = collection.sps.get(&switch).unwrap(); @@ -932,12 +943,12 @@ mod test { assert_eq!(sp.baseboard_revision, 1); assert_eq!(sp.hubris_archive, "hubris5"); assert_eq!(sp.power_state, PowerState::A2); - assert!(collection - .caboose_for(CabooseWhich::SpSlot0, &sled3_bb) - .is_none()); - assert!(collection - .caboose_for(CabooseWhich::SpSlot1, &sled3_bb) - .is_none()); + assert!( + collection.caboose_for(CabooseWhich::SpSlot0, &sled3_bb).is_none() + ); + assert!( + collection.caboose_for(CabooseWhich::SpSlot1, &sled3_bb).is_none() + ); assert!(!collection.rots.contains_key(&sled3_bb)); // There shouldn't be any other RoTs. @@ -982,12 +993,14 @@ mod test { let sled4_agent = &collection.sled_agents[&sled_agent_id_extra]; let sled4_bb = sled4_agent.baseboard_id.as_ref().unwrap(); assert_eq!(sled4_bb.serial_number, "s4"); - assert!(collection.sled_agents[&sled_agent_id_pc] - .baseboard_id - .is_none()); - assert!(collection.sled_agents[&sled_agent_id_unknown] - .baseboard_id - .is_none()); + assert!( + collection.sled_agents[&sled_agent_id_pc].baseboard_id.is_none() + ); + assert!( + collection.sled_agents[&sled_agent_id_unknown] + .baseboard_id + .is_none() + ); } // Exercises all the failure cases that shouldn't happen in real systems. @@ -1095,8 +1108,10 @@ mod test { sign: None, epoch: None, }; - assert!(!builder - .found_caboose_already(&bogus_baseboard, CabooseWhich::SpSlot0)); + assert!( + !builder + .found_caboose_already(&bogus_baseboard, CabooseWhich::SpSlot0) + ); let error = builder .found_caboose( &bogus_baseboard, @@ -1112,8 +1127,10 @@ mod test { (Caboose { board: \"board1\", git_commit: \"git_commit1\", \ name: \"name1\", version: \"version1\" })" ); - assert!(!builder - .found_caboose_already(&bogus_baseboard, CabooseWhich::SpSlot0)); + assert!( + !builder + .found_caboose_already(&bogus_baseboard, CabooseWhich::SpSlot0) + ); // report RoT caboose for an unknown baseboard let error2 = builder @@ -1175,8 +1192,10 @@ mod test { // report RoT page for an unknown baseboard let rot_page1 = RotPage { data_base64: "page1".to_string() }; let rot_page2 = RotPage { data_base64: "page2".to_string() }; - assert!(!builder - .found_rot_page_already(&bogus_baseboard, RotPageWhich::Cmpa)); + assert!( + !builder + .found_rot_page_already(&bogus_baseboard, RotPageWhich::Cmpa) + ); let error = builder .found_rot_page( &bogus_baseboard, @@ -1191,8 +1210,10 @@ mod test { BaseboardId { part_number: \"p1\", serial_number: \"bogus\" } \ (RotPage { data_base64: \"page1\" })" ); - assert!(!builder - .found_rot_page_already(&bogus_baseboard, RotPageWhich::Cmpa)); + assert!( + !builder + .found_rot_page_already(&bogus_baseboard, RotPageWhich::Cmpa) + ); // report the same rot page twice with the same contents builder @@ -1246,16 +1267,16 @@ mod test { collection.caboose_for(CabooseWhich::SpSlot0, &sled1_bb).unwrap(); assert_eq!(caboose.caboose.board, "board2"); assert!(collection.cabooses.contains(&caboose.caboose)); - assert!(collection - .caboose_for(CabooseWhich::SpSlot1, &sled1_bb) - .is_none()); + assert!( + collection.caboose_for(CabooseWhich::SpSlot1, &sled1_bb).is_none() + ); let _ = collection.rots.get(&sled1_bb).unwrap(); - assert!(collection - .caboose_for(CabooseWhich::RotSlotA, &sled1_bb) - .is_none()); - assert!(collection - .caboose_for(CabooseWhich::RotSlotB, &sled1_bb) - .is_none()); + assert!( + collection.caboose_for(CabooseWhich::RotSlotA, &sled1_bb).is_none() + ); + assert!( + collection.caboose_for(CabooseWhich::RotSlotB, &sled1_bb).is_none() + ); let rot_page = collection.rot_page_for(RotPageWhich::Cmpa, &sled1_bb).unwrap(); assert!(collection.rot_pages.contains(&rot_page.page)); @@ -1269,15 +1290,21 @@ mod test { // data. assert_eq!(rot_page.page.data_base64, rot_page2.data_base64); - assert!(collection - .rot_page_for(RotPageWhich::CfpaActive, &sled1_bb) - .is_none()); - assert!(collection - .rot_page_for(RotPageWhich::CfpaInactive, &sled1_bb) - .is_none()); - assert!(collection - .rot_page_for(RotPageWhich::CfpaScratch, &sled1_bb) - .is_none()); + assert!( + collection + .rot_page_for(RotPageWhich::CfpaActive, &sled1_bb) + .is_none() + ); + assert!( + collection + .rot_page_for(RotPageWhich::CfpaInactive, &sled1_bb) + .is_none() + ); + assert!( + collection + .rot_page_for(RotPageWhich::CfpaScratch, &sled1_bb) + .is_none() + ); // We should see an error. assert_eq!( diff --git a/nexus/inventory/src/collector.rs b/nexus/inventory/src/collector.rs index d14eb9ce8fb..92d0e89c2fc 100644 --- a/nexus/inventory/src/collector.rs +++ b/nexus/inventory/src/collector.rs @@ -4,9 +4,9 @@ //! Collection of inventory from Omicron components +use crate::SledAgentEnumerator; use crate::builder::CollectionBuilder; use crate::builder::InventoryError; -use crate::SledAgentEnumerator; use anyhow::Context; use gateway_client::types::GetCfpaParams; use gateway_client::types::RotCfpaSlot; @@ -15,8 +15,8 @@ use nexus_types::inventory::CabooseWhich; use nexus_types::inventory::Collection; use nexus_types::inventory::RotPage; use nexus_types::inventory::RotPageWhich; -use slog::o; use slog::Logger; +use slog::o; use slog::{debug, error}; use std::time::Duration; use strum::IntoEnumIterator; diff --git a/nexus/inventory/src/sled_agent_enumerator.rs b/nexus/inventory/src/sled_agent_enumerator.rs index 8a1b480e3f2..7764b7daa5d 100644 --- a/nexus/inventory/src/sled_agent_enumerator.rs +++ b/nexus/inventory/src/sled_agent_enumerator.rs @@ -3,8 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::InventoryError; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; /// Describes how to find the list of sled agents to collect from /// diff --git a/nexus/metrics-producer-gc/src/lib.rs b/nexus/metrics-producer-gc/src/lib.rs index 27ef73f75a4..f6462f72d5c 100644 --- a/nexus/metrics-producer-gc/src/lib.rs +++ b/nexus/metrics-producer-gc/src/lib.rs @@ -12,22 +12,22 @@ use chrono::DateTime; use chrono::Utc; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::identity::Asset; use nexus_db_queries::db::model::ProducerEndpoint; -use nexus_db_queries::db::DataStore; use omicron_common::api::external::Error as DbError; use oximeter_client::Client as OximeterClient; +use slog::Logger; use slog::info; use slog::o; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; use std::net::SocketAddr; use uuid::Uuid; @@ -180,9 +180,9 @@ mod tests { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::ExpressionMethods; use diesel::QueryDsl; + use httptest::Expectation; use httptest::matchers::request; use httptest::responders::status_code; - use httptest::Expectation; use nexus_db_model::OximeterInfo; use nexus_db_queries::db::pub_test_utils::TestDatabase; use nexus_types::internal_api::params; diff --git a/nexus/networking/src/firewall_rules.rs b/nexus/networking/src/firewall_rules.rs index 8491092353c..ea51ec8f710 100644 --- a/nexus/networking/src/firewall_rules.rs +++ b/nexus/networking/src/firewall_rules.rs @@ -9,6 +9,7 @@ use ipnetwork::IpNetwork; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::fixed_data::vpc::SERVICES_VPC_ID; use nexus_db_queries::db::fixed_data::vpc_firewall_rule::NEXUS_VPC_FW_RULE_NAME; use nexus_db_queries::db::identity::Asset; @@ -16,7 +17,6 @@ use nexus_db_queries::db::identity::Resource; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::Name; -use nexus_db_queries::db::DataStore; use omicron_common::api::external; use omicron_common::api::external::AllowedSourceIps; use omicron_common::api::external::Error; @@ -24,11 +24,11 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::internal::nexus::HostIdentifier; use omicron_common::api::internal::shared::NetworkInterface; use oxnet::IpNet; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::warn; -use slog::Logger; use std::collections::{HashMap, HashSet}; use std::net::IpAddr; use uuid::Uuid; @@ -344,7 +344,7 @@ pub async fn resolve_firewall_rules_for_sled_agent( are expected to have no built-in rules which filter on \ the hosts, so that we can modify the rules to apply the \ allowlist without worrying about destroying those built-in \ - host filters." + host filters.", )); } @@ -426,7 +426,7 @@ pub async fn resolve_firewall_rules_for_sled_agent( filter_ports, filter_protocols, action: rule.action.0.into(), - priority: rule.priority.0 .0, + priority: rule.priority.0.0, }, ); } diff --git a/nexus/networking/src/sled_client.rs b/nexus/networking/src/sled_client.rs index 073f073356c..98edd3d5619 100644 --- a/nexus/networking/src/sled_client.rs +++ b/nexus/networking/src/sled_client.rs @@ -5,14 +5,14 @@ //! Functionality for constructing sled-agent clients. use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; -use nexus_db_queries::db::DataStore; use omicron_common::api::external::Error; use omicron_common::api::external::LookupResult; use sled_agent_client::Client as SledAgentClient; -use slog::o; use slog::Logger; +use slog::o; use std::net::SocketAddrV6; use uuid::Uuid; diff --git a/nexus/reconfigurator/blippy/src/checks.rs b/nexus/reconfigurator/blippy/src/checks.rs index 2c56fce1d25..3422bd557ee 100644 --- a/nexus/reconfigurator/blippy/src/checks.rs +++ b/nexus/reconfigurator/blippy/src/checks.rs @@ -7,13 +7,13 @@ use crate::blippy::MultimapInconsistency; use crate::blippy::Severity; use crate::blippy::SledKind; use nexus_sled_agent_shared::inventory::ZoneKind; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetFilter; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::OmicronZoneExternalIp; +use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::views::SledState; use omicron_common::address::DnsSubnet; use omicron_common::address::Ipv6Subnet; @@ -21,9 +21,9 @@ use omicron_common::address::SLED_PREFIX; use omicron_common::disk::DatasetKind; use omicron_uuid_kinds::SledUuid; use omicron_uuid_kinds::ZpoolUuid; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; use std::net::Ipv6Addr; pub(crate) fn perform_all_blueprint_only_checks(blippy: &mut Blippy<'_>) { @@ -706,13 +706,13 @@ fn check_datasets(blippy: &mut Blippy<'_>) { #[cfg(test)] mod tests { use super::*; + use crate::BlippyReportSortKey; use crate::blippy::Kind; use crate::blippy::Note; - use crate::BlippyReportSortKey; - use nexus_reconfigurator_planning::example::example; use nexus_reconfigurator_planning::example::ExampleSystemBuilder; - use nexus_types::deployment::blueprint_zone_type; + use nexus_reconfigurator_planning::example::example; use nexus_types::deployment::BlueprintZoneType; + use nexus_types::deployment::blueprint_zone_type; use omicron_test_utils::dev::test_setup_log; use std::mem; diff --git a/nexus/reconfigurator/execution/src/clickhouse.rs b/nexus/reconfigurator/execution/src/clickhouse.rs index 262e686a457..764dfdb8bf7 100644 --- a/nexus/reconfigurator/execution/src/clickhouse.rs +++ b/nexus/reconfigurator/execution/src/clickhouse.rs @@ -10,14 +10,14 @@ use camino::Utf8PathBuf; use clickhouse_admin_keeper_client::Client as ClickhouseKeeperClient; use clickhouse_admin_server_client::Client as ClickhouseServerClient; use clickhouse_admin_single_client::Client as ClickhouseSingleClient; +use clickhouse_admin_types::CLICKHOUSE_KEEPER_CONFIG_DIR; +use clickhouse_admin_types::CLICKHOUSE_SERVER_CONFIG_DIR; use clickhouse_admin_types::ClickhouseHost; use clickhouse_admin_types::KeeperConfigurableSettings; use clickhouse_admin_types::KeeperSettings; use clickhouse_admin_types::RaftServerSettings; use clickhouse_admin_types::ServerConfigurableSettings; use clickhouse_admin_types::ServerSettings; -use clickhouse_admin_types::CLICKHOUSE_KEEPER_CONFIG_DIR; -use clickhouse_admin_types::CLICKHOUSE_SERVER_CONFIG_DIR; use futures::future::Either; use futures::stream::FuturesUnordered; use futures::stream::StreamExt; @@ -333,18 +333,17 @@ mod test { use clickhouse_admin_types::KeeperId; use clickhouse_admin_types::ServerId; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; - use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; + use nexus_types::deployment::blueprint_zone_type; use nexus_types::inventory::ZpoolName; use omicron_common::api::external::Generation; use omicron_uuid_kinds::ZpoolUuid; use std::collections::BTreeSet; - fn test_data( - ) -> (BTreeMap, ClickhouseClusterConfig) - { + fn test_data() + -> (BTreeMap, ClickhouseClusterConfig) { let num_keepers = 3u64; let num_servers = 2u64; diff --git a/nexus/reconfigurator/execution/src/datasets.rs b/nexus/reconfigurator/execution/src/datasets.rs index 92506718bc0..ae8a699e531 100644 --- a/nexus/reconfigurator/execution/src/datasets.rs +++ b/nexus/reconfigurator/execution/src/datasets.rs @@ -6,10 +6,10 @@ use crate::Sled; -use anyhow::anyhow; use anyhow::Context; -use futures::stream; +use anyhow::anyhow; use futures::StreamExt; +use futures::stream; use nexus_db_queries::context::OpContext; use nexus_types::deployment::BlueprintDatasetsConfig; use omicron_common::disk::DatasetsConfig; @@ -94,11 +94,7 @@ pub(crate) async fn deploy_datasets( .collect() .await; - if errors.is_empty() { - Ok(()) - } else { - Err(errors) - } + if errors.is_empty() { Ok(()) } else { Err(errors) } } #[cfg(test)] @@ -106,10 +102,10 @@ mod tests { use super::*; use nexus_sled_agent_shared::inventory::SledRole; use nexus_test_utils_macros::nexus_test; - use nexus_types::deployment::id_map::IdMap; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::deployment::BlueprintDatasetsConfig; + use nexus_types::deployment::id_map::IdMap; use omicron_common::api::external::Generation; use omicron_common::api::internal::shared::DatasetKind; use omicron_common::disk::CompressionAlgorithm; diff --git a/nexus/reconfigurator/execution/src/dns.rs b/nexus/reconfigurator/execution/src/dns.rs index af3fca7b179..3006a569f93 100644 --- a/nexus/reconfigurator/execution/src/dns.rs +++ b/nexus/reconfigurator/execution/src/dns.rs @@ -8,13 +8,13 @@ use crate::Sled; use internal_dns_types::diff::DnsDiff; use nexus_db_model::DnsGroup; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::Discoverability; use nexus_db_queries::db::datastore::DnsVersionUpdateBuilder; -use nexus_db_queries::db::DataStore; +use nexus_types::deployment::Blueprint; +use nexus_types::deployment::execution::Overridables; use nexus_types::deployment::execution::blueprint_external_dns_config; use nexus_types::deployment::execution::blueprint_internal_dns_config; -use nexus_types::deployment::execution::Overridables; -use nexus_types::deployment::Blueprint; use nexus_types::identity::Resource; use nexus_types::internal_api::params::DnsConfigParams; use nexus_types::internal_api::params::DnsConfigZone; @@ -297,23 +297,23 @@ fn dns_compute_update( #[cfg(test)] mod test { use super::*; + use crate::Sled; use crate::test_utils::overridables_for_test; use crate::test_utils::realize_blueprint_and_expect; - use crate::Sled; use internal_dns_resolver::Resolver; use internal_dns_types::config::Host; use internal_dns_types::config::Zone; - use internal_dns_types::names::ServiceName; use internal_dns_types::names::BOUNDARY_NTP_DNS_NAME; use internal_dns_types::names::DNS_ZONE; + use internal_dns_types::names::ServiceName; use nexus_db_model::DnsGroup; use nexus_db_model::Silo; use nexus_db_queries::authn; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; - use nexus_inventory::now_db_precision; use nexus_inventory::CollectionBuilder; + use nexus_inventory::now_db_precision; use nexus_reconfigurator_planning::blueprint_builder::BlueprintBuilder; use nexus_reconfigurator_planning::example::ExampleSystemBuilder; use nexus_reconfigurator_preparation::PlanningInputFromDb; @@ -321,10 +321,9 @@ mod test { use nexus_sled_agent_shared::inventory::OmicronZoneType; use nexus_sled_agent_shared::inventory::SledRole; use nexus_sled_agent_shared::inventory::ZoneKind; - use nexus_test_utils::resource_helpers::create_silo; use nexus_test_utils::resource_helpers::DiskTest; + use nexus_test_utils::resource_helpers::create_silo; use nexus_test_utils_macros::nexus_test; - use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintTarget; use nexus_types::deployment::BlueprintZoneConfig; @@ -338,6 +337,7 @@ mod test { pub use nexus_types::deployment::OmicronZoneExternalFloatingIp; pub use nexus_types::deployment::OmicronZoneExternalSnatIp; use nexus_types::deployment::SledFilter; + use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::params; use nexus_types::external_api::shared; use nexus_types::external_api::views::SledState; @@ -347,12 +347,12 @@ mod test { use nexus_types::internal_api::params::DnsRecord; use nexus_types::internal_api::params::Srv; use nexus_types::silo::silo_dns_name; - use omicron_common::address::get_sled_address; - use omicron_common::address::get_switch_zone_address; use omicron_common::address::IpRange; use omicron_common::address::Ipv6Subnet; use omicron_common::address::RACK_PREFIX; use omicron_common::address::SLED_PREFIX; + use omicron_common::address::get_sled_address; + use omicron_common::address::get_switch_zone_address; use omicron_common::api::external::Generation; use omicron_common::api::external::IdentityMetadataCreateParams; use omicron_common::policy::BOUNDARY_NTP_REDUNDANCY; @@ -763,9 +763,9 @@ mod test { println!("omicron zones by IP: {:#?}", omicron_zones_by_ip); // Check to see that the out-of-service zone was actually excluded - assert!(omicron_zones_by_ip - .values() - .all(|id| *id != out_of_service_id)); + assert!( + omicron_zones_by_ip.values().all(|id| *id != out_of_service_id) + ); // We also want a mapping from underlay IP to the corresponding switch // zone. In this case, the value is the Scrimlet's sled id. diff --git a/nexus/reconfigurator/execution/src/lib.rs b/nexus/reconfigurator/execution/src/lib.rs index 79116b58f3c..25a8121ff61 100644 --- a/nexus/reconfigurator/execution/src/lib.rs +++ b/nexus/reconfigurator/execution/src/lib.rs @@ -6,14 +6,14 @@ //! //! See `nexus_reconfigurator_planning` crate-level docs for background. -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use internal_dns_resolver::Resolver; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; -use nexus_types::deployment::execution::*; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::SledFilter; +use nexus_types::deployment::execution::*; use nexus_types::external_api::views::SledState; use nexus_types::identity::Asset; use omicron_physical_disks::DeployDisksDone; @@ -26,8 +26,8 @@ use slog_error_chain::InlineErrorChain; use std::collections::BTreeMap; use std::sync::Arc; use tokio::sync::mpsc; -use update_engine::merge_anyhow_list; use update_engine::StepWarning; +use update_engine::merge_anyhow_list; mod clickhouse; mod cockroachdb; diff --git a/nexus/reconfigurator/execution/src/omicron_physical_disks.rs b/nexus/reconfigurator/execution/src/omicron_physical_disks.rs index 6655eeb8b62..d640adc2183 100644 --- a/nexus/reconfigurator/execution/src/omicron_physical_disks.rs +++ b/nexus/reconfigurator/execution/src/omicron_physical_disks.rs @@ -5,10 +5,10 @@ //! Manges deployment of Omicron physical disks to Sled Agents. use crate::Sled; -use anyhow::anyhow; use anyhow::Context; -use futures::stream; +use anyhow::anyhow; use futures::StreamExt; +use futures::stream; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_types::deployment::BlueprintPhysicalDisksConfig; @@ -95,11 +95,7 @@ pub(crate) async fn deploy_disks( .collect() .await; - if errors.is_empty() { - Ok(DeployDisksDone {}) - } else { - Err(errors) - } + if errors.is_empty() { Ok(DeployDisksDone {}) } else { Err(errors) } } /// Typestate indicating that the deploy disks step was performed. @@ -126,18 +122,18 @@ pub(crate) async fn decommission_expunged_disks( #[cfg(test)] mod test { - use super::deploy_disks; use super::DeployDisksDone; + use super::deploy_disks; use crate::DataStore; use crate::Sled; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::ExpressionMethods; use diesel::QueryDsl; + use httptest::Expectation; use httptest::matchers::{all_of, json_decoded, request}; use httptest::responders::json_encoded; use httptest::responders::status_code; - use httptest::Expectation; use nexus_db_model::CrucibleDataset; use nexus_db_model::PhysicalDisk; use nexus_db_model::PhysicalDiskKind; @@ -351,9 +347,11 @@ mod test { println!("{:?}", errors); assert_eq!(errors.len(), 1); - assert!(errors[0] - .to_string() - .starts_with("Failed to put BlueprintPhysicalDisksConfig")); + assert!( + errors[0] + .to_string() + .starts_with("Failed to put BlueprintPhysicalDisksConfig") + ); s1.verify_and_clear(); s2.verify_and_clear(); diff --git a/nexus/reconfigurator/execution/src/omicron_zones.rs b/nexus/reconfigurator/execution/src/omicron_zones.rs index 5ef93e950c8..a87d6aa9579 100644 --- a/nexus/reconfigurator/execution/src/omicron_zones.rs +++ b/nexus/reconfigurator/execution/src/omicron_zones.rs @@ -5,18 +5,18 @@ //! Manages deployment of Omicron zones to Sled Agents use crate::Sled; +use anyhow::Context; use anyhow::anyhow; use anyhow::bail; -use anyhow::Context; use cockroach_admin_client::types::NodeDecommission; use cockroach_admin_client::types::NodeId; -use futures::stream; use futures::StreamExt; +use futures::stream; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::datastore::CollectorReassignment; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::datastore::CollectorReassignment; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; @@ -25,9 +25,9 @@ use omicron_common::address::COCKROACH_ADMIN_PORT; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::SledUuid; +use slog::Logger; use slog::info; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; use std::collections::BTreeMap; use std::net::SocketAddr; @@ -98,11 +98,7 @@ pub(crate) async fn deploy_zones( .collect() .await; - if errors.is_empty() { - Ok(DeployZonesDone(())) - } else { - Err(errors) - } + if errors.is_empty() { Ok(DeployZonesDone(())) } else { Err(errors) } } /// Idempontently perform any cleanup actions necessary for expunged zones. @@ -186,11 +182,7 @@ pub(crate) async fn clean_up_expunged_zones( .collect() .await; - if errors.is_empty() { - Ok(()) - } else { - Err(errors) - } + if errors.is_empty() { Ok(()) } else { Err(errors) } } async fn oximeter_cleanup( @@ -358,16 +350,16 @@ mod test { use super::*; use crate::Sled; use cockroach_admin_client::types::NodeMembership; + use httptest::Expectation; use httptest::matchers::{all_of, json_decoded, request}; use httptest::responders::{json_encoded, status_code}; - use httptest::Expectation; use nexus_sled_agent_shared::inventory::{ OmicronZoneDataset, OmicronZonesConfig, SledRole, }; use nexus_test_utils_macros::nexus_test; use nexus_types::deployment::{ - blueprint_zone_type, Blueprint, BlueprintTarget, - CockroachDbPreserveDowngrade, + Blueprint, BlueprintTarget, CockroachDbPreserveDowngrade, + blueprint_zone_type, }; use omicron_common::api::external::Generation; use omicron_common::zpool_name::ZpoolName; @@ -547,9 +539,11 @@ mod test { println!("{:?}", errors); assert_eq!(errors.len(), 1); - assert!(errors[0] - .to_string() - .starts_with("Failed to put OmicronZonesConfig")); + assert!( + errors[0] + .to_string() + .starts_with("Failed to put OmicronZonesConfig") + ); s1.verify_and_clear(); s2.verify_and_clear(); diff --git a/nexus/reconfigurator/execution/src/sled_state.rs b/nexus/reconfigurator/execution/src/sled_state.rs index fafc1c2e44c..fa21e9271f9 100644 --- a/nexus/reconfigurator/execution/src/sled_state.rs +++ b/nexus/reconfigurator/execution/src/sled_state.rs @@ -8,9 +8,9 @@ use anyhow::Context; use nexus_db_model::SledState; use nexus_db_queries::authz::Action; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::TransitionError; use nexus_db_queries::db::lookup::LookupPath; -use nexus_db_queries::db::DataStore; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::SledUuid; @@ -28,11 +28,7 @@ pub(crate) async fn decommission_sleds( } } - if errors.is_empty() { - Ok(()) - } else { - Err(errors) - } + if errors.is_empty() { Ok(()) } else { Err(errors) } } async fn decommission_one_sled( diff --git a/nexus/reconfigurator/execution/src/test_utils.rs b/nexus/reconfigurator/execution/src/test_utils.rs index 4e7521dce18..fd89a04fda8 100644 --- a/nexus/reconfigurator/execution/src/test_utils.rs +++ b/nexus/reconfigurator/execution/src/test_utils.rs @@ -9,8 +9,8 @@ use std::net::Ipv6Addr; use internal_dns_resolver::Resolver; use nexus_db_queries::{context::OpContext, db::DataStore}; use nexus_types::deployment::{ - execution::{EventBuffer, Overridables}, Blueprint, + execution::{EventBuffer, Overridables}, }; use omicron_uuid_kinds::OmicronZoneUuid; use update_engine::TerminalKind; diff --git a/nexus/reconfigurator/planning/src/blueprint_builder/builder.rs b/nexus/reconfigurator/planning/src/blueprint_builder/builder.rs index 15d85744f2a..a3248231be5 100644 --- a/nexus/reconfigurator/planning/src/blueprint_builder/builder.rs +++ b/nexus/reconfigurator/planning/src/blueprint_builder/builder.rs @@ -14,18 +14,16 @@ use crate::blueprint_editor::ExternalSnatNetworkingChoice; use crate::blueprint_editor::InternalDnsError; use crate::blueprint_editor::SledEditError; use crate::blueprint_editor::SledEditor; -use crate::planner::rng::PlannerRng; use crate::planner::ZoneExpungeReason; +use crate::planner::rng::PlannerRng; +use anyhow::Context as _; use anyhow::anyhow; use anyhow::bail; -use anyhow::Context as _; use clickhouse_admin_types::OXIMETER_CLUSTER; use itertools::Either; use nexus_inventory::now_db_precision; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; use nexus_sled_agent_shared::inventory::ZoneKind; -use nexus_types::deployment::blueprint_zone_type; -use nexus_types::deployment::id_map::IdMap; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::deployment::BlueprintDatasetFilter; @@ -48,13 +46,15 @@ use nexus_types::deployment::SledFilter; use nexus_types::deployment::SledResources; use nexus_types::deployment::ZpoolFilter; use nexus_types::deployment::ZpoolName; +use nexus_types::deployment::blueprint_zone_type; +use nexus_types::deployment::id_map::IdMap; use nexus_types::external_api::views::SledState; use nexus_types::inventory::Collection; -use omicron_common::address::ReservedRackSubnet; use omicron_common::address::CLICKHOUSE_HTTP_PORT; use omicron_common::address::DNS_HTTP_PORT; use omicron_common::address::DNS_PORT; use omicron_common::address::NTP_PORT; +use omicron_common::address::ReservedRackSubnet; use omicron_common::api::external::Generation; use omicron_common::api::external::Vni; use omicron_common::api::internal::shared::NetworkInterface; @@ -65,15 +65,15 @@ use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::SledUuid; use omicron_uuid_kinds::ZpoolUuid; use once_cell::unsync::OnceCell; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; -use slog::Logger; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashSet; +use std::collections::btree_map::Entry; use std::fmt; use std::iter; use std::net::IpAddr; @@ -292,7 +292,10 @@ impl fmt::Display for Operation { write!(f, "sled {sled_id}: added zone: {}", kind.report_str()) } Self::UpdateDisks { sled_id, added, updated, removed } => { - write!(f, "sled {sled_id}: added {added} disks, updated {updated}, removed {removed} disks") + write!( + f, + "sled {sled_id}: added {added} disks, updated {updated}, removed {removed} disks" + ) } Self::UpdateDatasets { sled_id, @@ -301,7 +304,10 @@ impl fmt::Display for Operation { expunged, removed, } => { - write!(f, "sled {sled_id}: added {added} datasets, updated: {updated}, expunged {expunged}, removed {removed} datasets") + write!( + f, + "sled {sled_id}: added {added} datasets, updated: {updated}, expunged {expunged}, removed {removed} datasets" + ) } Self::ZoneExpunged { sled_id, reason, count } => { let reason = match reason { @@ -2076,9 +2082,9 @@ pub(super) fn ensure_input_networking_records_appear_in_parent_blueprint( #[cfg(test)] pub mod test { use super::*; - use crate::example::example; use crate::example::ExampleSystemBuilder; use crate::example::SimRngState; + use crate::example::example; use crate::planner::test::assert_planning_makes_no_changes; use crate::system::SledBuilder; use nexus_reconfigurator_blippy::Blippy; @@ -2213,10 +2219,9 @@ pub mod test { .. } = &z { - assert!(new_sled_resources - .subnet - .net() - .contains(*address.ip())); + assert!( + new_sled_resources.subnet.net().contains(*address.ip()) + ); true } else { false diff --git a/nexus/reconfigurator/planning/src/blueprint_builder/clickhouse.rs b/nexus/reconfigurator/planning/src/blueprint_builder/clickhouse.rs index 9a5d2d8134b..4ca92f410d2 100644 --- a/nexus/reconfigurator/planning/src/blueprint_builder/clickhouse.rs +++ b/nexus/reconfigurator/planning/src/blueprint_builder/clickhouse.rs @@ -11,7 +11,7 @@ use nexus_types::deployment::{ BlueprintZonesConfig, ClickhouseClusterConfig, }; use omicron_uuid_kinds::{OmicronZoneUuid, SledUuid}; -use slog::{error, Logger}; +use slog::{Logger, error}; use std::collections::{BTreeMap, BTreeSet}; use thiserror::Error; @@ -620,8 +620,7 @@ pub mod test { #[test] fn expunge_a_different_keeper_while_adding_keeper() { - static TEST_NAME: &str = - "clickhouse_allocator_expunge_a_different_keeper_while_adding_keeper"; + static TEST_NAME: &str = "clickhouse_allocator_expunge_a_different_keeper_while_adding_keeper"; let logctx = test_setup_log(TEST_NAME); let (n_keeper_zones, n_server_zones, n_keepers, n_servers) = diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/allocators/external_networking.rs b/nexus/reconfigurator/planning/src/blueprint_editor/allocators/external_networking.rs index 4f5ee1ca18b..a8c2dc573b6 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/allocators/external_networking.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/allocators/external_networking.rs @@ -10,9 +10,9 @@ use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::OmicronZoneExternalIp; use nexus_types::inventory::SourceNatConfig; -use omicron_common::address::IpRange; use omicron_common::address::DNS_OPTE_IPV4_SUBNET; use omicron_common::address::DNS_OPTE_IPV6_SUBNET; +use omicron_common::address::IpRange; use omicron_common::address::NEXUS_OPTE_IPV4_SUBNET; use omicron_common::address::NEXUS_OPTE_IPV6_SUBNET; use omicron_common::address::NTP_OPTE_IPV4_SUBNET; @@ -21,10 +21,10 @@ use omicron_common::address::NUM_SOURCE_NAT_PORTS; use omicron_common::api::external::MacAddr; use omicron_common::api::internal::shared::SourceNatConfigError; use oxnet::IpNet; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashSet; +use std::collections::btree_map::Entry; use std::hash::Hash; use std::net::IpAddr; use std::net::Ipv4Addr; @@ -676,11 +676,11 @@ pub mod test { use super::*; use illumos_utils::zpool::ZpoolName; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; - use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::OmicronZoneExternalFloatingAddr; use nexus_types::deployment::OmicronZoneExternalFloatingIp; use nexus_types::deployment::OmicronZoneExternalSnatIp; + use nexus_types::deployment::blueprint_zone_type; use nexus_types::inventory::NetworkInterface; use nexus_types::inventory::NetworkInterfaceKind; use omicron_common::api::external::Generation; diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/allocators/internal_dns.rs b/nexus/reconfigurator/planning/src/blueprint_editor/allocators/internal_dns.rs index 2b0ac93b02d..7be9952c334 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/allocators/internal_dns.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/allocators/internal_dns.rs @@ -2,9 +2,9 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use nexus_types::deployment::blueprint_zone_type::InternalDns; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneType; +use nexus_types::deployment::blueprint_zone_type::InternalDns; use omicron_common::address::DnsSubnet; use omicron_common::address::ReservedRackSubnet; use omicron_common::policy::INTERNAL_DNS_REDUNDANCY; diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor.rs b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor.rs index b20b18d287f..f30cfbc1c55 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor.rs @@ -9,7 +9,6 @@ use crate::planner::SledPlannerRng; use illumos_utils::zpool::ZpoolName; use itertools::Either; use nexus_sled_agent_shared::inventory::ZoneKind; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetFilter; use nexus_types::deployment::BlueprintDatasetsConfig; @@ -20,6 +19,7 @@ use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::BlueprintZonesConfig; use nexus_types::deployment::DiskFilter; +use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::views::SledState; use nexus_types::inventory::Dataset; use nexus_types::inventory::Zpool; @@ -31,9 +31,9 @@ use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::ZpoolUuid; +use slog::Logger; use slog::info; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; use std::borrow::Cow; use std::collections::BTreeMap; diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/datasets.rs b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/datasets.rs index a8e05ef5242..30e694578b1 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/datasets.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/datasets.rs @@ -5,11 +5,11 @@ use crate::blueprint_builder::EditCounts; use crate::planner::SledPlannerRng; use illumos_utils::zpool::ZpoolName; -use nexus_types::deployment::id_map::{self, IdMap}; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::deployment::BlueprintDatasetFilter; use nexus_types::deployment::BlueprintDatasetsConfig; +use nexus_types::deployment::id_map::{self, IdMap}; use omicron_common::api::external::ByteCount; use omicron_common::api::external::Generation; use omicron_common::disk::CompressionAlgorithm; @@ -18,8 +18,8 @@ use omicron_common::disk::DatasetName; use omicron_common::disk::GzipLevel; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::ZpoolUuid; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::net::SocketAddrV6; #[derive(Debug, thiserror::Error)] @@ -336,8 +336,8 @@ mod tests { use omicron_uuid_kinds::SledUuid; use proptest::prelude::*; use std::collections::BTreeSet; - use test_strategy::proptest; use test_strategy::Arbitrary; + use test_strategy::proptest; use uuid::Uuid; // Helper functions to "tag" an iterator (i.e., turn it into an iterator of diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/disks.rs b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/disks.rs index 84cce288a79..3cb823c2087 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/disks.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/disks.rs @@ -10,8 +10,8 @@ use nexus_types::deployment::DiskFilter; use omicron_common::api::external::Generation; use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::ZpoolUuid; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; #[derive(Debug, thiserror::Error)] pub enum DisksEditError { diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/underlay_ip_allocator.rs b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/underlay_ip_allocator.rs index 9586497d443..7aee5b08104 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/underlay_ip_allocator.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/underlay_ip_allocator.rs @@ -5,12 +5,12 @@ //! Allocator for zone underlay IP addresses with a single sled's subnet. use ipnet::IpAdd; -use omicron_common::address::get_sled_address; -use omicron_common::address::get_switch_zone_address; -use omicron_common::address::Ipv6Subnet; use omicron_common::address::CP_SERVICES_RESERVED_ADDRESSES; +use omicron_common::address::Ipv6Subnet; use omicron_common::address::SLED_PREFIX; use omicron_common::address::SLED_RESERVED_ADDRESSES; +use omicron_common::address::get_sled_address; +use omicron_common::address::get_switch_zone_address; use std::net::Ipv6Addr; /// Very simple allocator for picking addresses from a sled's subnet diff --git a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/zones.rs b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/zones.rs index c5474b83387..44277aab26c 100644 --- a/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/zones.rs +++ b/nexus/reconfigurator/planning/src/blueprint_editor/sled_editor/zones.rs @@ -5,11 +5,11 @@ use crate::blueprint_builder::EditCounts; use illumos_utils::zpool::ZpoolName; use nexus_sled_agent_shared::inventory::ZoneKind; -use nexus_types::deployment::id_map::Entry; -use nexus_types::deployment::id_map::IdMap; use nexus_types::deployment::BlueprintZoneConfig; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZonesConfig; +use nexus_types::deployment::id_map::Entry; +use nexus_types::deployment::id_map::IdMap; use omicron_common::api::external::Generation; use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::ZpoolUuid; diff --git a/nexus/reconfigurator/planning/src/planner.rs b/nexus/reconfigurator/planning/src/planner.rs index f293a62635f..49afcaa898e 100644 --- a/nexus/reconfigurator/planning/src/planner.rs +++ b/nexus/reconfigurator/planning/src/planner.rs @@ -32,7 +32,7 @@ use nexus_types::external_api::views::SledState; use nexus_types::inventory::Collection; use omicron_uuid_kinds::SledUuid; use slog::error; -use slog::{info, warn, Logger}; +use slog::{Logger, info, warn}; use std::collections::BTreeSet; use std::str::FromStr; @@ -827,9 +827,9 @@ pub(crate) enum ZoneExpungeReason { pub(crate) mod test { use super::*; use crate::blueprint_builder::test::verify_blueprint; - use crate::example::example; use crate::example::ExampleSystemBuilder; use crate::example::SimRngState; + use crate::example::example; use crate::system::SledBuilder; use chrono::NaiveDateTime; use chrono::TimeZone; @@ -837,13 +837,13 @@ pub(crate) mod test { use clickhouse_admin_types::ClickhouseKeeperClusterMembership; use clickhouse_admin_types::KeeperId; use expectorate::assert_contents; - use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::deployment::BlueprintDiffSummary; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::ClickhouseMode; use nexus_types::deployment::ClickhousePolicy; use nexus_types::deployment::SledDisk; + use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::views::PhysicalDiskState; use nexus_types::external_api::views::SledProvisionPolicy; use nexus_types::external_api::views::SledState; @@ -1237,11 +1237,9 @@ pub(crate) mod test { // sleds (two should get 4 and one should get 3). let mut total_new_nexus_zones = 0; for sled_id in &summary.sleds_modified { - assert!(!summary - .diff - .blueprint_zones - .removed - .contains_key(sled_id)); + assert!( + !summary.diff.blueprint_zones.removed.contains_key(sled_id) + ); let zones_cfg_diff = summary.zones_on_modified_sled(sled_id).unwrap(); assert_eq!(zones_cfg_diff.zones.modified().count(), 0); @@ -2530,8 +2528,10 @@ pub(crate) mod test { // All the zones of the expunged sled should be expunged, and the sled // itself should be decommissioned. - assert!(blueprint2.blueprint_zones[&expunged_sled_id] - .are_all_zones_expunged()); + assert!( + blueprint2.blueprint_zones[&expunged_sled_id] + .are_all_zones_expunged() + ); assert_eq!( blueprint2.sled_state[&expunged_sled_id], SledState::Decommissioned diff --git a/nexus/reconfigurator/planning/src/planner/omicron_zone_placement.rs b/nexus/reconfigurator/planning/src/planner/omicron_zone_placement.rs index 20b908867d2..ffdf44a1c22 100644 --- a/nexus/reconfigurator/planning/src/planner/omicron_zone_placement.rs +++ b/nexus/reconfigurator/planning/src/planner/omicron_zone_placement.rs @@ -335,8 +335,8 @@ pub mod test { use proptest::collection::btree_map; use proptest::sample::size_range; use std::collections::BTreeMap; - use test_strategy::proptest; use test_strategy::Arbitrary; + use test_strategy::proptest; use uuid::Uuid; #[derive(Debug, Clone, Arbitrary)] diff --git a/nexus/reconfigurator/planning/src/planner/rng.rs b/nexus/reconfigurator/planning/src/planner/rng.rs index 633b05e3aae..cdab48d1c88 100644 --- a/nexus/reconfigurator/planning/src/planner/rng.rs +++ b/nexus/reconfigurator/planning/src/planner/rng.rs @@ -14,8 +14,8 @@ use omicron_uuid_kinds::ExternalIpUuid; use omicron_uuid_kinds::OmicronZoneKind; use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::SledUuid; -use rand::rngs::StdRng; use rand::SeedableRng as _; +use rand::rngs::StdRng; use std::collections::BTreeMap; use std::hash::Hash; use typed_rng::TypedUuidRng; diff --git a/nexus/reconfigurator/planning/src/system.rs b/nexus/reconfigurator/planning/src/system.rs index 30bb3f93fb8..34b676cd4ec 100644 --- a/nexus/reconfigurator/planning/src/system.rs +++ b/nexus/reconfigurator/planning/src/system.rs @@ -5,7 +5,7 @@ //! Builders for constructing descriptions of systems (real or synthetic) and //! associated inventory collections and blueprints -use anyhow::{anyhow, bail, ensure, Context}; +use anyhow::{Context, anyhow, bail, ensure}; use gateway_client::types::RotState; use gateway_client::types::SpState; use indexmap::IndexMap; @@ -36,11 +36,11 @@ use nexus_types::inventory::BaseboardId; use nexus_types::inventory::PowerState; use nexus_types::inventory::RotSlot; use nexus_types::inventory::SpType; -use omicron_common::address::get_sled_address; use omicron_common::address::IpRange; use omicron_common::address::Ipv6Subnet; use omicron_common::address::RACK_PREFIX; use omicron_common::address::SLED_PREFIX; +use omicron_common::address::get_sled_address; use omicron_common::api::external::ByteCount; use omicron_common::api::external::Generation; use omicron_common::disk::DiskIdentity; @@ -147,11 +147,13 @@ impl SystemDescription { CockroachDbClusterVersion::POLICY; // IPs from TEST-NET-1 (RFC 5737) - let service_ip_pool_ranges = vec![IpRange::try_from(( - "192.0.2.2".parse::().unwrap(), - "192.0.2.20".parse::().unwrap(), - )) - .unwrap()]; + let service_ip_pool_ranges = vec![ + IpRange::try_from(( + "192.0.2.2".parse::().unwrap(), + "192.0.2.20".parse::().unwrap(), + )) + .unwrap(), + ]; SystemDescription { sleds: IndexMap::new(), diff --git a/nexus/reconfigurator/preparation/src/lib.rs b/nexus/reconfigurator/preparation/src/lib.rs index 52df1e9ecd4..f75c84ab372 100644 --- a/nexus/reconfigurator/preparation/src/lib.rs +++ b/nexus/reconfigurator/preparation/src/lib.rs @@ -8,12 +8,12 @@ use anyhow::Context; use futures::StreamExt; use nexus_db_model::DnsGroup; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::DataStoreDnsTest; use nexus_db_queries::db::datastore::DataStoreInventoryTest; use nexus_db_queries::db::datastore::Discoverability; use nexus_db_queries::db::datastore::SQL_BATCH_SIZE; use nexus_db_queries::db::pagination::Paginator; -use nexus_db_queries::db::DataStore; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintMetadata; use nexus_types::deployment::ClickhousePolicy; @@ -49,8 +49,8 @@ use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::OmicronZoneUuid; use omicron_uuid_kinds::SledUuid; use omicron_uuid_kinds::ZpoolUuid; -use slog::error; use slog::Logger; +use slog::error; use slog_error_chain::InlineErrorChain; use std::collections::BTreeMap; use std::collections::BTreeSet; diff --git a/nexus/reconfigurator/rendezvous/src/crucible_dataset.rs b/nexus/reconfigurator/rendezvous/src/crucible_dataset.rs index 0a0f5384e9d..f1d7b7a7114 100644 --- a/nexus/reconfigurator/rendezvous/src/crucible_dataset.rs +++ b/nexus/reconfigurator/rendezvous/src/crucible_dataset.rs @@ -4,11 +4,11 @@ //! Recording Crucible datasets in their rendezvous table -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::model::CrucibleDataset; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::model::CrucibleDataset; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::identity::Asset; @@ -123,9 +123,9 @@ pub(crate) async fn record_new_crucible_datasets( #[cfg(test)] mod tests { use super::*; - use crate::tests::usize_to_id; use crate::tests::ArbitraryDisposition; use crate::tests::DatasetPrep; + use crate::tests::usize_to_id; use async_bb8_diesel::AsyncRunQueryDsl; use async_bb8_diesel::AsyncSimpleConnection; use nexus_db_model::Generation; diff --git a/nexus/reconfigurator/rendezvous/src/debug_dataset.rs b/nexus/reconfigurator/rendezvous/src/debug_dataset.rs index bfce81bb3fb..301927a4882 100644 --- a/nexus/reconfigurator/rendezvous/src/debug_dataset.rs +++ b/nexus/reconfigurator/rendezvous/src/debug_dataset.rs @@ -6,8 +6,8 @@ use anyhow::Context; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::model::RendezvousDebugDataset; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::model::RendezvousDebugDataset; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetDisposition; use nexus_types::internal_api::background::DebugDatasetsRendezvousStats; @@ -136,9 +136,9 @@ pub(crate) async fn reconcile_debug_datasets( #[cfg(test)] mod tests { use super::*; - use crate::tests::usize_to_id; use crate::tests::ArbitraryDisposition; use crate::tests::DatasetPrep; + use crate::tests::usize_to_id; use async_bb8_diesel::AsyncRunQueryDsl; use async_bb8_diesel::AsyncSimpleConnection; use nexus_db_queries::db::pub_test_utils::TestDatabase; diff --git a/nexus/reconfigurator/simulation/src/config.rs b/nexus/reconfigurator/simulation/src/config.rs index 4a5e44e6c23..39ff02f5bf1 100644 --- a/nexus/reconfigurator/simulation/src/config.rs +++ b/nexus/reconfigurator/simulation/src/config.rs @@ -8,9 +8,9 @@ use indexmap::IndexSet; use omicron_common::api::external::Name; use crate::{ + LoadSerializedResultBuilder, errors::{DuplicateError, KeyError}, utils::join_comma_or_none, - LoadSerializedResultBuilder, }; /// Versioned simulator configuration. diff --git a/nexus/reconfigurator/simulation/src/sim.rs b/nexus/reconfigurator/simulation/src/sim.rs index 06e89288ad7..41b28e58da9 100644 --- a/nexus/reconfigurator/simulation/src/sim.rs +++ b/nexus/reconfigurator/simulation/src/sim.rs @@ -11,7 +11,7 @@ use indexmap::IndexSet; use omicron_uuid_kinds::{ReconfiguratorSimKind, ReconfiguratorSimUuid}; use typed_rng::TypedUuidRng; -use crate::{seed_from_entropy, SimState}; +use crate::{SimState, seed_from_entropy}; /// A store to track reconfigurator states: the main entrypoint for /// reconfigurator simulation. diff --git a/nexus/reconfigurator/simulation/src/state.rs b/nexus/reconfigurator/simulation/src/state.rs index 8e406113ae6..1bdf010dfc9 100644 --- a/nexus/reconfigurator/simulation/src/state.rs +++ b/nexus/reconfigurator/simulation/src/state.rs @@ -4,7 +4,7 @@ use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; +use anyhow::{Context, anyhow, bail}; use nexus_inventory::CollectionBuilder; use nexus_types::deployment::UnstableReconfiguratorState; use omicron_common::api::external::Generation; @@ -12,10 +12,10 @@ use omicron_uuid_kinds::{CollectionUuid, ReconfiguratorSimUuid}; use sync_ptr::SyncConstPtr; use crate::{ - config::SimConfig, errors::NonEmptySystemError, LoadSerializedConfigResult, - LoadSerializedSystemResult, SimConfigBuilder, SimConfigLogEntry, SimRng, - SimRngBuilder, SimRngLogEntry, SimSystem, SimSystemBuilder, - SimSystemLogEntry, Simulator, + LoadSerializedConfigResult, LoadSerializedSystemResult, SimConfigBuilder, + SimConfigLogEntry, SimRng, SimRngBuilder, SimRngLogEntry, SimSystem, + SimSystemBuilder, SimSystemLogEntry, Simulator, config::SimConfig, + errors::NonEmptySystemError, }; /// A top-level, versioned snapshot of reconfigurator state. @@ -149,10 +149,9 @@ impl SimState { .map(|params| (params.generation, params.clone())) .collect(), silo_names: self.config.silo_names().cloned().collect(), - external_dns_zone_names: vec![self - .config - .external_dns_zone_name() - .to_owned()], + external_dns_zone_names: vec![ + self.config.external_dns_zone_name().to_owned(), + ], }) } diff --git a/nexus/reconfigurator/simulation/src/system.rs b/nexus/reconfigurator/simulation/src/system.rs index 3d0bbcd5f09..2c8eb29905c 100644 --- a/nexus/reconfigurator/simulation/src/system.rs +++ b/nexus/reconfigurator/simulation/src/system.rs @@ -23,9 +23,9 @@ use omicron_common::{address::IpRange, api::external::Generation}; use omicron_uuid_kinds::{BlueprintUuid, CollectionUuid, SledUuid}; use crate::{ + LoadSerializedResultBuilder, errors::{DuplicateError, KeyError, NonEmptySystemError}, utils::join_comma_or_none, - LoadSerializedResultBuilder, }; /// A versioned, simulated reconfigurator system. diff --git a/nexus/reconfigurator/simulation/src/utils.rs b/nexus/reconfigurator/simulation/src/utils.rs index a3530412ba3..4d650251954 100644 --- a/nexus/reconfigurator/simulation/src/utils.rs +++ b/nexus/reconfigurator/simulation/src/utils.rs @@ -6,7 +6,7 @@ use std::fmt; -use swrite::{swrite, SWrite}; +use swrite::{SWrite, swrite}; pub(crate) fn join_comma_or_none(iter: I) -> String where diff --git a/nexus/saga-recovery/src/recovery.rs b/nexus/saga-recovery/src/recovery.rs index 79458b4e277..64b223ac7f3 100644 --- a/nexus/saga-recovery/src/recovery.rs +++ b/nexus/saga-recovery/src/recovery.rs @@ -74,16 +74,17 @@ impl RestState { let time_observed = Utc::now(); for saga_id in new_sagas { info!(log, "observed saga start"; "saga_id" => %saga_id); - assert!(self - .sagas_started - .insert( - saga_id, - SagaStartInfo { - time_observed, - source: SagaStartSource::StartChannel, - } - ) - .is_none()); + assert!( + self.sagas_started + .insert( + saga_id, + SagaStartInfo { + time_observed, + source: SagaStartSource::StartChannel, + } + ) + .is_none() + ); } rv } @@ -97,16 +98,17 @@ impl RestState { } for saga_id in execution.sagas_recovered_successfully() { - assert!(self - .sagas_started - .insert( - saga_id, - SagaStartInfo { - time_observed, - source: SagaStartSource::Recovered, - } - ) - .is_none()); + assert!( + self.sagas_started + .insert( + saga_id, + SagaStartInfo { + time_observed, + source: SagaStartSource::Recovered, + } + ) + .is_none() + ); } self.remove_next = plan.sagas_maybe_done().collect(); diff --git a/nexus/src/app/address_lot.rs b/nexus/src/app/address_lot.rs index 847021bdd42..ec0d97c1f0d 100644 --- a/nexus/src/app/address_lot.rs +++ b/nexus/src/app/address_lot.rs @@ -10,10 +10,10 @@ use nexus_db_queries::db; use nexus_db_queries::db::datastore::AddressLotCreateResult; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::{ CreateResult, DeleteResult, Error, ListResultVec, }; diff --git a/nexus/src/app/background/driver.rs b/nexus/src/app/background/driver.rs index 4467a8b070e..e0e19421d80 100644 --- a/nexus/src/app/background/driver.rs +++ b/nexus/src/app/background/driver.rs @@ -11,10 +11,10 @@ use super::BackgroundTask; use super::TaskName; use assert_matches::assert_matches; use chrono::Utc; -use futures::future::BoxFuture; -use futures::stream::FuturesUnordered; use futures::FutureExt; use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream::FuturesUnordered; use nexus_db_queries::context::OpContext; use nexus_types::internal_api::views::ActivationReason; use nexus_types::internal_api::views::CurrentStatus; @@ -23,13 +23,13 @@ use nexus_types::internal_api::views::LastResult; use nexus_types::internal_api::views::LastResultCompleted; use nexus_types::internal_api::views::TaskStatus; use std::collections::BTreeMap; +use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; -use std::sync::Arc; use std::time::Duration; use std::time::Instant; -use tokio::sync::watch; use tokio::sync::Notify; +use tokio::sync::watch; use tokio::time::MissedTickBehavior; /// Drives the execution of background tasks @@ -438,12 +438,12 @@ impl GenericWatcher for watch::Receiver { mod test { use super::BackgroundTask; use super::Driver; - use crate::app::background::driver::TaskDefinition; use crate::app::background::Activator; + use crate::app::background::driver::TaskDefinition; use assert_matches::assert_matches; use chrono::Utc; - use futures::future::BoxFuture; use futures::FutureExt; + use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_test_utils_macros::nexus_test; use nexus_types::internal_api::views::ActivationReason; diff --git a/nexus/src/app/background/init.rs b/nexus/src/app/background/init.rs index 0c9f09dc444..e6feebd7a4a 100644 --- a/nexus/src/app/background/init.rs +++ b/nexus/src/app/background/init.rs @@ -87,6 +87,8 @@ //! It's not foolproof but hopefully these mechanisms will catch the easy //! mistakes. +use super::Activator; +use super::Driver; use super::driver::TaskDefinition; use super::tasks::abandoned_vmm_reaper; use super::tasks::bfd; @@ -123,11 +125,9 @@ use super::tasks::sync_switch_configuration::SwitchPortSettingsManager; use super::tasks::tuf_artifact_replication; use super::tasks::v2p_mappings::V2PManager; use super::tasks::vpc_routes; -use super::Activator; -use super::Driver; +use crate::Nexus; use crate::app::oximeter::PRODUCER_LEASE_DURATION; use crate::app::saga::StartSaga; -use crate::Nexus; use nexus_config::BackgroundTaskConfig; use nexus_config::DnsTasksConfig; use nexus_db_model::DnsGroup; @@ -1030,8 +1030,8 @@ pub mod test { use internal_dns_types::names::ServiceName; use nexus_db_model::DnsGroup; use nexus_db_queries::context::OpContext; - use nexus_db_queries::db::datastore::DnsVersionUpdateBuilder; use nexus_db_queries::db::DataStore; + use nexus_db_queries::db::datastore::DnsVersionUpdateBuilder; use nexus_test_utils_macros::nexus_test; use nexus_types::internal_api::params as nexus_params; use nexus_types::internal_api::params::DnsRecord; diff --git a/nexus/src/app/background/tasks/abandoned_vmm_reaper.rs b/nexus/src/app/background/tasks/abandoned_vmm_reaper.rs index 1853a82fb19..8aaf1c9a538 100644 --- a/nexus/src/app/background/tasks/abandoned_vmm_reaper.rs +++ b/nexus/src/app/background/tasks/abandoned_vmm_reaper.rs @@ -33,13 +33,13 @@ use crate::app::background::BackgroundTask; use anyhow::Context; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::Vmm; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::SQL_BATCH_SIZE; use nexus_db_queries::db::pagination::Paginator; -use nexus_db_queries::db::DataStore; use nexus_types::internal_api::background::AbandonedVmmReaperStatus; use omicron_uuid_kinds::{GenericUuid, PropolisUuid}; use std::sync::Arc; @@ -264,16 +264,18 @@ mod tests { ); let constraints = nexus_db_model::SledReservationConstraints::none(); - dbg!(datastore - .sled_reservation_create( - &opctx, - InstanceUuid::from_untyped_uuid(instance.identity.id), - destroyed_vmm_id, - resources.clone(), - constraints, - ) - .await - .expect("sled reservation should be created successfully")); + dbg!( + datastore + .sled_reservation_create( + &opctx, + InstanceUuid::from_untyped_uuid(instance.identity.id), + destroyed_vmm_id, + resources.clone(), + constraints, + ) + .await + .expect("sled reservation should be created successfully") + ); Self { destroyed_vmm_id } } diff --git a/nexus/src/app/background/tasks/bfd.rs b/nexus/src/app/background/tasks/bfd.rs index c37d3e5c58e..099014583ee 100644 --- a/nexus/src/app/background/tasks/bfd.rs +++ b/nexus/src/app/background/tasks/bfd.rs @@ -10,8 +10,8 @@ use crate::app::{ }; use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use mg_admin_client::types::{BfdPeerConfig, SessionMode}; diff --git a/nexus/src/app/background/tasks/blueprint_execution.rs b/nexus/src/app/background/tasks/blueprint_execution.rs index 527138b659d..7a8ec4273b5 100644 --- a/nexus/src/app/background/tasks/blueprint_execution.rs +++ b/nexus/src/app/background/tasks/blueprint_execution.rs @@ -5,14 +5,14 @@ //! Background task for realizing a plan blueprint use crate::app::background::{Activator, BackgroundTask}; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_resolver::Resolver; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_reconfigurator_execution::RealizeBlueprintOutput; use nexus_types::deployment::{ - execution::EventBuffer, Blueprint, BlueprintTarget, + Blueprint, BlueprintTarget, execution::EventBuffer, }; use omicron_uuid_kinds::OmicronZoneUuid; use serde_json::json; @@ -165,9 +165,9 @@ impl BackgroundTask for BlueprintExecutor { mod test { use super::BlueprintExecutor; use crate::app::background::{Activator, BackgroundTask}; + use httptest::Expectation; use httptest::matchers::{not, request}; use httptest::responders::status_code; - use httptest::Expectation; use nexus_db_model::{ ByteCount, SledBaseboard, SledSystemHardware, SledUpdate, Zpool, }; @@ -181,10 +181,10 @@ mod test { ReconfiguratorExecutionSpec, StepInfo, }; use nexus_types::deployment::{ - blueprint_zone_type, Blueprint, BlueprintDatasetsConfig, - BlueprintPhysicalDisksConfig, BlueprintTarget, BlueprintZoneConfig, - BlueprintZoneDisposition, BlueprintZoneType, BlueprintZonesConfig, - CockroachDbPreserveDowngrade, + Blueprint, BlueprintDatasetsConfig, BlueprintPhysicalDisksConfig, + BlueprintTarget, BlueprintZoneConfig, BlueprintZoneDisposition, + BlueprintZoneType, BlueprintZonesConfig, CockroachDbPreserveDowngrade, + blueprint_zone_type, }; use nexus_types::external_api::views::SledState; use omicron_common::api::external::Generation; diff --git a/nexus/src/app/background/tasks/blueprint_load.rs b/nexus/src/app/background/tasks/blueprint_load.rs index d9342cc4eda..93d10322b19 100644 --- a/nexus/src/app/background/tasks/blueprint_load.rs +++ b/nexus/src/app/background/tasks/blueprint_load.rs @@ -8,8 +8,8 @@ //! blueprint changes. use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_types::deployment::{Blueprint, BlueprintTarget}; diff --git a/nexus/src/app/background/tasks/blueprint_rendezvous.rs b/nexus/src/app/background/tasks/blueprint_rendezvous.rs index 7618eb7f1d4..ddd5504cc44 100644 --- a/nexus/src/app/background/tasks/blueprint_rendezvous.rs +++ b/nexus/src/app/background/tasks/blueprint_rendezvous.rs @@ -6,8 +6,8 @@ //! Reconfigurator rendezvous tables use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_reconfigurator_rendezvous::reconcile_blueprint_rendezvous_tables; diff --git a/nexus/src/app/background/tasks/crdb_node_id_collector.rs b/nexus/src/app/background/tasks/crdb_node_id_collector.rs index 96febb0994f..38dab6f2c82 100644 --- a/nexus/src/app/background/tasks/crdb_node_id_collector.rs +++ b/nexus/src/app/background/tasks/crdb_node_id_collector.rs @@ -24,19 +24,19 @@ //! whether a zone without a known node ID ever existed. use crate::app::background::BackgroundTask; -use anyhow::ensure; use anyhow::Context; -use futures::future::BoxFuture; -use futures::stream; +use anyhow::ensure; use futures::FutureExt; use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream; use nexus_auth::context::OpContext; use nexus_db_queries::db::DataStore; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintTarget; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; +use nexus_types::deployment::blueprint_zone_type; use omicron_common::address::COCKROACH_ADMIN_PORT; use omicron_uuid_kinds::OmicronZoneUuid; use serde_json::json; @@ -232,10 +232,10 @@ impl BackgroundTask for CockroachNodeIdCollector { mod tests { use super::*; use chrono::Utc; + use httptest::Expectation; use httptest::matchers::any; use httptest::responders::json_encoded; use httptest::responders::status_code; - use httptest::Expectation; use nexus_db_queries::db::pub_test_utils::TestDatabase; use nexus_reconfigurator_planning::blueprint_builder::BlueprintBuilder; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; diff --git a/nexus/src/app/background/tasks/decommissioned_disk_cleaner.rs b/nexus/src/app/background/tasks/decommissioned_disk_cleaner.rs index e5e21f5ea97..2cd68a987dc 100644 --- a/nexus/src/app/background/tasks/decommissioned_disk_cleaner.rs +++ b/nexus/src/app/background/tasks/decommissioned_disk_cleaner.rs @@ -12,12 +12,12 @@ use crate::app::background::BackgroundTask; use anyhow::Context; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::Zpool; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::pagination::Paginator; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::pagination::Paginator; use nexus_types::identity::Asset; use omicron_common::api::external::Error; use omicron_uuid_kinds::{GenericUuid, ZpoolUuid}; @@ -348,7 +348,9 @@ mod tests { match (fetched_zpool, fetched_dataset) { (Some(_), Some(_)) => false, (None, None) => true, - _ => panic!("If zpool and dataset were cleaned, they should be cleaned together"), + _ => panic!( + "If zpool and dataset were cleaned, they should be cleaned together" + ), } } } diff --git a/nexus/src/app/background/tasks/dns_config.rs b/nexus/src/app/background/tasks/dns_config.rs index 44158b25bbb..d155241ac28 100644 --- a/nexus/src/app/background/tasks/dns_config.rs +++ b/nexus/src/app/background/tasks/dns_config.rs @@ -5,8 +5,8 @@ //! Background task for keeping track of DNS configuration use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_types::config::DnsConfigParams; use nexus_db_model::DnsGroup; use nexus_db_queries::context::OpContext; @@ -158,8 +158,8 @@ impl BackgroundTask for DnsConfigWatcher { #[cfg(test)] mod test { use super::DnsConfigWatcher; - use crate::app::background::init::test::write_test_dns_generation; use crate::app::background::BackgroundTask; + use crate::app::background::init::test::write_test_dns_generation; use assert_matches::assert_matches; use async_bb8_diesel::AsyncRunQueryDsl; use async_bb8_diesel::AsyncSimpleConnection; diff --git a/nexus/src/app/background/tasks/dns_propagation.rs b/nexus/src/app/background/tasks/dns_propagation.rs index df788609123..0d64a45de9f 100644 --- a/nexus/src/app/background/tasks/dns_propagation.rs +++ b/nexus/src/app/background/tasks/dns_propagation.rs @@ -7,10 +7,10 @@ use super::dns_servers::DnsServersList; use crate::app::background::BackgroundTask; use anyhow::Context; -use futures::future::BoxFuture; -use futures::stream; use futures::FutureExt; use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream; use internal_dns_types::config::DnsConfigParams; use nexus_db_queries::context::OpContext; use serde_json::json; @@ -178,11 +178,11 @@ async fn dns_propagate_one( #[cfg(test)] mod test { use super::DnsPropagator; - use crate::app::background::tasks::dns_servers::DnsServersList; use crate::app::background::BackgroundTask; + use crate::app::background::tasks::dns_servers::DnsServersList; + use httptest::Expectation; use httptest::matchers::request; use httptest::responders::status_code; - use httptest::Expectation; use nexus_db_queries::context::OpContext; use nexus_test_utils_macros::nexus_test; use nexus_types::internal_api::params::DnsConfigParams; diff --git a/nexus/src/app/background/tasks/dns_servers.rs b/nexus/src/app/background/tasks/dns_servers.rs index 3b1e32a2372..0654f9f6c2d 100644 --- a/nexus/src/app/background/tasks/dns_servers.rs +++ b/nexus/src/app/background/tasks/dns_servers.rs @@ -5,8 +5,8 @@ //! Background task for keeping track of DNS servers use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use nexus_db_model::DnsGroup; diff --git a/nexus/src/app/background/tasks/external_endpoints.rs b/nexus/src/app/background/tasks/external_endpoints.rs index c866cade756..8295b5804f9 100644 --- a/nexus/src/app/background/tasks/external_endpoints.rs +++ b/nexus/src/app/background/tasks/external_endpoints.rs @@ -7,10 +7,10 @@ //! associated with those names use crate::app::background::BackgroundTask; -use crate::app::external_endpoints::read_all_endpoints; pub use crate::app::external_endpoints::ExternalEndpoints; -use futures::future::BoxFuture; +use crate::app::external_endpoints::read_all_endpoints; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use serde_json::json; diff --git a/nexus/src/app/background/tasks/instance_reincarnation.rs b/nexus/src/app/background/tasks/instance_reincarnation.rs index 9657980c824..0fd7054ba78 100644 --- a/nexus/src/app/background/tasks/instance_reincarnation.rs +++ b/nexus/src/app/background/tasks/instance_reincarnation.rs @@ -6,13 +6,13 @@ use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; -use crate::app::sagas::instance_start; use crate::app::sagas::NexusSaga; +use crate::app::sagas::instance_start; use futures::future::BoxFuture; use nexus_db_queries::authn; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::pagination::Paginator; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::pagination::Paginator; use nexus_types::identity::Resource; use nexus_types::internal_api::background::InstanceReincarnationStatus; use nexus_types::internal_api::background::ReincarnatableInstance; diff --git a/nexus/src/app/background/tasks/instance_updater.rs b/nexus/src/app/background/tasks/instance_updater.rs index b4951b24842..b9a1f6ee495 100644 --- a/nexus/src/app/background/tasks/instance_updater.rs +++ b/nexus/src/app/background/tasks/instance_updater.rs @@ -6,15 +6,15 @@ use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; -use crate::app::sagas::instance_update; use crate::app::sagas::NexusSaga; -use futures::future::BoxFuture; +use crate::app::sagas::instance_update; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::Instance; use nexus_db_model::VmmState; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::{authn, authz}; use nexus_types::identity::Resource; use nexus_types::internal_api::background::InstanceUpdaterStatus; diff --git a/nexus/src/app/background/tasks/instance_watcher.rs b/nexus/src/app/background/tasks/instance_watcher.rs index 1232e7e19a8..92800606172 100644 --- a/nexus/src/app/background/tasks/instance_watcher.rs +++ b/nexus/src/app/background/tasks/instance_watcher.rs @@ -7,14 +7,14 @@ use crate::app::background::BackgroundTask; use crate::app::instance::SledAgentInstanceError; use crate::app::saga::StartSaga; -use futures::{future::BoxFuture, FutureExt}; +use futures::{FutureExt, future::BoxFuture}; use nexus_db_model::Instance; use nexus_db_model::Project; use nexus_db_model::Sled; use nexus_db_model::Vmm; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::pagination::Paginator; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::pagination::Paginator; use nexus_types::external_api::views::SledPolicy; use nexus_types::identity::Asset; use nexus_types::identity::Resource; @@ -577,9 +577,9 @@ mod metrics { use super::virtual_machine::Check; use super::virtual_machine::IncompleteCheck; use super::{CheckOutcome, Incomplete, VirtualMachine}; - use oximeter::types::Cumulative; use oximeter::MetricsError; use oximeter::Sample; + use oximeter::types::Cumulative; use std::collections::BTreeMap; use std::sync::Arc; use std::sync::Mutex; diff --git a/nexus/src/app/background/tasks/inventory_collection.rs b/nexus/src/app/background/tasks/inventory_collection.rs index 54adfa617a9..d1916148040 100644 --- a/nexus/src/app/background/tasks/inventory_collection.rs +++ b/nexus/src/app/background/tasks/inventory_collection.rs @@ -5,10 +5,10 @@ //! Background task for reading inventory for the rack use crate::app::background::BackgroundTask; -use anyhow::ensure; use anyhow::Context; -use futures::future::BoxFuture; +use anyhow::ensure; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_resolver::ResolveError; use internal_dns_types::names::ServiceName; use nexus_db_queries::context::OpContext; diff --git a/nexus/src/app/background/tasks/lookup_region_port.rs b/nexus/src/app/background/tasks/lookup_region_port.rs index e8fee3dc693..37c33d4ba08 100644 --- a/nexus/src/app/background/tasks/lookup_region_port.rs +++ b/nexus/src/app/background/tasks/lookup_region_port.rs @@ -11,11 +11,11 @@ use crate::app::background::BackgroundTask; use anyhow::Result; +use crucible_agent_client::Client as CrucibleAgentClient; use crucible_agent_client::types::Region; use crucible_agent_client::types::RegionId; -use crucible_agent_client::Client as CrucibleAgentClient; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_types::internal_api::background::LookupRegionPortStatus; diff --git a/nexus/src/app/background/tasks/metrics_producer_gc.rs b/nexus/src/app/background/tasks/metrics_producer_gc.rs index 7e061480415..efc463dc0f2 100644 --- a/nexus/src/app/background/tasks/metrics_producer_gc.rs +++ b/nexus/src/app/background/tasks/metrics_producer_gc.rs @@ -8,8 +8,8 @@ use crate::app::background::BackgroundTask; use chrono::TimeDelta; use chrono::Utc; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use serde_json::json; @@ -111,9 +111,9 @@ mod tests { use chrono::DateTime; use chrono::Utc; use diesel::ExpressionMethods; + use httptest::Expectation; use httptest::matchers::request; use httptest::responders::status_code; - use httptest::Expectation; use nexus_db_model::OximeterInfo; use nexus_db_queries::context::OpContext; use nexus_test_utils_macros::nexus_test; diff --git a/nexus/src/app/background/tasks/nat_cleanup.rs b/nexus/src/app/background/tasks/nat_cleanup.rs index f8bfdc0bd9a..29ba3f6da3e 100644 --- a/nexus/src/app/background/tasks/nat_cleanup.rs +++ b/nexus/src/app/background/tasks/nat_cleanup.rs @@ -11,8 +11,8 @@ use crate::app::map_switch_zone_addrs; use super::networking::build_dpd_clients; use crate::app::background::BackgroundTask; use chrono::{Duration, Utc}; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use nexus_db_queries::context::OpContext; diff --git a/nexus/src/app/background/tasks/phantom_disks.rs b/nexus/src/app/background/tasks/phantom_disks.rs index 7f3fceab1c0..3cd96a40ab2 100644 --- a/nexus/src/app/background/tasks/phantom_disks.rs +++ b/nexus/src/app/background/tasks/phantom_disks.rs @@ -19,8 +19,8 @@ //! already in this phantom state. use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use serde_json::json; diff --git a/nexus/src/app/background/tasks/physical_disk_adoption.rs b/nexus/src/app/background/tasks/physical_disk_adoption.rs index 8ad17b58817..b7686a99555 100644 --- a/nexus/src/app/background/tasks/physical_disk_adoption.rs +++ b/nexus/src/app/background/tasks/physical_disk_adoption.rs @@ -12,8 +12,8 @@ //! In the future, this may become more explicitly operator-controlled. use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::PhysicalDisk; use nexus_db_model::Zpool; use nexus_db_queries::context::OpContext; diff --git a/nexus/src/app/background/tasks/read_only_region_replacement_start.rs b/nexus/src/app/background/tasks/read_only_region_replacement_start.rs index a1920e0c43e..e6080e68c96 100644 --- a/nexus/src/app/background/tasks/read_only_region_replacement_start.rs +++ b/nexus/src/app/background/tasks/read_only_region_replacement_start.rs @@ -11,8 +11,8 @@ //! start' background task. use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_types::internal_api::background::ReadOnlyRegionReplacementStartStatus; @@ -161,8 +161,8 @@ impl BackgroundTask for ReadOnlyRegionReplacementDetector { #[cfg(test)] mod test { use super::*; - use crate::app::RegionAllocationStrategy; use crate::app::MIN_DISK_SIZE_BYTES; + use crate::app::RegionAllocationStrategy; use crate::external_api::params; use chrono::Utc; use nexus_db_model::BlockSize; diff --git a/nexus/src/app/background/tasks/region_replacement.rs b/nexus/src/app/background/tasks/region_replacement.rs index a3811cb1a34..558de4d4b74 100644 --- a/nexus/src/app/background/tasks/region_replacement.rs +++ b/nexus/src/app/background/tasks/region_replacement.rs @@ -10,15 +10,15 @@ //! for any requests that are in state "Requested". See the documentation there //! for more information. +use crate::app::RegionAllocationStrategy; use crate::app::authn; use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; use crate::app::sagas; -use crate::app::sagas::region_replacement_start::SagaRegionReplacementStart; use crate::app::sagas::NexusSaga; -use crate::app::RegionAllocationStrategy; -use futures::future::BoxFuture; +use crate::app::sagas::region_replacement_start::SagaRegionReplacementStart; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::RegionReplacement; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; diff --git a/nexus/src/app/background/tasks/region_replacement_driver.rs b/nexus/src/app/background/tasks/region_replacement_driver.rs index 81191e5d2f8..6586d214b18 100644 --- a/nexus/src/app/background/tasks/region_replacement_driver.rs +++ b/nexus/src/app/background/tasks/region_replacement_driver.rs @@ -22,11 +22,11 @@ use crate::app::authn; use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; use crate::app::sagas; +use crate::app::sagas::NexusSaga; use crate::app::sagas::region_replacement_drive::SagaRegionReplacementDrive; use crate::app::sagas::region_replacement_finish::SagaRegionReplacementFinish; -use crate::app::sagas::NexusSaga; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use nexus_types::internal_api::background::RegionReplacementDriverStatus; diff --git a/nexus/src/app/background/tasks/region_snapshot_replacement_finish.rs b/nexus/src/app/background/tasks/region_snapshot_replacement_finish.rs index 8aadcf36490..68971a9c205 100644 --- a/nexus/src/app/background/tasks/region_snapshot_replacement_finish.rs +++ b/nexus/src/app/background/tasks/region_snapshot_replacement_finish.rs @@ -12,10 +12,10 @@ use crate::app::authn; use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; use crate::app::sagas; -use crate::app::sagas::region_snapshot_replacement_finish::*; use crate::app::sagas::NexusSaga; -use futures::future::BoxFuture; +use crate::app::sagas::region_snapshot_replacement_finish::*; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::RegionSnapshotReplacement; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; @@ -191,9 +191,9 @@ mod test { use nexus_db_model::RegionSnapshotReplacement; use nexus_db_model::RegionSnapshotReplacementStep; use nexus_db_model::RegionSnapshotReplacementStepState; - use nexus_db_queries::db::datastore::region_snapshot_replacement; use nexus_db_queries::db::datastore::NewRegionVolumeId; use nexus_db_queries::db::datastore::OldSnapshotVolumeId; + use nexus_db_queries::db::datastore::region_snapshot_replacement; use nexus_test_utils_macros::nexus_test; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::VolumeUuid; diff --git a/nexus/src/app/background/tasks/region_snapshot_replacement_garbage_collect.rs b/nexus/src/app/background/tasks/region_snapshot_replacement_garbage_collect.rs index 9e76cd4daf6..3d7d7317d31 100644 --- a/nexus/src/app/background/tasks/region_snapshot_replacement_garbage_collect.rs +++ b/nexus/src/app/background/tasks/region_snapshot_replacement_garbage_collect.rs @@ -8,10 +8,10 @@ use crate::app::authn; use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; use crate::app::sagas; -use crate::app::sagas::region_snapshot_replacement_garbage_collect::*; use crate::app::sagas::NexusSaga; -use futures::future::BoxFuture; +use crate::app::sagas::region_snapshot_replacement_garbage_collect::*; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::RegionSnapshotReplacement; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; diff --git a/nexus/src/app/background/tasks/region_snapshot_replacement_start.rs b/nexus/src/app/background/tasks/region_snapshot_replacement_start.rs index c7eb449312e..362f5abf3e7 100644 --- a/nexus/src/app/background/tasks/region_snapshot_replacement_start.rs +++ b/nexus/src/app/background/tasks/region_snapshot_replacement_start.rs @@ -10,15 +10,15 @@ //! replacement start saga for any requests that are in state "Requested". See //! the documentation in that saga's docstring for more information. +use crate::app::RegionAllocationStrategy; use crate::app::authn; use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; use crate::app::sagas; -use crate::app::sagas::region_snapshot_replacement_start::*; use crate::app::sagas::NexusSaga; -use crate::app::RegionAllocationStrategy; -use futures::future::BoxFuture; +use crate::app::sagas::region_snapshot_replacement_start::*; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::ReadOnlyTargetReplacement; use nexus_db_model::RegionSnapshotReplacement; use nexus_db_queries::context::OpContext; @@ -307,8 +307,8 @@ impl BackgroundTask for RegionSnapshotReplacementDetector { #[cfg(test)] mod test { use super::*; - use crate::app::background::init::test::NoopStartSaga; use crate::app::MIN_DISK_SIZE_BYTES; + use crate::app::background::init::test::NoopStartSaga; use chrono::Utc; use nexus_db_model::BlockSize; use nexus_db_model::Generation; diff --git a/nexus/src/app/background/tasks/region_snapshot_replacement_step.rs b/nexus/src/app/background/tasks/region_snapshot_replacement_step.rs index fb9c27e5c9a..ee30d57a22a 100644 --- a/nexus/src/app/background/tasks/region_snapshot_replacement_step.rs +++ b/nexus/src/app/background/tasks/region_snapshot_replacement_step.rs @@ -25,15 +25,15 @@ use crate::app::authn; use crate::app::background::BackgroundTask; use crate::app::saga::StartSaga; use crate::app::sagas; +use crate::app::sagas::NexusSaga; use crate::app::sagas::region_snapshot_replacement_step::*; use crate::app::sagas::region_snapshot_replacement_step_garbage_collect::*; -use crate::app::sagas::NexusSaga; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::RegionSnapshotReplacementStep; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::datastore::region_snapshot_replacement::*; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::datastore::region_snapshot_replacement::*; use nexus_types::identity::Asset; use nexus_types::internal_api::background::RegionSnapshotReplacementStepStatus; use omicron_common::api::external::Error; diff --git a/nexus/src/app/background/tasks/saga_recovery.rs b/nexus/src/app/background/tasks/saga_recovery.rs index 652e3f2276c..943fb9666ac 100644 --- a/nexus/src/app/background/tasks/saga_recovery.rs +++ b/nexus/src/app/background/tasks/saga_recovery.rs @@ -120,12 +120,12 @@ //! to process things in the right order. These details are mostly handled by //! the separate [`nexus_saga_recovery`] crate. +use crate::Nexus; use crate::app::background::BackgroundTask; use crate::app::sagas::NexusSagaType; use crate::saga_interface::SagaContext; -use crate::Nexus; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; use nexus_db_queries::db::DataStore; @@ -491,17 +491,17 @@ mod test { use nexus_types::internal_api::views::LastResult; use omicron_test_utils::dev::{ self, - poll::{wait_for_condition, CondCheckError}, + poll::{CondCheckError, wait_for_condition}, }; use pretty_assertions::assert_eq; use std::sync::{ - atomic::{AtomicBool, AtomicU32, Ordering}, LazyLock, + atomic::{AtomicBool, AtomicU32, Ordering}, }; use steno::{ - new_action_noop_undo, Action, ActionContext, ActionError, - ActionRegistry, DagBuilder, Node, SagaDag, SagaId, SagaName, - SagaResult, SagaType, SecClient, + Action, ActionContext, ActionError, ActionRegistry, DagBuilder, Node, + SagaDag, SagaId, SagaName, SagaResult, SagaType, SecClient, + new_action_noop_undo, }; use uuid::Uuid; type ControlPlaneTestContext = diff --git a/nexus/src/app/background/tasks/service_firewall_rules.rs b/nexus/src/app/background/tasks/service_firewall_rules.rs index 4004de42c88..3fc794ae850 100644 --- a/nexus/src/app/background/tasks/service_firewall_rules.rs +++ b/nexus/src/app/background/tasks/service_firewall_rules.rs @@ -11,8 +11,8 @@ //! place to propagate changes in the IP allowlist for user-facing services. use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use std::sync::Arc; diff --git a/nexus/src/app/background/tasks/support_bundle_collector.rs b/nexus/src/app/background/tasks/support_bundle_collector.rs index 887b8b25b0b..200284b04be 100644 --- a/nexus/src/app/background/tasks/support_bundle_collector.rs +++ b/nexus/src/app/background/tasks/support_bundle_collector.rs @@ -7,11 +7,11 @@ use crate::app::background::BackgroundTask; use camino::Utf8DirEntry; use camino::Utf8Path; +use camino_tempfile::Utf8TempDir; use camino_tempfile::tempdir_in; use camino_tempfile::tempfile_in; -use camino_tempfile::Utf8TempDir; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::SupportBundle; use nexus_db_model::SupportBundleState; use nexus_db_queries::authz; @@ -39,8 +39,8 @@ use std::sync::Arc; use tokio::io::AsyncReadExt; use tokio::io::AsyncSeekExt; use tokio::io::SeekFrom; -use zip::write::FullFileOptions; use zip::ZipWriter; +use zip::write::FullFileOptions; // We use "/var/tmp" to use Nexus' filesystem for temporary storage, // rather than "/tmp", which would keep this collected data in-memory. diff --git a/nexus/src/app/background/tasks/sync_service_zone_nat.rs b/nexus/src/app/background/tasks/sync_service_zone_nat.rs index 972c9702cf5..ae78ea2dda3 100644 --- a/nexus/src/app/background/tasks/sync_service_zone_nat.rs +++ b/nexus/src/app/background/tasks/sync_service_zone_nat.rs @@ -10,14 +10,14 @@ use crate::app::map_switch_zone_addrs; use super::networking::build_dpd_clients; use crate::app::background::BackgroundTask; use anyhow::Context; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use nexus_db_model::Ipv4NatValues; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::lookup::LookupPath; use nexus_sled_agent_shared::inventory::{ OmicronZoneConfig, OmicronZoneType, OmicronZonesConfig, }; diff --git a/nexus/src/app/background/tasks/sync_switch_configuration.rs b/nexus/src/app/background/tasks/sync_switch_configuration.rs index 30309618374..c722e6eb7b0 100644 --- a/nexus/src/app/background/tasks/sync_switch_configuration.rs +++ b/nexus/src/app/background/tasks/sync_switch_configuration.rs @@ -18,16 +18,16 @@ use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use ipnetwork::IpNetwork; use nexus_db_model::{ - AddressLotBlock, BgpConfig, BootstoreConfig, LoopbackAddress, - SwitchLinkSpeed, INFRA_LOT, NETWORK_KEY, + AddressLotBlock, BgpConfig, BootstoreConfig, INFRA_LOT, LoopbackAddress, + NETWORK_KEY, SwitchLinkSpeed, }; use uuid::Uuid; use crate::app::background::BackgroundTask; use display_error_chain::DisplayErrorChain; use dpd_client::types::PortId; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use mg_admin_client::types::{ AddStaticRoute4Request, ApplyRequest, BgpPeerConfig, CheckerSource, DeleteStaticRoute4Request, ImportExportPolicy as MgImportExportPolicy, @@ -36,13 +36,13 @@ use mg_admin_client::types::{ }; use nexus_db_queries::{ context::OpContext, - db::{datastore::SwitchPortSettingsCombinedResult, DataStore}, + db::{DataStore, datastore::SwitchPortSettingsCombinedResult}, }; use nexus_types::identity::Asset; use nexus_types::{external_api::params, identity::Resource}; use omicron_common::OMICRON_DPD_TAG; use omicron_common::{ - address::{get_sled_address, Ipv6Subnet}, + address::{Ipv6Subnet, get_sled_address}, api::{ external::{DataPageParams, ImportExportPolicy, SwitchLocation}, internal::shared::ParseSwitchLocationError, @@ -56,7 +56,7 @@ use sled_agent_client::types::{ RouteConfig as SledRouteConfig, TxEqConfig, UplinkAddressConfig, }; use std::{ - collections::{hash_map::Entry, HashMap, HashSet}, + collections::{HashMap, HashSet, hash_map::Entry}, hash::Hash, net::{IpAddr, Ipv4Addr}, str::FromStr, diff --git a/nexus/src/app/background/tasks/tuf_artifact_replication.rs b/nexus/src/app/background/tasks/tuf_artifact_replication.rs index 3ae62b8d400..0a958384c08 100644 --- a/nexus/src/app/background/tasks/tuf_artifact_replication.rs +++ b/nexus/src/app/background/tasks/tuf_artifact_replication.rs @@ -64,7 +64,7 @@ use futures::future::BoxFuture; use futures::{FutureExt, Stream, StreamExt}; use nexus_auth::context::OpContext; use nexus_db_queries::db::{ - datastore::SQL_BATCH_SIZE, pagination::Paginator, DataStore, + DataStore, datastore::SQL_BATCH_SIZE, pagination::Paginator, }; use nexus_networking::sled_client_from_address; use nexus_types::deployment::SledFilter; @@ -78,7 +78,7 @@ use rand::seq::SliceRandom; use serde_json::json; use slog_error_chain::InlineErrorChain; use tokio::sync::mpsc::error::TryRecvError; -use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; use update_common::artifacts::{ ArtifactsWithPlan, ExtractedArtifactDataHandle, }; @@ -218,11 +218,7 @@ impl Inventory { if *count > 0 && *count < EXPECTED_COUNT { let Ok(source_sled) = sleds_present .choose_weighted(rng, |sled| { - if sled.id == target_sled.id { - 0 - } else { - 1 - } + if sled.id == target_sled.id { 0 } else { 1 } }) .copied() else { @@ -695,7 +691,7 @@ mod tests { use std::fmt::Write; use expectorate::assert_contents; - use rand::{rngs::StdRng, Rng, SeedableRng}; + use rand::{Rng, SeedableRng, rngs::StdRng}; use super::*; diff --git a/nexus/src/app/background/tasks/v2p_mappings.rs b/nexus/src/app/background/tasks/v2p_mappings.rs index b8323700342..c095771c610 100644 --- a/nexus/src/app/background/tasks/v2p_mappings.rs +++ b/nexus/src/app/background/tasks/v2p_mappings.rs @@ -1,7 +1,7 @@ use std::{collections::HashSet, sync::Arc}; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::Sled; use nexus_db_queries::{context::OpContext, db::DataStore}; use nexus_networking::sled_client_from_address; diff --git a/nexus/src/app/background/tasks/vpc_routes.rs b/nexus/src/app/background/tasks/vpc_routes.rs index 5c326dc7337..dc44ef285ec 100644 --- a/nexus/src/app/background/tasks/vpc_routes.rs +++ b/nexus/src/app/background/tasks/vpc_routes.rs @@ -5,8 +5,8 @@ //! Background task for propagating VPC routes (system and custom) to sleds. use crate::app::background::BackgroundTask; -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_model::{Sled, SledState, Vni}; use nexus_db_queries::{context::OpContext, db::DataStore}; use nexus_networking::sled_client_from_address; diff --git a/nexus/src/app/bgp.rs b/nexus/src/app/bgp.rs index 31a0faa6634..149568d34fb 100644 --- a/nexus/src/app/bgp.rs +++ b/nexus/src/app/bgp.rs @@ -127,9 +127,9 @@ impl super::Nexus { Ok(result) => result.into_inner(), Err(e) => { error!( - self.log, - "failed to get peers for asn {asn} from {switch}: {e}" - ); + self.log, + "failed to get peers for asn {asn} from {switch}: {e}" + ); continue; } }; @@ -186,9 +186,9 @@ impl super::Nexus { Ok(result) => result.into_inner(), Err(e) => { error!( - self.log, - "failed to get exports for asn {asn} from {switch}: {e}" - ); + self.log, + "failed to get exports for asn {asn} from {switch}: {e}" + ); continue; } }; diff --git a/nexus/src/app/certificate.rs b/nexus/src/app/certificate.rs index 2f130d1ad30..410799e71e5 100644 --- a/nexus/src/app/certificate.rs +++ b/nexus/src/app/certificate.rs @@ -13,12 +13,12 @@ use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::Name; use nexus_db_queries::db::model::ServiceKind; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::InternalContext; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::NameOrId; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use uuid::Uuid; diff --git a/nexus/src/app/crucible.rs b/nexus/src/app/crucible.rs index de40d5b4f5c..0255b5bcb9d 100644 --- a/nexus/src/app/crucible.rs +++ b/nexus/src/app/crucible.rs @@ -7,6 +7,7 @@ use super::*; use anyhow::anyhow; +use crucible_agent_client::Client as CrucibleAgentClient; use crucible_agent_client::types::CreateRegion; use crucible_agent_client::types::GetSnapshotResponse; use crucible_agent_client::types::Region; @@ -14,7 +15,6 @@ use crucible_agent_client::types::RegionId; use crucible_agent_client::types::RunningSnapshot; use crucible_agent_client::types::Snapshot; use crucible_agent_client::types::State as RegionState; -use crucible_agent_client::Client as CrucibleAgentClient; use futures::StreamExt; use nexus_db_queries::db; use nexus_db_queries::db::identity::Asset; diff --git a/nexus/src/app/device_auth.rs b/nexus/src/app/device_auth.rs index ebc250bffc5..3b6d8ba436d 100644 --- a/nexus/src/app/device_auth.rs +++ b/nexus/src/app/device_auth.rs @@ -45,7 +45,7 @@ //! but that may change in the future. use dropshot::{Body, HttpError}; -use http::{header, Response, StatusCode}; +use http::{Response, StatusCode, header}; use nexus_db_queries::authn::{Actor, Reason}; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; diff --git a/nexus/src/app/disk.rs b/nexus/src/app/disk.rs index 556ed5f1046..69e41b33754 100644 --- a/nexus/src/app/disk.rs +++ b/nexus/src/app/disk.rs @@ -12,7 +12,6 @@ use nexus_db_queries::context::OpContext; use nexus_db_queries::db; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::ByteCount; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; @@ -23,6 +22,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::internal::nexus::DiskRuntimeState; use sled_agent_client::Client as SledAgentClient; use std::sync::Arc; @@ -53,12 +53,11 @@ impl super::Nexus { .disk_name_owned(name.into()); Ok(disk) } - params::DiskSelector { - disk: NameOrId::Id(_), - .. - } => Err(Error::invalid_request( - "when providing disk as an ID project should not be specified", - )), + params::DiskSelector { disk: NameOrId::Id(_), .. } => { + Err(Error::invalid_request( + "when providing disk as an ID project should not be specified", + )) + } _ => Err(Error::invalid_request( "disk should either be UUID or project should be specified", )), @@ -94,13 +93,11 @@ impl super::Nexus { // If the size of the snapshot is greater than the size of the // disk, return an error. if db_snapshot.size.to_bytes() > params.size.to_bytes() { - return Err(Error::invalid_request( - &format!( - "disk size {} must be greater than or equal to snapshot size {}", - params.size.to_bytes(), - db_snapshot.size.to_bytes(), - ), - )); + return Err(Error::invalid_request(&format!( + "disk size {} must be greater than or equal to snapshot size {}", + params.size.to_bytes(), + db_snapshot.size.to_bytes(), + ))); } db_snapshot.block_size.to_bytes().into() @@ -124,13 +121,11 @@ impl super::Nexus { // If the size of the image is greater than the size of the // disk, return an error. if db_image.size.to_bytes() > params.size.to_bytes() { - return Err(Error::invalid_request( - &format!( - "disk size {} must be greater than or equal to image size {}", - params.size.to_bytes(), - db_image.size.to_bytes(), - ), - )); + return Err(Error::invalid_request(&format!( + "disk size {} must be greater than or equal to image size {}", + params.size.to_bytes(), + db_image.size.to_bytes(), + ))); } db_image.block_size.to_bytes().into() diff --git a/nexus/src/app/external_dns.rs b/nexus/src/app/external_dns.rs index 7a8dacbb98d..22e78664dbf 100644 --- a/nexus/src/app/external_dns.rs +++ b/nexus/src/app/external_dns.rs @@ -5,11 +5,11 @@ use std::net::IpAddr; use std::net::SocketAddr; +use hickory_resolver::TokioAsyncResolver; use hickory_resolver::config::NameServerConfig; use hickory_resolver::config::Protocol; use hickory_resolver::config::ResolverConfig; use hickory_resolver::config::ResolverOpts; -use hickory_resolver::TokioAsyncResolver; use omicron_common::address::DNS_PORT; use reqwest::dns::Name; diff --git a/nexus/src/app/external_endpoints.rs b/nexus/src/app/external_endpoints.rs index b93b6924655..00cc83b2b44 100644 --- a/nexus/src/app/external_endpoints.rs +++ b/nexus/src/app/external_endpoints.rs @@ -27,32 +27,32 @@ //! [`rustls::server::ResolvesServerCert`]. See [`NexusCertResolver`]. use crate::context::ApiContext; +use anyhow::Context; use anyhow::anyhow; use anyhow::bail; -use anyhow::Context; use nexus_db_model::AuthenticationMode; use nexus_db_model::Certificate; use nexus_db_model::DnsGroup; use nexus_db_model::DnsZone; use nexus_db_model::Silo; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::Discoverability; use nexus_db_queries::db::model::ServiceKind; use nexus_db_queries::db::pagination::Paginator; -use nexus_db_queries::db::DataStore; use nexus_types::identity::Resource; -use nexus_types::silo::silo_dns_name; use nexus_types::silo::DEFAULT_SILO_ID; -use omicron_common::api::external::http_pagination::PaginatedBy; +use nexus_types::silo::silo_dns_name; use omicron_common::api::external::Error; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::bail_unless; use openssl::pkey::PKey; use openssl::x509::X509; use rustls::sign::CertifiedKey; use serde::Serialize; use serde_with::SerializeDisplay; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::fmt; use std::num::NonZeroU32; use std::sync::Arc; @@ -784,18 +784,18 @@ fn endpoint_for_authority( #[cfg(test)] mod test { - use super::endpoint_for_authority; use super::ExternalEndpoints; use super::TlsCertificate; - use crate::app::external_endpoints::authority_for_request; + use super::endpoint_for_authority; use crate::app::external_endpoints::ExternalEndpointError; use crate::app::external_endpoints::NexusCertResolver; + use crate::app::external_endpoints::authority_for_request; use chrono::Utc; - use dropshot::endpoint; - use dropshot::test_util::LogContext; use dropshot::ConfigLogging; use dropshot::ConfigLoggingIfExists; use dropshot::ConfigLoggingLevel; + use dropshot::endpoint; + use dropshot::test_util::LogContext; use http::uri::Authority; use nexus_db_model::Certificate; use nexus_db_model::DnsGroup; @@ -1282,9 +1282,9 @@ mod test { // At this point we haven't filled in the configuration so any attempt // to resolve anything should fail. - assert!(cert_resolver - .do_resolve(Some("silo1.sys.oxide1.test")) - .is_none()); + assert!( + cert_resolver.do_resolve(Some("silo1.sys.oxide1.test")).is_none() + ); // Now pass along the configuration and try again. watch_tx.send(Some(ee.clone())).unwrap(); @@ -1294,9 +1294,9 @@ mod test { let resolved_c2 = cert_resolver.do_resolve(Some("silo2.sys.oxide1.test")).unwrap(); assert_eq!(resolved_c2.cert, c2.certified_key.cert); - assert!(cert_resolver - .do_resolve(Some("silo3.sys.oxide1.test")) - .is_none()); + assert!( + cert_resolver.do_resolve(Some("silo3.sys.oxide1.test")).is_none() + ); // We should get an expired cert if it's the only option. let resolved_c4 = cert_resolver.do_resolve(Some("silo4.sys.oxide1.test")).unwrap(); diff --git a/nexus/src/app/external_ip.rs b/nexus/src/app/external_ip.rs index 06dfc7732fd..106237ffe99 100644 --- a/nexus/src/app/external_ip.rs +++ b/nexus/src/app/external_ip.rs @@ -16,7 +16,6 @@ use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::IpKind; use nexus_types::external_api::params; use nexus_types::external_api::views; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -24,6 +23,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::InstanceUuid; @@ -61,9 +61,12 @@ impl super::Nexus { fip_selector: params::FloatingIpSelector, ) -> LookupResult> { match fip_selector { - params::FloatingIpSelector { floating_ip: NameOrId::Id(id), project: None } => { - let floating_ip = - LookupPath::new(opctx, &self.db_datastore).floating_ip_id(id); + params::FloatingIpSelector { + floating_ip: NameOrId::Id(id), + project: None, + } => { + let floating_ip = LookupPath::new(opctx, &self.db_datastore) + .floating_ip_id(id); Ok(floating_ip) } params::FloatingIpSelector { @@ -76,8 +79,7 @@ impl super::Nexus { Ok(floating_ip) } params::FloatingIpSelector { - floating_ip: NameOrId::Id(_), - .. + floating_ip: NameOrId::Id(_), .. } => Err(Error::invalid_request( "when providing Floating IP as an ID project should not be specified", )), diff --git a/nexus/src/app/image.rs b/nexus/src/app/image.rs index 15f29cfd9ce..96a3c22a80e 100644 --- a/nexus/src/app/image.rs +++ b/nexus/src/app/image.rs @@ -15,7 +15,6 @@ use nexus_db_queries::db::lookup::ImageLookup; use nexus_db_queries::db::lookup::ImageParentLookup; use nexus_db_queries::db::lookup::LookupPath; use omicron_common::api::external; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -23,6 +22,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_uuid_kinds::VolumeUuid; use std::sync::Arc; use uuid::Uuid; @@ -41,14 +41,18 @@ impl super::Nexus { project: None, } => { let (.., db_image) = LookupPath::new(opctx, &self.db_datastore) - .image_id(id).fetch().await?; + .image_id(id) + .fetch() + .await?; let lookup = match db_image.project_id { - Some(_) => ImageLookup::ProjectImage(LookupPath::new(opctx, &self.db_datastore) - .project_image_id(id)), - None => { - ImageLookup::SiloImage(LookupPath::new(opctx, &self.db_datastore) - .silo_image_id(id)) - }, + Some(_) => ImageLookup::ProjectImage( + LookupPath::new(opctx, &self.db_datastore) + .project_image_id(id), + ), + None => ImageLookup::SiloImage( + LookupPath::new(opctx, &self.db_datastore) + .silo_image_id(id), + ), }; Ok(lookup) } @@ -56,24 +60,26 @@ impl super::Nexus { image: NameOrId::Name(name), project: Some(project), } => { - let image = - self.project_lookup(opctx, params::ProjectSelector { project })?.project_image_name_owned(name.into()); + let image = self + .project_lookup(opctx, params::ProjectSelector { project })? + .project_image_name_owned(name.into()); Ok(ImageLookup::ProjectImage(image)) } params::ImageSelector { image: NameOrId::Name(name), project: None, } => { - let image = self.current_silo_lookup(opctx)?.silo_image_name_owned(name.into()); + let image = self + .current_silo_lookup(opctx)? + .silo_image_name_owned(name.into()); Ok(ImageLookup::SiloImage(image)) } - params::ImageSelector { - image: NameOrId::Id(_), - .. - } => Err(Error::invalid_request( - "when providing image as an ID, project should not be specified", - )), + params::ImageSelector { image: NameOrId::Id(_), .. } => { + Err(Error::invalid_request( + "when providing image as an ID, project should not be specified", + )) } + } } /// Creates an image diff --git a/nexus/src/app/instance.rs b/nexus/src/app/instance.rs index efd85485eeb..240419aa053 100644 --- a/nexus/src/app/instance.rs +++ b/nexus/src/app/instance.rs @@ -29,13 +29,12 @@ use nexus_db_queries::authn; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::InstanceAndActiveVmm; use nexus_db_queries::db::identity::Resource; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; -use nexus_db_queries::db::DataStore; use nexus_types::external_api::views; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::ByteCount; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; @@ -48,18 +47,19 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::internal::nexus; use omicron_common::api::internal::shared::SourceNatConfig; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::InstanceUuid; use omicron_uuid_kinds::PropolisUuid; use omicron_uuid_kinds::SledUuid; -use propolis_client::support::tungstenite::protocol::frame::coding::CloseCode; -use propolis_client::support::tungstenite::protocol::CloseFrame; -use propolis_client::support::tungstenite::Message as WebSocketMessage; use propolis_client::support::InstanceSerialConsoleHelper; use propolis_client::support::WSClientOffset; use propolis_client::support::WebSocketStream; +use propolis_client::support::tungstenite::Message as WebSocketMessage; +use propolis_client::support::tungstenite::protocol::CloseFrame; +use propolis_client::support::tungstenite::protocol::frame::coding::CloseCode; use sagas::instance_common::ExternalIpAttach; use sagas::instance_start; use sagas::instance_update; @@ -272,7 +272,7 @@ impl super::Nexus { match instance_selector { params::InstanceSelector { instance: NameOrId::Id(id), - project: None + project: None, } => { let instance = LookupPath::new(opctx, &self.db_datastore).instance_id(id); @@ -280,26 +280,21 @@ impl super::Nexus { } params::InstanceSelector { instance: NameOrId::Name(name), - project: Some(project) + project: Some(project), } => { let instance = self .project_lookup(opctx, params::ProjectSelector { project })? .instance_name_owned(name.into()); Ok(instance) } - params::InstanceSelector { - instance: NameOrId::Id(_), - .. - } => { + params::InstanceSelector { instance: NameOrId::Id(_), .. } => { Err(Error::invalid_request( "when providing instance as an ID project should not be specified", )) } - _ => { - Err(Error::invalid_request( - "instance should either be UUID or project should be specified", - )) - } + _ => Err(Error::invalid_request( + "instance should either be UUID or project should be specified", + )), } } @@ -808,22 +803,24 @@ impl super::Nexus { return Err(Error::invalid_request(&format!( "cannot run an instance in state {} with no VMM", effective_state - ))) + ))); } InstanceStateChangeRequest::Stop => { - return Ok(InstanceStateChangeRequestAction::AlreadyDone); + return Ok( + InstanceStateChangeRequestAction::AlreadyDone, + ); } InstanceStateChangeRequest::Reboot => { return Err(Error::invalid_request(&format!( "cannot reboot an instance in state {} with no VMM", effective_state - ))) + ))); } InstanceStateChangeRequest::Migrate(_) => { return Err(Error::invalid_request(&format!( "cannot migrate an instance in state {} with no VMM", effective_state - ))) + ))); } }, @@ -832,9 +829,9 @@ impl super::Nexus { // Return a specific error message explaining the problem. InstanceState::Creating => { return Err(Error::invalid_request( - "cannot change instance state while it is \ - still being created" - )) + "cannot change instance state while it is \ + still being created", + )); } // Failed instances may transition to Stopped by just changing // the Nexus state in the database to NoVmm. @@ -849,23 +846,32 @@ impl super::Nexus { // that a Failed instance is definitely not incarnated on a // sled, so all we need to do to "stop" it is to update its // state in the database. - InstanceState::Failed if matches!(requested, InstanceStateChangeRequest::Stop) => { + InstanceState::Failed + if matches!( + requested, + InstanceStateChangeRequest::Stop + ) => + { // As discussed above, this shouldn't happen, so return an // internal error and complain about it in the logs. if vmm_state.is_some() { return Err(Error::internal_error( "an instance should not be in the Failed \ - effective state if it has an active VMM" + effective state if it has an active VMM", )); } let prev_runtime = instance_state.runtime(); - return Ok(InstanceStateChangeRequestAction::UpdateRuntime(db::model::InstanceRuntimeState { - time_updated: chrono::Utc::now(), - r#gen: prev_runtime.r#gen.0.next().into(), - nexus_state: db::model::InstanceState::NoVmm, - ..prev_runtime.clone() - })); + return Ok( + InstanceStateChangeRequestAction::UpdateRuntime( + db::model::InstanceRuntimeState { + time_updated: chrono::Utc::now(), + r#gen: prev_runtime.r#gen.0.next().into(), + nexus_state: db::model::InstanceState::NoVmm, + ..prev_runtime.clone() + }, + ), + ); } // If the instance has no sled beacuse it's been destroyed or // has fallen over, reject the state change. @@ -873,7 +879,7 @@ impl super::Nexus { return Err(Error::invalid_request(&format!( "instance state cannot be changed from {}", effective_state - ))) + ))); } // In other states, the instance should have a sled, and an @@ -884,7 +890,7 @@ impl super::Nexus { "state" => ?effective_state); return Err(Error::internal_error( - "instance is active but not resident on a sled" + "instance is active but not resident on a sled", )); } } @@ -1676,24 +1682,28 @@ impl super::Nexus { match vmm.runtime.state { DbVmmState::Running | DbVmmState::Rebooting - | DbVmmState::Migrating => { - Ok((vmm.clone(), SocketAddr::new(vmm.propolis_ip.ip(), vmm.propolis_port.into()))) - } + | DbVmmState::Migrating => Ok(( + vmm.clone(), + SocketAddr::new( + vmm.propolis_ip.ip(), + vmm.propolis_port.into(), + ), + )), DbVmmState::Starting | DbVmmState::Stopping | DbVmmState::Stopped | DbVmmState::Failed - | DbVmmState::Creating => { - Err(Error::invalid_request(format!( - "cannot connect to serial console of instance in state \"{}\"", - state.effective_state(), - ))) + | DbVmmState::Creating => Err(Error::invalid_request(format!( + "cannot connect to serial console of instance in state \"{}\"", + state.effective_state(), + ))), + + DbVmmState::Destroyed | DbVmmState::SagaUnwound => { + Err(Error::invalid_request( + "cannot connect to serial console of instance in state \"Stopped\"", + )) } - - DbVmmState::Destroyed | DbVmmState::SagaUnwound => Err(Error::invalid_request( - "cannot connect to serial console of instance in state \"Stopped\"", - )), } } else { Err(Error::invalid_request(format!( @@ -2262,7 +2272,7 @@ fn instance_start_allowed( return Err(Error::conflict(&format!( "instance is in state {s} but it must be {} to be started", InstanceState::Stopped - ))) + ))); } } } @@ -2426,12 +2436,14 @@ mod tests { let (mut instance, _vmm) = make_instance_and_vmm(); instance.runtime_state.nexus_state = DbInstanceState::NoVmm; let state = InstanceAndActiveVmm::from((instance, None)); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_ok()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_ok() + ); logctx.cleanup_successful(); } @@ -2445,12 +2457,14 @@ mod tests { instance.runtime_state.propolis_id = Some(vmm.id); vmm.runtime.state = DbVmmState::SagaUnwound; let state = InstanceAndActiveVmm::from((instance, Some(vmm))); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_ok()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_ok() + ); logctx.cleanup_successful(); } @@ -2461,12 +2475,14 @@ mod tests { let (mut instance, _vmm) = make_instance_and_vmm(); instance.runtime_state.nexus_state = DbInstanceState::Creating; let state = InstanceAndActiveVmm::from((instance, None)); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_err()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_err() + ); logctx.cleanup_successful(); } @@ -2479,41 +2495,49 @@ mod tests { vmm.runtime.state = DbVmmState::Starting; let state = InstanceAndActiveVmm::from((instance.clone(), Some(vmm.clone()))); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_ok()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_ok() + ); vmm.runtime.state = DbVmmState::Running; let state = InstanceAndActiveVmm::from((instance.clone(), Some(vmm.clone()))); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_ok()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_ok() + ); vmm.runtime.state = DbVmmState::Rebooting; let state = InstanceAndActiveVmm::from((instance.clone(), Some(vmm.clone()))); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_ok()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_ok() + ); vmm.runtime.state = DbVmmState::Migrating; let state = InstanceAndActiveVmm::from((instance, Some(vmm))); - assert!(instance_start_allowed( - &logctx.log, - &state, - instance_start::Reason::User - ) - .is_ok()); + assert!( + instance_start_allowed( + &logctx.log, + &state, + instance_start::Reason::User + ) + .is_ok() + ); logctx.cleanup_successful(); } } diff --git a/nexus/src/app/instance_network.rs b/nexus/src/app/instance_network.rs index dc4162d3536..5472383b8d3 100644 --- a/nexus/src/app/instance_network.rs +++ b/nexus/src/app/instance_network.rs @@ -13,8 +13,8 @@ use nexus_db_model::Ipv4NatValues; use nexus_db_model::Vni as DbVni; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; -use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::lookup::LookupPath; use omicron_common::api::external::Error; use omicron_common::api::internal::shared::NetworkInterface; use omicron_common::api::internal::shared::SwitchLocation; @@ -26,8 +26,8 @@ use std::collections::HashSet; use std::str::FromStr; use uuid::Uuid; -use super::background::BackgroundTasks; use super::Nexus; +use super::background::BackgroundTasks; impl Nexus { /// Returns the set of switches with uplinks configured and boundary diff --git a/nexus/src/app/internet_gateway.rs b/nexus/src/app/internet_gateway.rs index 9afa0bc38cc..610e6e86d1e 100644 --- a/nexus/src/app/internet_gateway.rs +++ b/nexus/src/app/internet_gateway.rs @@ -11,13 +11,13 @@ use nexus_db_queries::db; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; +use omicron_common::api::external::http_pagination::PaginatedBy; use uuid::Uuid; impl super::Nexus { @@ -33,7 +33,7 @@ impl super::Nexus { params::InternetGatewaySelector { gateway: NameOrId::Id(id), vpc: None, - project: None + project: None, } => { let gw = LookupPath::new(opctx, &self.db_datastore) .internet_gateway_id(id); @@ -42,7 +42,7 @@ impl super::Nexus { params::InternetGatewaySelector { gateway: NameOrId::Name(name), vpc: Some(vpc), - project + project, } => { let gw = self .vpc_lookup(opctx, params::VpcSelector { project, vpc })? @@ -170,7 +170,11 @@ impl super::Nexus { let route = self .internet_gateway_lookup( opctx, - params::InternetGatewaySelector { project, vpc, gateway }, + params::InternetGatewaySelector { + project, + vpc, + gateway, + }, )? .internet_gateway_ip_pool_name_owned(name.into()); Ok(route) @@ -296,7 +300,11 @@ impl super::Nexus { let route = self .internet_gateway_lookup( opctx, - params::InternetGatewaySelector { project, vpc, gateway }, + params::InternetGatewaySelector { + project, + vpc, + gateway, + }, )? .internet_gateway_ip_address_name_owned(name.into()); Ok(route) diff --git a/nexus/src/app/ip_pool.rs b/nexus/src/app/ip_pool.rs index 4e276731a2b..f51b1184c90 100644 --- a/nexus/src/app/ip_pool.rs +++ b/nexus/src/app/ip_pool.rs @@ -15,7 +15,6 @@ use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::Name; use nexus_types::identity::Resource; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DataPageParams; use omicron_common::api::external::DeleteResult; @@ -26,6 +25,7 @@ use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::ResourceType; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use std::matches; use uuid::Uuid; diff --git a/nexus/src/app/login.rs b/nexus/src/app/login.rs index 93a1d0444bf..4b935735d1e 100644 --- a/nexus/src/app/login.rs +++ b/nexus/src/app/login.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use dropshot::{http_response_found, HttpError, HttpResponseFound}; +use dropshot::{HttpError, HttpResponseFound, http_response_found}; use nexus_auth::context::OpContext; use nexus_db_model::{ConsoleSession, Name}; use nexus_db_queries::authn::silos::IdentityProviderType; diff --git a/nexus/src/app/mod.rs b/nexus/src/app/mod.rs index db87d7db7d7..5a8b612d537 100644 --- a/nexus/src/app/mod.rs +++ b/nexus/src/app/mod.rs @@ -6,12 +6,12 @@ use self::external_endpoints::NexusCertResolver; use self::saga::SagaExecutor; +use crate::DropshotServer; use crate::app::background::BackgroundTasksData; use crate::app::background::SagaRecoveryHelpers; -use crate::populate::populate_start; use crate::populate::PopulateArgs; use crate::populate::PopulateStatus; -use crate::DropshotServer; +use crate::populate::populate_start; use ::oximeter::types::ProducerRegistry; use anyhow::anyhow; use internal_dns_types::names::ServiceName; @@ -31,8 +31,8 @@ use omicron_common::api::external::Error; use omicron_common::api::internal::shared::SwitchLocation; use omicron_uuid_kinds::OmicronZoneUuid; use oximeter_producer::Server as ProducerServer; -use sagas::common_storage::make_pantry_connection_pool; use sagas::common_storage::PooledPantryClient; +use sagas::common_storage::make_pantry_connection_pool; use slog::Logger; use std::collections::HashMap; use std::net::SocketAddrV6; @@ -613,7 +613,7 @@ impl Nexus { PopulateStatus::NotDone => (), PopulateStatus::Done => return Ok(()), PopulateStatus::Failed(error) => { - return Err(anyhow!(error.clone())) + return Err(anyhow!(error.clone())); } }; } @@ -1192,7 +1192,10 @@ async fn map_switch_zone_addrs( switch_zone_addrs.insert(SwitchLocation::Switch1, addr); } _ => { - warn!(log, "Expected a slot number of 0 or 1, found {switch_slot:#?} when querying {addr:#?}"); + warn!( + log, + "Expected a slot number of 0 or 1, found {switch_slot:#?} when querying {addr:#?}" + ); } }; } diff --git a/nexus/src/app/network_interface.rs b/nexus/src/app/network_interface.rs index fef8e9d1ac6..2df15ec6e25 100644 --- a/nexus/src/app/network_interface.rs +++ b/nexus/src/app/network_interface.rs @@ -9,8 +9,8 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::InstanceUuid; use uuid::Uuid; @@ -29,7 +29,7 @@ impl super::Nexus { params::InstanceNetworkInterfaceSelector { network_interface: NameOrId::Id(id), instance: None, - project: None + project: None, } => { let network_interface = LookupPath::new(opctx, &self.db_datastore) @@ -39,26 +39,25 @@ impl super::Nexus { params::InstanceNetworkInterfaceSelector { network_interface: NameOrId::Name(name), instance: Some(instance), - project + project, } => { let network_interface = self - .instance_lookup(opctx, params::InstanceSelector { project, instance })? + .instance_lookup( + opctx, + params::InstanceSelector { project, instance }, + )? .instance_network_interface_name_owned(name.into()); Ok(network_interface) } params::InstanceNetworkInterfaceSelector { - network_interface: NameOrId::Id(_), - .. - } => { - Err(Error::invalid_request( - "when providing network_interface as an id instance and project should not be specified" - )) - } - _ => { - Err(Error::invalid_request( - "network_interface should either be a UUID or instance should be specified" - )) - } + network_interface: NameOrId::Id(_), + .. + } => Err(Error::invalid_request( + "when providing network_interface as an id instance and project should not be specified", + )), + _ => Err(Error::invalid_request( + "network_interface should either be a UUID or instance should be specified", + )), } } diff --git a/nexus/src/app/oximeter.rs b/nexus/src/app/oximeter.rs index 708b0828c9b..3fbc60367a3 100644 --- a/nexus/src/app/oximeter.rs +++ b/nexus/src/app/oximeter.rs @@ -13,8 +13,8 @@ use nexus_db_queries::db::DataStore; use omicron_common::api::external::{DataPageParams, Error, ListResultVec}; use omicron_common::api::internal::nexus::{self, ProducerEndpoint}; use oximeter_client::Client as OximeterClient; -use oximeter_db::query::Timestamp; use oximeter_db::Measurement; +use oximeter_db::query::Timestamp; use std::net::SocketAddr; use std::num::NonZeroU32; use std::time::Duration; diff --git a/nexus/src/app/probe.rs b/nexus/src/app/probe.rs index 67673d8e001..f4b5602a7d0 100644 --- a/nexus/src/app/probe.rs +++ b/nexus/src/app/probe.rs @@ -7,8 +7,8 @@ use nexus_types::external_api::shared::ProbeInfo; use nexus_types::identity::Resource; use omicron_common::api::external::Error; use omicron_common::api::external::{ - http_pagination::PaginatedBy, CreateResult, DataPageParams, DeleteResult, - ListResultVec, LookupResult, NameOrId, + CreateResult, DataPageParams, DeleteResult, ListResultVec, LookupResult, + NameOrId, http_pagination::PaginatedBy, }; use uuid::Uuid; diff --git a/nexus/src/app/project.rs b/nexus/src/app/project.rs index 8f31e74728f..531fad4fb22 100644 --- a/nexus/src/app/project.rs +++ b/nexus/src/app/project.rs @@ -14,7 +14,6 @@ use nexus_db_queries::context::OpContext; use nexus_db_queries::db; use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -23,6 +22,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use std::sync::Arc; impl super::Nexus { diff --git a/nexus/src/app/rack.rs b/nexus/src/app/rack.rs index 75e19d67398..5ea15555859 100644 --- a/nexus/src/app/rack.rs +++ b/nexus/src/app/rack.rs @@ -12,8 +12,8 @@ use gateway_client::types::SpType; use internal_dns_types::names::DNS_ZONE; use ipnetwork::{IpNetwork, Ipv6Network}; use nexus_db_model::DnsGroup; -use nexus_db_model::InitialDnsGroup; use nexus_db_model::INFRA_LOT; +use nexus_db_model::InitialDnsGroup; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; @@ -21,11 +21,11 @@ use nexus_db_queries::db::datastore::DnsVersionUpdateBuilder; use nexus_db_queries::db::datastore::RackInit; use nexus_db_queries::db::datastore::SledUnderlayAllocationResult; use nexus_db_queries::db::lookup::LookupPath; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; use nexus_types::deployment::CockroachDbClusterVersion; use nexus_types::deployment::SledFilter; +use nexus_types::deployment::blueprint_zone_type; use nexus_types::external_api::params::Address; use nexus_types::external_api::params::AddressConfig; use nexus_types::external_api::params::AddressLotBlockCreate; @@ -49,7 +49,7 @@ use nexus_types::external_api::shared::UninitializedSled; use nexus_types::external_api::views; use nexus_types::internal_api::params::DnsRecord; use nexus_types::silo::silo_dns_name; -use omicron_common::address::{get_64_subnet, Ipv6Subnet, RACK_PREFIX}; +use omicron_common::address::{Ipv6Subnet, RACK_PREFIX, get_64_subnet}; use omicron_common::api::external::AddressLotKind; use omicron_common::api::external::BgpPeer; use omicron_common::api::external::DataPageParams; @@ -165,7 +165,9 @@ impl super::Nexus { CertificateCreate { identity: IdentityMetadataCreateParams { name: Name::try_from(format!("default-{i}")).unwrap(), - description: format!("x.509 certificate #{i} initialized at rack install"), + description: format!( + "x.509 certificate #{i} initialized at rack install" + ), }, cert: c.cert, key: c.key, @@ -699,7 +701,7 @@ impl super::Nexus { ) .await?; } // TODO - https://github.com/oxidecomputer/omicron/issues/3277 - // record port speed + // record port speed self.db_datastore .rack_set_initialized( @@ -958,12 +960,12 @@ pub fn rack_subnet( Some(IpNetwork::V4(_)) => { return Err(Error::InternalError { internal_message: "rack subnet not IPv6".into(), - }) + }); } None => { return Err(Error::InternalError { internal_message: "rack subnet not set".into(), - }) + }); } } } diff --git a/nexus/src/app/saga.rs b/nexus/src/app/saga.rs index 93dc5a135ac..1d1b77b020e 100644 --- a/nexus/src/app/saga.rs +++ b/nexus/src/app/saga.rs @@ -48,14 +48,14 @@ //! * Tests can use any of the lower-level pieces to examine intermediate state //! or inject errors. -use super::sagas::NexusSaga; use super::sagas::ACTION_REGISTRY; -use crate::saga_interface::SagaContext; +use super::sagas::NexusSaga; use crate::Nexus; +use crate::saga_interface::SagaContext; use anyhow::Context; -use futures::future::BoxFuture; use futures::FutureExt; use futures::StreamExt; +use futures::future::BoxFuture; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_types::internal_api::views::DemoSaga; diff --git a/nexus/src/app/sagas/common_storage.rs b/nexus/src/app/sagas/common_storage.rs index 3c6b5215608..ea32aa47be6 100644 --- a/nexus/src/app/sagas/common_storage.rs +++ b/nexus/src/app/sagas/common_storage.rs @@ -23,8 +23,8 @@ use std::net::SocketAddrV6; mod pantry_pool; -pub(crate) use pantry_pool::make_pantry_connection_pool; pub(crate) use pantry_pool::PooledPantryClient; +pub(crate) use pantry_pool::make_pantry_connection_pool; // Common Pantry operations diff --git a/nexus/src/app/sagas/common_storage/pantry_pool.rs b/nexus/src/app/sagas/common_storage/pantry_pool.rs index e19d526c91c..cddf0f3889a 100644 --- a/nexus/src/app/sagas/common_storage/pantry_pool.rs +++ b/nexus/src/app/sagas/common_storage/pantry_pool.rs @@ -4,8 +4,8 @@ //! `qorb` support for Crucible pantry connection pooling. -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use internal_dns_resolver::QorbResolver; use internal_dns_types::names::ServiceName; use qorb::backend; diff --git a/nexus/src/app/sagas/disk_create.rs b/nexus/src/app/sagas/disk_create.rs index 9f920d0baa5..155e1567b16 100644 --- a/nexus/src/app/sagas/disk_create.rs +++ b/nexus/src/app/sagas/disk_create.rs @@ -3,12 +3,12 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::{ + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, common_storage::{ call_pantry_attach_for_disk, call_pantry_detach_for_disk, get_pantry_address, }, - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, }; use crate::app::sagas::declare_saga_actions; use crate::app::{authn, authz, db}; @@ -18,7 +18,7 @@ use nexus_db_queries::db::lookup::LookupPath; use omicron_common::api::external::DiskState; use omicron_common::api::external::Error; use omicron_uuid_kinds::VolumeUuid; -use rand::{rngs::StdRng, RngCore, SeedableRng}; +use rand::{RngCore, SeedableRng, rngs::StdRng}; use serde::Deserialize; use serde::Serialize; use sled_agent_client::{CrucibleOpts, VolumeConstructionRequest}; @@ -569,7 +569,11 @@ async fn sdc_regions_ensure_undo( // the disk that the saga created: change that disk's state to // Faulted here. - error!(log, "sdc_regions_ensure_undo: Deleting crucible regions failed with {}", e); + error!( + log, + "sdc_regions_ensure_undo: Deleting crucible regions failed with {}", + e + ); let disk_id = sagactx.lookup::("disk_id")?; let (.., authz_disk, db_disk) = LookupPath::new(&opctx, &datastore) diff --git a/nexus/src/app/sagas/disk_delete.rs b/nexus/src/app/sagas/disk_delete.rs index 296216f0897..1af2e53fd3a 100644 --- a/nexus/src/app/sagas/disk_delete.rs +++ b/nexus/src/app/sagas/disk_delete.rs @@ -5,9 +5,9 @@ use super::ActionRegistry; use super::NexusActionContext; use super::NexusSaga; +use crate::app::sagas::SagaInitError; use crate::app::sagas::declare_saga_actions; use crate::app::sagas::volume_delete; -use crate::app::sagas::SagaInitError; use nexus_db_queries::authn; use nexus_db_queries::db; use omicron_common::api::external::DiskState; @@ -188,8 +188,8 @@ pub(crate) mod test { use nexus_db_model::Disk; use nexus_db_queries::authn::saga::Serialized; use nexus_db_queries::context::OpContext; - use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::DiskTest; + use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use omicron_common::api::external::Name; diff --git a/nexus/src/app/sagas/finalize_disk.rs b/nexus/src/app/sagas/finalize_disk.rs index 59c9b7dada2..abcf2eaf59a 100644 --- a/nexus/src/app/sagas/finalize_disk.rs +++ b/nexus/src/app/sagas/finalize_disk.rs @@ -5,11 +5,11 @@ //! For disks in state ImportReady, "finalize" them: detach them from their //! attached Pantry, and set to Detached. -use super::declare_saga_actions; use super::ActionRegistry; use super::NexusActionContext; use super::NexusSaga; use super::SagaInitError; +use super::declare_saga_actions; use crate::app::sagas::common_storage::call_pantry_detach_for_disk; use crate::app::sagas::snapshot_create; use crate::external_api::params; diff --git a/nexus/src/app/sagas/instance_common.rs b/nexus/src/app/sagas/instance_common.rs index 22134e8f6d1..5e428bd1454 100644 --- a/nexus/src/app/sagas/instance_common.rs +++ b/nexus/src/app/sagas/instance_common.rs @@ -285,18 +285,18 @@ pub(super) async fn instance_ip_get_instance_state( return Err(ActionError::action_failed(Error::not_found_by_id( omicron_common::api::external::ResourceType::Instance, &authz_instance.id(), - ))) + ))); } (InstanceState::Creating, _) => { return Err(ActionError::action_failed(Error::invalid_request( "cannot modify instance IPs, instance is still being created", - ))) + ))); } (InstanceState::Failed, _) | (InstanceState::Vmm, Some(VmmState::Failed)) => { return Err(ActionError::action_failed(Error::invalid_request( "cannot modify instance IPs, instance is in unhealthy state", - ))) + ))); } // This case represents an inconsistency in the database. It should diff --git a/nexus/src/app/sagas/instance_create.rs b/nexus/src/app/sagas/instance_create.rs index d9aae35596f..956370cd543 100644 --- a/nexus/src/app/sagas/instance_create.rs +++ b/nexus/src/app/sagas/instance_create.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{NexusActionContext, NexusSaga, SagaInitError, ACTION_GENERATE_ID}; +use super::{ACTION_GENERATE_ID, NexusActionContext, NexusSaga, SagaInitError}; use crate::app::sagas::declare_saga_actions; use crate::app::sagas::disk_create::{self, SagaDiskCreate}; use crate::app::{ @@ -763,9 +763,11 @@ async fn sic_allocate_instance_external_ip( .map_err(ActionError::action_failed)?; if authz_project.id() != saga_params.project_id { - return Err(ActionError::action_failed(Error::invalid_request( - "floating IP must be in the same project as the instance" - ))); + return Err(ActionError::action_failed( + Error::invalid_request( + "floating IP must be in the same project as the instance", + ), + )); } datastore @@ -1157,10 +1159,10 @@ pub mod test { use nexus_db_queries::authn::saga::Serialized; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::datastore::DataStore; + use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_disk; use nexus_test_utils::resource_helpers::create_project; - use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use omicron_common::api::external::{ ByteCount, IdentityMetadataCreateParams, InstanceCpuCount, diff --git a/nexus/src/app/sagas/instance_delete.rs b/nexus/src/app/sagas/instance_delete.rs index 780f0407a3b..d38a18c9560 100644 --- a/nexus/src/app/sagas/instance_delete.rs +++ b/nexus/src/app/sagas/instance_delete.rs @@ -169,10 +169,10 @@ mod test { use nexus_db_queries::{ authn::saga::Serialized, context::OpContext, db, db::lookup::LookupPath, }; + use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_disk; use nexus_test_utils::resource_helpers::create_project; - use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use nexus_types::identity::Resource; use omicron_common::api::external::{ diff --git a/nexus/src/app/sagas/instance_ip_attach.rs b/nexus/src/app/sagas/instance_ip_attach.rs index 7fb5f61628b..cf1789f12be 100644 --- a/nexus/src/app/sagas/instance_ip_attach.rs +++ b/nexus/src/app/sagas/instance_ip_attach.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::instance_common::{ + ExternalIpAttach, ModifyStateForExternalIp, VmmAndSledIds, instance_ip_add_nat, instance_ip_add_opte, instance_ip_get_instance_state, - instance_ip_move_state, instance_ip_remove_opte, ExternalIpAttach, - ModifyStateForExternalIp, VmmAndSledIds, + instance_ip_move_state, instance_ip_remove_opte, }; use super::{ActionRegistry, NexusActionContext, NexusSaga}; use crate::app::sagas::declare_saga_actions; @@ -438,12 +438,16 @@ pub(crate) mod test { { let mut eips = sled_agent.external_ips.lock().unwrap(); let my_eips = eips.entry(vmm_id).or_default(); - assert!(my_eips - .iter() - .any(|v| matches!(v, InstanceExternalIpBody::Floating(_)))); - assert!(my_eips - .iter() - .any(|v| matches!(v, InstanceExternalIpBody::Ephemeral(_)))); + assert!( + my_eips + .iter() + .any(|v| matches!(v, InstanceExternalIpBody::Floating(_))) + ); + assert!( + my_eips + .iter() + .any(|v| matches!(v, InstanceExternalIpBody::Ephemeral(_))) + ); } // DB has records for SNAT plus the new IPs. @@ -469,28 +473,32 @@ pub(crate) mod test { let conn = datastore.pool_connection_for_tests().await.unwrap(); // No Floating IPs exist in states other than 'detached'. - assert!(dsl::external_ip - .filter(dsl::kind.eq(IpKind::Floating)) - .filter(dsl::time_deleted.is_null()) - .filter(dsl::parent_id.eq(instance_id.into_untyped_uuid())) - .filter(dsl::state.ne(IpAttachState::Detached)) - .select(ExternalIp::as_select()) - .first_async::(&*conn) - .await - .optional() - .unwrap() - .is_none()); + assert!( + dsl::external_ip + .filter(dsl::kind.eq(IpKind::Floating)) + .filter(dsl::time_deleted.is_null()) + .filter(dsl::parent_id.eq(instance_id.into_untyped_uuid())) + .filter(dsl::state.ne(IpAttachState::Detached)) + .select(ExternalIp::as_select()) + .first_async::(&*conn) + .await + .optional() + .unwrap() + .is_none() + ); // All ephemeral IPs are removed. - assert!(dsl::external_ip - .filter(dsl::kind.eq(IpKind::Ephemeral)) - .filter(dsl::time_deleted.is_null()) - .select(ExternalIp::as_select()) - .first_async::(&*conn) - .await - .optional() - .unwrap() - .is_none()); + assert!( + dsl::external_ip + .filter(dsl::kind.eq(IpKind::Ephemeral)) + .filter(dsl::time_deleted.is_null()) + .select(ExternalIp::as_select()) + .first_async::(&*conn) + .await + .optional() + .unwrap() + .is_none() + ); // No IP bindings remain on sled-agent. let VmmAndSledIds { vmm_id, .. } = diff --git a/nexus/src/app/sagas/instance_ip_detach.rs b/nexus/src/app/sagas/instance_ip_detach.rs index 321ae65c2a9..543ec8e08bd 100644 --- a/nexus/src/app/sagas/instance_ip_detach.rs +++ b/nexus/src/app/sagas/instance_ip_detach.rs @@ -3,9 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::instance_common::{ - instance_ip_add_nat, instance_ip_add_opte, instance_ip_get_instance_state, + ModifyStateForExternalIp, VmmAndSledIds, instance_ip_add_nat, + instance_ip_add_opte, instance_ip_get_instance_state, instance_ip_move_state, instance_ip_remove_nat, instance_ip_remove_opte, - ModifyStateForExternalIp, VmmAndSledIds, }; use super::{ActionRegistry, NexusActionContext, NexusSaga}; use crate::app::sagas::declare_saga_actions; @@ -281,6 +281,7 @@ impl NexusSaga for SagaInstanceIpDetach { pub(crate) mod test { use super::*; use crate::{ + Nexus, app::{ saga::create_saga_dag, sagas::{ @@ -288,7 +289,6 @@ pub(crate) mod test { test_helpers, }, }, - Nexus, }; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ @@ -433,27 +433,31 @@ pub(crate) mod test { let conn = datastore.pool_connection_for_tests().await.unwrap(); // No IPs in transitional states w/ current instance. - assert!(dsl::external_ip - .filter(dsl::time_deleted.is_null()) - .filter(dsl::parent_id.eq(instance_id)) - .filter(dsl::state.ne(IpAttachState::Attached)) - .select(ExternalIp::as_select()) - .first_async::(&*conn) - .await - .optional() - .unwrap() - .is_none()); + assert!( + dsl::external_ip + .filter(dsl::time_deleted.is_null()) + .filter(dsl::parent_id.eq(instance_id)) + .filter(dsl::state.ne(IpAttachState::Attached)) + .select(ExternalIp::as_select()) + .first_async::(&*conn) + .await + .optional() + .unwrap() + .is_none() + ); // No external IPs in detached state. - assert!(dsl::external_ip - .filter(dsl::time_deleted.is_null()) - .filter(dsl::state.eq(IpAttachState::Detached)) - .select(ExternalIp::as_select()) - .first_async::(&*conn) - .await - .optional() - .unwrap() - .is_none()); + assert!( + dsl::external_ip + .filter(dsl::time_deleted.is_null()) + .filter(dsl::state.eq(IpAttachState::Detached)) + .select(ExternalIp::as_select()) + .first_async::(&*conn) + .await + .optional() + .unwrap() + .is_none() + ); // Instance still has one Ephemeral IP, and one Floating IP. let db_eips = datastore diff --git a/nexus/src/app/sagas/instance_migrate.rs b/nexus/src/app/sagas/instance_migrate.rs index 465105a813f..4eb976ed1e4 100644 --- a/nexus/src/app/sagas/instance_migrate.rs +++ b/nexus/src/app/sagas/instance_migrate.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::{NexusActionContext, NexusSaga, ACTION_GENERATE_ID}; +use super::{ACTION_GENERATE_ID, NexusActionContext, NexusSaga}; use crate::app::instance::{ InstanceEnsureRegisteredApiResources, InstanceRegisterReason, InstanceStateChangeError, InstanceStateChangeRequest, @@ -188,7 +188,7 @@ async fn sim_reserve_sled_resources( osagactx.nexus(), InstanceUuid::from_untyped_uuid(params.instance.id()), propolis_id, - u32::from(params.instance.ncpus.0 .0), + u32::from(params.instance.ncpus.0.0), params.instance.memory, constraints, ) @@ -482,11 +482,7 @@ async fn sim_ensure_destination_propolis_undo( { Ok(_) => Ok(()), Err(InstanceStateChangeError::SledAgent(inner)) => { - if !inner.vmm_gone() { - Ok(()) - } else { - Err(inner.0.into()) - } + if !inner.vmm_gone() { Ok(()) } else { Err(inner.0.into()) } } Err(e) => Err(e.into()), } diff --git a/nexus/src/app/sagas/instance_start.rs b/nexus/src/app/sagas/instance_start.rs index e6af6453291..48ffb621945 100644 --- a/nexus/src/app/sagas/instance_start.rs +++ b/nexus/src/app/sagas/instance_start.rs @@ -7,8 +7,8 @@ use std::net::Ipv6Addr; use super::{ - instance_common::allocate_vmm_ipv6, NexusActionContext, NexusSaga, - SagaInitError, + NexusActionContext, NexusSaga, SagaInitError, + instance_common::allocate_vmm_ipv6, }; use crate::app::instance::{ InstanceEnsureRegisteredApiResources, InstanceRegisterReason, @@ -438,7 +438,7 @@ async fn sis_account_virtual_resources( &opctx, instance_id, params.db_instance.project_id, - i64::from(params.db_instance.ncpus.0 .0), + i64::from(params.db_instance.ncpus.0.0), nexus_db_model::ByteCount(*params.db_instance.memory), ) .await @@ -464,7 +464,7 @@ async fn sis_account_virtual_resources_undo( &opctx, instance_id, params.db_instance.project_id, - i64::from(params.db_instance.ncpus.0 .0), + i64::from(params.db_instance.ncpus.0.0), nexus_db_model::ByteCount(*params.db_instance.memory), ) .await diff --git a/nexus/src/app/sagas/instance_update/destroyed.rs b/nexus/src/app/sagas/instance_update/destroyed.rs index 243f952c8bf..ac0382a53f9 100644 --- a/nexus/src/app/sagas/instance_update/destroyed.rs +++ b/nexus/src/app/sagas/instance_update/destroyed.rs @@ -3,8 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use super::{ - declare_saga_actions, ActionRegistry, DagBuilder, NexusActionContext, - NexusSaga, SagaInitError, + ActionRegistry, DagBuilder, NexusActionContext, NexusSaga, SagaInitError, + declare_saga_actions, }; use crate::app::sagas::ActionError; use nexus_db_queries::authn; diff --git a/nexus/src/app/sagas/instance_update/mod.rs b/nexus/src/app/sagas/instance_update/mod.rs index 206ecb85afe..434ca022ded 100644 --- a/nexus/src/app/sagas/instance_update/mod.rs +++ b/nexus/src/app/sagas/instance_update/mod.rs @@ -341,12 +341,12 @@ //! tasks, as appropriate. use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; -use crate::app::db::datastore::instance; use crate::app::db::datastore::InstanceGestalt; use crate::app::db::datastore::VmmStateUpdateResult; +use crate::app::db::datastore::instance; use crate::app::db::lookup::LookupPath; use crate::app::db::model::ByteCount; use crate::app::db::model::Generation; @@ -698,7 +698,7 @@ impl UpdatesRequired { // that the instance's oximeter producer should be cleaned up. Some(Deprovision { project_id: snapshot.instance.project_id, - cpus_diff: i64::from(snapshot.instance.ncpus.0 .0), + cpus_diff: i64::from(snapshot.instance.ncpus.0.0), ram_diff: snapshot.instance.memory, }) } else { @@ -1372,7 +1372,7 @@ async fn unwind_instance_lock( // - fails *because the instance doesn't exist*, in which case we can die // happily because it doesn't matter if the instance is actually unlocked. use dropshot::HttpError; - use futures::{future, TryFutureExt}; + use futures::{TryFutureExt, future}; use omicron_common::backoff; let osagactx = sagactx.user_data(); @@ -1470,11 +1470,11 @@ async fn unwind_instance_lock( #[cfg(test)] mod test { use super::*; + use crate::app::OpContext; use crate::app::db::model::Instance; use crate::app::db::model::VmmRuntimeState; use crate::app::saga::create_saga_dag; use crate::app::sagas::test_helpers; - use crate::app::OpContext; use crate::external_api::params; use chrono::Utc; use dropshot::test_util::ClientTestContext; diff --git a/nexus/src/app/sagas/instance_update/start.rs b/nexus/src/app/sagas/instance_update/start.rs index fbd8cbffc23..ec3e93553ad 100644 --- a/nexus/src/app/sagas/instance_update/start.rs +++ b/nexus/src/app/sagas/instance_update/start.rs @@ -5,9 +5,9 @@ // instance update start saga use super::{ - ActionRegistry, NexusActionContext, NexusSaga, RealParams, - SagaDoActualInstanceUpdate, SagaInitError, UpdatesRequired, - ACTION_GENERATE_ID, INSTANCE_LOCK, INSTANCE_LOCK_ID, + ACTION_GENERATE_ID, ActionRegistry, INSTANCE_LOCK, INSTANCE_LOCK_ID, + NexusActionContext, NexusSaga, RealParams, SagaDoActualInstanceUpdate, + SagaInitError, UpdatesRequired, }; use crate::app::saga; use crate::app::sagas::declare_saga_actions; diff --git a/nexus/src/app/sagas/mod.rs b/nexus/src/app/sagas/mod.rs index f8020346116..361c2ca7881 100644 --- a/nexus/src/app/sagas/mod.rs +++ b/nexus/src/app/sagas/mod.rs @@ -12,13 +12,13 @@ use crate::saga_interface::SagaContext; use std::sync::Arc; use std::sync::LazyLock; -use steno::new_action_noop_undo; use steno::ActionContext; use steno::ActionError; use steno::DagBuilder; use steno::SagaDag; use steno::SagaName; use steno::SagaType; +use steno::new_action_noop_undo; use thiserror::Error; use uuid::Uuid; diff --git a/nexus/src/app/sagas/region_replacement_drive.rs b/nexus/src/app/sagas/region_replacement_drive.rs index 48430177fd9..71c2f125471 100644 --- a/nexus/src/app/sagas/region_replacement_drive.rs +++ b/nexus/src/app/sagas/region_replacement_drive.rs @@ -137,8 +137,8 @@ //! use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; use crate::app::db::datastore::InstanceAndActiveVmm; use crate::app::db::lookup::LookupPath; @@ -944,10 +944,12 @@ async fn srrd_drive_region_replacement_prepare( | VmmState::Creating => { // Propolis server is not ok to receive volume // replacement requests, bail out - return Err(ActionError::action_failed(format!( - "vmm {} propolis not in a state to receive request", - vmm.id, - ))); + return Err(ActionError::action_failed( + format!( + "vmm {} propolis not in a state to receive request", + vmm.id, + ), + )); } } @@ -1302,78 +1304,80 @@ async fn execute_pantry_drive_action( // // Try to get the volume's status in order to check. - let detach_required = - match client.volume_status(&volume_id.to_string()).await { - Ok(volume_status) => { - info!( - log, - "volume is already attached with status {volume_status:?}"; - "region replacement id" => %request_id, - "volume id" => ?volume_id, - "endpoint" => endpoint.clone(), - ); + let detach_required = match client + .volume_status(&volume_id.to_string()) + .await + { + Ok(volume_status) => { + info!( + log, + "volume is already attached with status {volume_status:?}"; + "region replacement id" => %request_id, + "volume id" => ?volume_id, + "endpoint" => endpoint.clone(), + ); - // In the case where this forward action is being rerun, - // detaching the volume would mean that the reconciliation would - // be interrupted. This is ok, as that operation can be - // interrupted at any time. + // In the case where this forward action is being rerun, + // detaching the volume would mean that the reconciliation would + // be interrupted. This is ok, as that operation can be + // interrupted at any time. - // Detach this volume so we can reattach with this saga's job id. - true - } + // Detach this volume so we can reattach with this saga's job id. + true + } - Err(e) => { - match e { - crucible_pantry_client::Error::ErrorResponse(ref rv) => { - match rv.status() { - http::StatusCode::NOT_FOUND => { - // No detach required, this Volume isn't attached to - // this Pantry. - false - } + Err(e) => { + match e { + crucible_pantry_client::Error::ErrorResponse(ref rv) => { + match rv.status() { + http::StatusCode::NOT_FOUND => { + // No detach required, this Volume isn't attached to + // this Pantry. + false + } - http::StatusCode::GONE => { - // 410 Gone means detach is required - it was - // previously attached and may have been activated - true - } + http::StatusCode::GONE => { + // 410 Gone means detach is required - it was + // previously attached and may have been activated + true + } - _ => { - error!( - log, - "error checking volume status: {e}"; - "region replacement id" => %request_id, - "volume id" => ?volume_id, - "endpoint" => endpoint.clone(), - ); + _ => { + error!( + log, + "error checking volume status: {e}"; + "region replacement id" => %request_id, + "volume id" => ?volume_id, + "endpoint" => endpoint.clone(), + ); - return Err(ActionError::action_failed( - Error::internal_error(&format!( + return Err(ActionError::action_failed( + Error::internal_error(&format!( "unexpected error from volume_status: {e}" )), - )); - } + )); } } + } - _ => { - error!( - log, - "error checking volume status: {e}"; - "region replacement id" => %request_id, - "volume id" => ?volume_id, - "endpoint" => endpoint.clone(), - ); + _ => { + error!( + log, + "error checking volume status: {e}"; + "region replacement id" => %request_id, + "volume id" => ?volume_id, + "endpoint" => endpoint.clone(), + ); - return Err(ActionError::action_failed( - Error::internal_error(&format!( - "unexpected error from volume_status: {e}" - )), - )); - } + return Err(ActionError::action_failed( + Error::internal_error(&format!( + "unexpected error from volume_status: {e}" + )), + )); } } - }; + } + }; if detach_required { info!( diff --git a/nexus/src/app/sagas/region_replacement_finish.rs b/nexus/src/app/sagas/region_replacement_finish.rs index 6291c179978..47d88159428 100644 --- a/nexus/src/app/sagas/region_replacement_finish.rs +++ b/nexus/src/app/sagas/region_replacement_finish.rs @@ -31,8 +31,8 @@ //! use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; use crate::app::sagas::declare_saga_actions; use crate::app::sagas::volume_delete; @@ -349,10 +349,8 @@ pub(crate) mod test { assert!(result.operating_saga_id.is_none()); // Validate the Volume was deleted - assert!(datastore - .volume_get(old_region_volume_id) - .await - .unwrap() - .is_none()); + assert!( + datastore.volume_get(old_region_volume_id).await.unwrap().is_none() + ); } } diff --git a/nexus/src/app/sagas/region_replacement_start.rs b/nexus/src/app/sagas/region_replacement_start.rs index a937f25cce7..f38f2ad5f33 100644 --- a/nexus/src/app/sagas/region_replacement_start.rs +++ b/nexus/src/app/sagas/region_replacement_start.rs @@ -46,13 +46,13 @@ //! steps in the process. use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; +use crate::app::RegionAllocationStrategy; use crate::app::db::datastore::VolumeReplaceResult; use crate::app::sagas::common_storage::find_only_new_region; use crate::app::sagas::declare_saga_actions; -use crate::app::RegionAllocationStrategy; use crate::app::{authn, db}; use nexus_db_queries::db::datastore::REGION_REDUNDANCY_THRESHOLD; use omicron_common::api::external::Error; @@ -763,12 +763,12 @@ async fn srrs_update_request_record( #[cfg(test)] pub(crate) mod test { use crate::{ - app::db::lookup::LookupPath, app::db::DataStore, - app::saga::create_saga_dag, - app::sagas::region_replacement_start::find_only_new_region, + app::RegionAllocationStrategy, app::db::DataStore, + app::db::lookup::LookupPath, app::saga::create_saga_dag, app::sagas::region_replacement_start::Params, app::sagas::region_replacement_start::SagaRegionReplacementStart, - app::sagas::test_helpers::test_opctx, app::RegionAllocationStrategy, + app::sagas::region_replacement_start::find_only_new_region, + app::sagas::test_helpers::test_opctx, }; use chrono::Utc; use nexus_db_model::CrucibleDataset; @@ -878,9 +878,9 @@ pub(crate) mod test { // Validate that one of the regions for the disk is the new one let new_region = datastore.get_region(result.new_region_id.unwrap()).await.unwrap(); - assert!(allocated_regions - .iter() - .any(|(_, region)| *region == new_region)); + assert!( + allocated_regions.iter().any(|(_, region)| *region == new_region) + ); // Validate the old region has the new volume id let old_region = diff --git a/nexus/src/app/sagas/region_snapshot_replacement_finish.rs b/nexus/src/app/sagas/region_snapshot_replacement_finish.rs index f99d523392d..cada7264178 100644 --- a/nexus/src/app/sagas/region_snapshot_replacement_finish.rs +++ b/nexus/src/app/sagas/region_snapshot_replacement_finish.rs @@ -31,8 +31,8 @@ //! Any unwind will place the state back into Running. use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; use crate::app::sagas::declare_saga_actions; use crate::app::sagas::volume_delete; diff --git a/nexus/src/app/sagas/region_snapshot_replacement_garbage_collect.rs b/nexus/src/app/sagas/region_snapshot_replacement_garbage_collect.rs index 0192f6ca04e..703baf10e1e 100644 --- a/nexus/src/app/sagas/region_snapshot_replacement_garbage_collect.rs +++ b/nexus/src/app/sagas/region_snapshot_replacement_garbage_collect.rs @@ -25,8 +25,8 @@ //! the next step(s) in the process. use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; use crate::app::sagas::declare_saga_actions; use crate::app::sagas::volume_delete; @@ -332,10 +332,12 @@ pub(crate) mod test { ); // Validate the Volume was deleted - assert!(datastore - .volume_get(old_snapshot_volume_id) - .await - .unwrap() - .is_none()); + assert!( + datastore + .volume_get(old_snapshot_volume_id) + .await + .unwrap() + .is_none() + ); } } diff --git a/nexus/src/app/sagas/region_snapshot_replacement_start.rs b/nexus/src/app/sagas/region_snapshot_replacement_start.rs index e302caa80db..d9e8a0349ba 100644 --- a/nexus/src/app/sagas/region_snapshot_replacement_start.rs +++ b/nexus/src/app/sagas/region_snapshot_replacement_start.rs @@ -48,9 +48,10 @@ //! saga for the next step in the process. use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; +use crate::app::RegionAllocationStrategy; use crate::app::db::datastore::ExistingTarget; use crate::app::db::datastore::RegionAllocationFor; use crate::app::db::datastore::RegionAllocationParameters; @@ -60,7 +61,6 @@ use crate::app::db::datastore::VolumeToDelete; use crate::app::db::datastore::VolumeWithTarget; use crate::app::sagas::common_storage::find_only_new_region; use crate::app::sagas::declare_saga_actions; -use crate::app::RegionAllocationStrategy; use crate::app::{authn, db}; use nexus_db_model::ReadOnlyTargetReplacement; use nexus_db_queries::db::datastore::NewRegionVolumeId; @@ -1218,10 +1218,10 @@ async fn rsrss_update_request_record( #[cfg(test)] pub(crate) mod test { use crate::{ - app::db::lookup::LookupPath, app::db::DataStore, - app::saga::create_saga_dag, + app::RegionAllocationStrategy, app::db::DataStore, + app::db::lookup::LookupPath, app::saga::create_saga_dag, app::sagas::region_snapshot_replacement_start::*, - app::sagas::test_helpers::test_opctx, app::RegionAllocationStrategy, + app::sagas::test_helpers::test_opctx, }; use nexus_db_model::PhysicalDiskPolicy; use nexus_db_model::RegionSnapshotReplacement; @@ -1229,11 +1229,11 @@ pub(crate) mod test { use nexus_db_model::Volume; use nexus_db_queries::authn::saga::Serialized; use nexus_db_queries::context::OpContext; + use nexus_test_utils::resource_helpers::DiskTest; + use nexus_test_utils::resource_helpers::DiskTestBuilder; use nexus_test_utils::resource_helpers::create_disk; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::create_snapshot; - use nexus_test_utils::resource_helpers::DiskTest; - use nexus_test_utils::resource_helpers::DiskTestBuilder; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::views; use nexus_types::identity::Asset; @@ -1411,10 +1411,12 @@ pub(crate) mod test { .await .unwrap(); - assert!(volumes - .iter() - .map(|v| v.id()) - .any(|vid| vid == db_snapshot.volume_id())); + assert!( + volumes + .iter() + .map(|v| v.id()) + .any(|vid| vid == db_snapshot.volume_id()) + ); } fn new_test_params( diff --git a/nexus/src/app/sagas/region_snapshot_replacement_step.rs b/nexus/src/app/sagas/region_snapshot_replacement_step.rs index a9382431d45..5a3fdaed93e 100644 --- a/nexus/src/app/sagas/region_snapshot_replacement_step.rs +++ b/nexus/src/app/sagas/region_snapshot_replacement_step.rs @@ -44,8 +44,8 @@ //! collect" saga for the next step in the process. use super::{ - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, }; use crate::app::db::datastore::ExistingTarget; use crate::app::db::datastore::ReplacementTarget; diff --git a/nexus/src/app/sagas/region_snapshot_replacement_step_garbage_collect.rs b/nexus/src/app/sagas/region_snapshot_replacement_step_garbage_collect.rs index 45afd980894..87fb9da9f2a 100644 --- a/nexus/src/app/sagas/region_snapshot_replacement_step_garbage_collect.rs +++ b/nexus/src/app/sagas/region_snapshot_replacement_step_garbage_collect.rs @@ -243,10 +243,12 @@ pub(crate) mod test { ); // Validate the Volume was deleted - assert!(datastore - .volume_get(old_snapshot_volume_id) - .await - .unwrap() - .is_none()); + assert!( + datastore + .volume_get(old_snapshot_volume_id) + .await + .unwrap() + .is_none() + ); } } diff --git a/nexus/src/app/sagas/snapshot_create.rs b/nexus/src/app/sagas/snapshot_create.rs index 99f59b3df46..fd185b97402 100644 --- a/nexus/src/app/sagas/snapshot_create.rs +++ b/nexus/src/app/sagas/snapshot_create.rs @@ -89,12 +89,12 @@ //! use super::{ + ACTION_GENERATE_ID, ActionRegistry, NexusActionContext, NexusSaga, + SagaInitError, common_storage::{ call_pantry_attach_for_disk, call_pantry_detach_for_disk, get_pantry_address, is_pantry_gone, }, - ActionRegistry, NexusActionContext, NexusSaga, SagaInitError, - ACTION_GENERATE_ID, }; use crate::app::sagas::declare_saga_actions; use crate::app::{authn, authz, db}; @@ -109,12 +109,12 @@ use omicron_common::{ api::external, progenitor_operation_retry::ProgenitorOperationRetry, }; use omicron_uuid_kinds::{GenericUuid, PropolisUuid, SledUuid, VolumeUuid}; -use rand::{rngs::StdRng, RngCore, SeedableRng}; +use rand::{RngCore, SeedableRng, rngs::StdRng}; use serde::Deserialize; use serde::Serialize; -use sled_agent_client::types::VmmIssueDiskSnapshotRequestBody; use sled_agent_client::CrucibleOpts; use sled_agent_client::VolumeConstructionRequest; +use sled_agent_client::types::VmmIssueDiskSnapshotRequestBody; use slog::info; use slog_error_chain::InlineErrorChain; use std::collections::BTreeMap; @@ -1168,7 +1168,7 @@ async fn ssc_call_pantry_attach_for_disk_undo( params.disk_id, pantry_address, InlineErrorChain::new(&err) - )) + )); } } } else { @@ -1771,8 +1771,8 @@ mod test { }; use dropshot::test_util::ClientTestContext; use nexus_db_queries::context::OpContext; - use nexus_db_queries::db::datastore::InstanceAndActiveVmm; use nexus_db_queries::db::DataStore; + use nexus_db_queries::db::datastore::InstanceAndActiveVmm; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_disk; use nexus_test_utils::resource_helpers::create_project; @@ -2331,15 +2331,17 @@ mod test { .await .expect("Failed to look up created disk"); - assert!(nexus - .datastore() - .disk_update_runtime( - &opctx, - &authz_disk, - &db_disk.runtime().detach(), - ) - .await - .expect("failed to detach disk")); + assert!( + nexus + .datastore() + .disk_update_runtime( + &opctx, + &authz_disk, + &db_disk.runtime().detach(), + ) + .await + .expect("failed to detach disk") + ); // Stop and destroy the test instance to satisfy the // clean-slate check. @@ -2465,15 +2467,17 @@ mod test { .await .expect("Failed to look up created disk"); - assert!(nexus - .datastore() - .disk_update_runtime( - &opctx, - &authz_disk, - &db_disk.runtime().detach(), - ) - .await - .expect("failed to detach disk")); + assert!( + nexus + .datastore() + .disk_update_runtime( + &opctx, + &authz_disk, + &db_disk.runtime().detach(), + ) + .await + .expect("failed to detach disk") + ); // Rerun the saga let params = new_test_params( @@ -2550,15 +2554,17 @@ mod test { .await .expect("Failed to look up created disk"); - assert!(nexus - .datastore() - .disk_update_runtime( - &opctx, - &authz_disk, - &db_disk.runtime().detach(), - ) - .await - .expect("failed to detach disk")); + assert!( + nexus + .datastore() + .disk_update_runtime( + &opctx, + &authz_disk, + &db_disk.runtime().detach(), + ) + .await + .expect("failed to detach disk") + ); // Actually run the saga. This should fail. let output = runnable_saga diff --git a/nexus/src/app/sagas/test_helpers.rs b/nexus/src/app/sagas/test_helpers.rs index 19d11bde725..4cc46f80c26 100644 --- a/nexus/src/app/sagas/test_helpers.rs +++ b/nexus/src/app/sagas/test_helpers.rs @@ -5,8 +5,8 @@ //! Helper functions for writing saga undo tests and working with instances in //! saga tests. -use super::{instance_common::VmmAndSledIds, instance_start, NexusSaga}; -use crate::{app::saga::create_saga_dag, Nexus}; +use super::{NexusSaga, instance_common::VmmAndSledIds, instance_start}; +use crate::{Nexus, app::saga::create_saga_dag}; use async_bb8_diesel::{AsyncRunQueryDsl, AsyncSimpleConnection}; use diesel::{ BoolExpressionMethods, ExpressionMethods, QueryDsl, SelectableHelper, @@ -17,9 +17,9 @@ use nexus_db_queries::{ authz, context::OpContext, db::{ + DataStore, datastore::{InstanceAndActiveVmm, InstanceGestalt}, lookup::LookupPath, - DataStore, }, }; use nexus_types::identity::Resource; @@ -28,7 +28,7 @@ use omicron_common::api::external::NameOrId; use omicron_test_utils::dev::poll; use omicron_uuid_kinds::{GenericUuid, InstanceUuid, PropolisUuid, SledUuid}; use sled_agent_client::TestInterfaces as _; -use slog::{info, warn, Logger}; +use slog::{Logger, info, warn}; use std::{num::NonZeroU32, sync::Arc, time::Duration}; use steno::SagaDag; diff --git a/nexus/src/app/sagas/vpc_create.rs b/nexus/src/app/sagas/vpc_create.rs index a223cdec867..6d9acf35e7e 100644 --- a/nexus/src/app/sagas/vpc_create.rs +++ b/nexus/src/app/sagas/vpc_create.rs @@ -2,10 +2,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use super::ACTION_GENERATE_ID; use super::ActionRegistry; use super::NexusActionContext; use super::NexusSaga; -use super::ACTION_GENERATE_ID; use crate::app::sagas::declare_saga_actions; use crate::external_api::params; use nexus_db_model::InternetGatewayIpPool; diff --git a/nexus/src/app/sagas/vpc_subnet_create.rs b/nexus/src/app/sagas/vpc_subnet_create.rs index 360c882aada..8a2b6b8b957 100644 --- a/nexus/src/app/sagas/vpc_subnet_create.rs +++ b/nexus/src/app/sagas/vpc_subnet_create.rs @@ -2,10 +2,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use super::ACTION_GENERATE_ID; use super::ActionRegistry; use super::NexusActionContext; use super::NexusSaga; -use super::ACTION_GENERATE_ID; use crate::app::sagas::declare_saga_actions; use crate::external_api::params; use nexus_db_queries::db::lookup::LookupPath; diff --git a/nexus/src/app/session.rs b/nexus/src/app/session.rs index 90b24a52ad9..d043fc6474d 100644 --- a/nexus/src/app/session.rs +++ b/nexus/src/app/session.rs @@ -17,7 +17,7 @@ use omicron_common::api::external::Error; use omicron_common::api::external::LookupResult; use omicron_common::api::external::LookupType; use omicron_common::api::external::UpdateResult; -use rand::{rngs::StdRng, RngCore, SeedableRng}; +use rand::{RngCore, SeedableRng, rngs::StdRng}; use uuid::Uuid; fn generate_session_token() -> String { diff --git a/nexus/src/app/silo.rs b/nexus/src/app/silo.rs index b8e3de8866c..39d70a15eaf 100644 --- a/nexus/src/app/silo.rs +++ b/nexus/src/app/silo.rs @@ -19,10 +19,10 @@ use nexus_db_queries::{authn, authz}; use nexus_types::deployment::execution::blueprint_nexus_external_ips; use nexus_types::internal_api::params::DnsRecord; use nexus_types::silo::silo_dns_name; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::{CreateResult, LookupType}; use omicron_common::api::external::{DataPageParams, ResourceType}; use omicron_common::api::external::{DeleteResult, NameOrId}; @@ -666,7 +666,6 @@ impl super::Nexus { saml_identity_provider: NameOrId::Id(id), silo: None, } => { - let saml_provider = LookupPath::new(opctx, &self.db_datastore) .saml_identity_provider_id(id); Ok(saml_provider) @@ -683,8 +682,12 @@ impl super::Nexus { params::SamlIdentityProviderSelector { saml_identity_provider: NameOrId::Id(_), silo: _, - } => Err(Error::invalid_request("when providing provider as an ID, silo should not be specified")), - _ => Err(Error::invalid_request("provider should either be a UUID or silo should be specified")) + } => Err(Error::invalid_request( + "when providing provider as an ID, silo should not be specified", + )), + _ => Err(Error::invalid_request( + "provider should either be a UUID or silo should be specified", + )), } } diff --git a/nexus/src/app/sled.rs b/nexus/src/app/sled.rs index ffa507ffb8e..66b493c1210 100644 --- a/nexus/src/app/sled.rs +++ b/nexus/src/app/sled.rs @@ -269,7 +269,7 @@ impl super::Nexus { || existing_disk.model != request.model { return Err(Error::internal_error( - "Invalid Physical Disk update (was: {existing_disk:?}, asking for {request:?})" + "Invalid Physical Disk update (was: {existing_disk:?}, asking for {request:?})", )); } return Ok(()); diff --git a/nexus/src/app/snapshot.rs b/nexus/src/app/snapshot.rs index 57b8edd1f03..c045e4997f8 100644 --- a/nexus/src/app/snapshot.rs +++ b/nexus/src/app/snapshot.rs @@ -8,13 +8,13 @@ use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; use nexus_types::external_api::params; use nexus_types::external_api::params::DiskSelector; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; +use omicron_common::api::external::http_pagination::PaginatedBy; use super::sagas; @@ -44,16 +44,15 @@ impl super::Nexus { .snapshot_name_owned(name.into()); Ok(snapshot) } - params::SnapshotSelector { - snapshot: NameOrId::Id(_), - .. - } => Err(Error::invalid_request( - "when providing snapshot as an ID, project should not \ - be specified" - )), + params::SnapshotSelector { snapshot: NameOrId::Id(_), .. } => { + Err(Error::invalid_request( + "when providing snapshot as an ID, project should not \ + be specified", + )) + } _ => Err(Error::invalid_request( - "snapshot should either be an ID or project should be specified" - )) + "snapshot should either be an ID or project should be specified", + )), } } diff --git a/nexus/src/app/ssh_key.rs b/nexus/src/app/ssh_key.rs index 11a16c286ad..15264a5dbda 100644 --- a/nexus/src/app/ssh_key.rs +++ b/nexus/src/app/ssh_key.rs @@ -5,12 +5,12 @@ use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::Name; use nexus_db_queries::db::model::SshKey; use nexus_db_queries::db::{self, lookup}; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; +use omicron_common::api::external::http_pagination::PaginatedBy; use ref_cast::RefCast; use uuid::Uuid; diff --git a/nexus/src/app/switch_port.rs b/nexus/src/app/switch_port.rs index b616531f533..129397f8269 100644 --- a/nexus/src/app/switch_port.rs +++ b/nexus/src/app/switch_port.rs @@ -11,11 +11,11 @@ use http::StatusCode; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::UpdatePrecondition; use nexus_db_queries::db::model::{SwitchPort, SwitchPortSettings}; -use nexus_db_queries::db::DataStore; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::SwitchLocation; +use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::{ self, CreateResult, DataPageParams, DeleteResult, Error, ListResultVec, LookupResult, Name, NameOrId, UpdateResult, @@ -65,7 +65,10 @@ impl super::Nexus { if key.len() > 80 { return Err(Error::invalid_value( "md5_auth_key", - format!("md5 auth key for {} is longer than 80 characters", p.addr) + format!( + "md5 auth key for {} is longer than 80 characters", + p.addr + ), )); } for c in key.chars() { diff --git a/nexus/src/app/update/host_phase1_updater.rs b/nexus/src/app/update/host_phase1_updater.rs index fb013d0ffe7..6075b8ac8d0 100644 --- a/nexus/src/app/update/host_phase1_updater.rs +++ b/nexus/src/app/update/host_phase1_updater.rs @@ -4,14 +4,14 @@ //! Module containing types for updating host OS phase1 images via MGS. -use super::common_sp_update::deliver_update; -use super::common_sp_update::SpComponentUpdater; use super::MgsClients; use super::SpComponentUpdateError; use super::UpdateProgress; +use super::common_sp_update::SpComponentUpdater; +use super::common_sp_update::deliver_update; +use gateway_client::SpComponent; use gateway_client::types::SpComponentFirmwareSlot; use gateway_client::types::SpType; -use gateway_client::SpComponent; use slog::Logger; use tokio::sync::watch; use uuid::Uuid; diff --git a/nexus/src/app/update/rot_updater.rs b/nexus/src/app/update/rot_updater.rs index 12126a7de92..484eac526d2 100644 --- a/nexus/src/app/update/rot_updater.rs +++ b/nexus/src/app/update/rot_updater.rs @@ -4,15 +4,15 @@ //! Module containing types for updating RoTs via MGS. -use super::common_sp_update::deliver_update; -use super::common_sp_update::SpComponentUpdater; use super::MgsClients; use super::SpComponentUpdateError; use super::UpdateProgress; +use super::common_sp_update::SpComponentUpdater; +use super::common_sp_update::deliver_update; +use gateway_client::SpComponent; use gateway_client::types::RotSlot; use gateway_client::types::SpComponentFirmwareSlot; use gateway_client::types::SpType; -use gateway_client::SpComponent; use slog::Logger; use tokio::sync::watch; use uuid::Uuid; diff --git a/nexus/src/app/update/sp_updater.rs b/nexus/src/app/update/sp_updater.rs index 2a6ddc6de68..1e5bd3c2b44 100644 --- a/nexus/src/app/update/sp_updater.rs +++ b/nexus/src/app/update/sp_updater.rs @@ -4,13 +4,13 @@ //! Module containing types for updating SPs via MGS. -use super::common_sp_update::deliver_update; -use super::common_sp_update::SpComponentUpdater; use super::MgsClients; use super::SpComponentUpdateError; use super::UpdateProgress; -use gateway_client::types::SpType; +use super::common_sp_update::SpComponentUpdater; +use super::common_sp_update::deliver_update; use gateway_client::SpComponent; +use gateway_client::types::SpType; use slog::Logger; use tokio::sync::watch; use uuid::Uuid; diff --git a/nexus/src/app/utilization.rs b/nexus/src/app/utilization.rs index bd5f5d002ab..395e83cfd6d 100644 --- a/nexus/src/app/utilization.rs +++ b/nexus/src/app/utilization.rs @@ -11,9 +11,9 @@ use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; use nexus_db_queries::db::lookup; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::Error; use omicron_common::api::external::ListResultVec; +use omicron_common::api::external::http_pagination::PaginatedBy; impl super::Nexus { pub async fn silo_utilization_view( diff --git a/nexus/src/app/vpc.rs b/nexus/src/app/vpc.rs index 56a7777f0ed..9396c1843fa 100644 --- a/nexus/src/app/vpc.rs +++ b/nexus/src/app/vpc.rs @@ -15,7 +15,6 @@ use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::Name; use nexus_defaults as defaults; use omicron_common::api::external; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -26,6 +25,7 @@ use omicron_common::api::external::LookupType; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; use omicron_common::api::external::VpcFirewallRuleUpdateParams; +use omicron_common::api::external::http_pagination::PaginatedBy; use std::sync::Arc; use uuid::Uuid; @@ -51,12 +51,11 @@ impl super::Nexus { .vpc_name_owned(name.into()); Ok(vpc) } - params::VpcSelector { - vpc: NameOrId::Id(_), - project: Some(_), - } => Err(Error::invalid_request( - "when providing vpc as an ID, project should not be specified", - )), + params::VpcSelector { vpc: NameOrId::Id(_), project: Some(_) } => { + Err(Error::invalid_request( + "when providing vpc as an ID, project should not be specified", + )) + } _ => Err(Error::invalid_request( "vpc should either be an ID or project should be specified", )), @@ -213,7 +212,7 @@ impl super::Nexus { _ => { return Err(external::Error::internal_error( "unexpected target in default firewall rule", - )) + )); } } if let Some(ref mut filter_hosts) = rule.filter_hosts { @@ -224,9 +223,11 @@ impl super::Nexus { ) if name.as_str() == "default" => { *name = vpc_name.clone().into() } - _ => return Err(external::Error::internal_error( - "unexpected host filter in default firewall rule" - )), + _ => { + return Err(external::Error::internal_error( + "unexpected host filter in default firewall rule", + )); + } } } } diff --git a/nexus/src/app/vpc_router.rs b/nexus/src/app/vpc_router.rs index 53961341cad..4d345904eb7 100644 --- a/nexus/src/app/vpc_router.rs +++ b/nexus/src/app/vpc_router.rs @@ -13,7 +13,6 @@ use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::RouterRoute; use nexus_db_queries::db::model::VpcRouter; use nexus_db_queries::db::model::VpcRouterKind; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -24,6 +23,7 @@ use omicron_common::api::external::RouteDestination; use omicron_common::api::external::RouteTarget; use omicron_common::api::external::RouterRouteKind; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; use oxnet::IpNet; use std::net::IpAddr; use uuid::Uuid; @@ -39,7 +39,7 @@ impl super::Nexus { params::RouterSelector { router: NameOrId::Id(id), vpc: None, - project: None + project: None, } => { let router = LookupPath::new(opctx, &self.db_datastore) .vpc_router_id(id); @@ -48,19 +48,18 @@ impl super::Nexus { params::RouterSelector { router: NameOrId::Name(name), vpc: Some(vpc), - project + project, } => { let router = self .vpc_lookup(opctx, params::VpcSelector { project, vpc })? .vpc_router_name_owned(name.into()); Ok(router) } - params::RouterSelector { - router: NameOrId::Id(_), - .. - } => Err(Error::invalid_request( - "when providing router as an ID vpc and project should not be specified", - )), + params::RouterSelector { router: NameOrId::Id(_), .. } => { + Err(Error::invalid_request( + "when providing router as an ID vpc and project should not be specified", + )) + } _ => Err(Error::invalid_request( "router should either be an ID or vpc should be specified", )), @@ -215,12 +214,11 @@ impl super::Nexus { .router_route_name_owned(name.into()); Ok(route) } - params::RouteSelector { - route: NameOrId::Id(_), - .. - } => Err(Error::invalid_request( - "when providing route as an ID router, subnet, vpc, and project should not be specified", - )), + params::RouteSelector { route: NameOrId::Id(_), .. } => { + Err(Error::invalid_request( + "when providing route as an ID router, subnet, vpc, and project should not be specified", + )) + } _ => Err(Error::invalid_request( "route should either be an ID or router should be specified", )), @@ -291,15 +289,17 @@ impl super::Nexus { match db_route.kind.0 { // Default routes allow a constrained form of modification: // only the target may change. - RouterRouteKind::Default if - params.identity.name.is_some() + RouterRouteKind::Default + if params.identity.name.is_some() || params.identity.description.is_some() - || params.destination != db_route.destination.0 => { + || params.destination != db_route.destination.0 => + { return Err(Error::invalid_request( "the destination and metadata of a Default route cannot be changed", - ))}, + )); + } - RouterRouteKind::Custom | RouterRouteKind::Default => {}, + RouterRouteKind::Custom | RouterRouteKind::Default => {} _ => { return Err(Error::invalid_request(format!( @@ -386,26 +386,43 @@ fn validate_user_route_targets( route_type: RouterRouteKind, ) -> Result<(), Error> { match (dest, target) { - (RouteDestination::Ip(IpAddr::V4(_)), RouteTarget::Ip(IpAddr::V4(_))) - | (RouteDestination::Ip(IpAddr::V6(_)), RouteTarget::Ip(IpAddr::V6(_))) - | (RouteDestination::IpNet(IpNet::V4(_)), RouteTarget::Ip(IpAddr::V4(_))) - | (RouteDestination::IpNet(IpNet::V6(_)), RouteTarget::Ip(IpAddr::V6(_))) => {}, + ( + RouteDestination::Ip(IpAddr::V4(_)), + RouteTarget::Ip(IpAddr::V4(_)), + ) + | ( + RouteDestination::Ip(IpAddr::V6(_)), + RouteTarget::Ip(IpAddr::V6(_)), + ) + | ( + RouteDestination::IpNet(IpNet::V4(_)), + RouteTarget::Ip(IpAddr::V4(_)), + ) + | ( + RouteDestination::IpNet(IpNet::V6(_)), + RouteTarget::Ip(IpAddr::V6(_)), + ) => {} (RouteDestination::Ip(_), RouteTarget::Ip(_)) - | (RouteDestination::IpNet(_), RouteTarget::Ip(_)) - => return Err(Error::invalid_request( - "cannot mix explicit IPv4 and IPv6 addresses between destination and target" - )), + | (RouteDestination::IpNet(_), RouteTarget::Ip(_)) => { + return Err(Error::invalid_request( + "cannot mix explicit IPv4 and IPv6 addresses between destination and target", + )); + } - (RouteDestination::Vpc(_), _) | (_, RouteTarget::Vpc(_)) => return Err(Error::invalid_request( - format!("users cannot specify VPCs as a destination or target in {route_type} routes") - )), + (RouteDestination::Vpc(_), _) | (_, RouteTarget::Vpc(_)) => { + return Err(Error::invalid_request(format!( + "users cannot specify VPCs as a destination or target in {route_type} routes" + ))); + } - (_, RouteTarget::Subnet(_)) => return Err(Error::invalid_request( - format!("subnets cannot be used as a target in {route_type} routers") - )), + (_, RouteTarget::Subnet(_)) => { + return Err(Error::invalid_request(format!( + "subnets cannot be used as a target in {route_type} routers" + ))); + } - _ => {}, + _ => {} }; Ok(()) diff --git a/nexus/src/app/vpc_subnet.rs b/nexus/src/app/vpc_subnet.rs index 224ac25aa20..2ae5ee0cc8a 100644 --- a/nexus/src/app/vpc_subnet.rs +++ b/nexus/src/app/vpc_subnet.rs @@ -15,7 +15,6 @@ use nexus_db_queries::db::lookup; use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::db::model::VpcSubnet; use omicron_common::api::external; -use omicron_common::api::external::http_pagination::PaginatedBy; use omicron_common::api::external::CreateResult; use omicron_common::api::external::DeleteResult; use omicron_common::api::external::Error; @@ -25,6 +24,7 @@ use omicron_common::api::external::ListResultVec; use omicron_common::api::external::LookupResult; use omicron_common::api::external::NameOrId; use omicron_common::api::external::UpdateResult; +use omicron_common::api::external::http_pagination::PaginatedBy; impl super::Nexus { pub fn vpc_subnet_lookup<'a>( diff --git a/nexus/src/bin/nexus.rs b/nexus/src/bin/nexus.rs index 01e4bfc3af2..b0d1a5eb713 100644 --- a/nexus/src/bin/nexus.rs +++ b/nexus/src/bin/nexus.rs @@ -14,8 +14,8 @@ use anyhow::anyhow; use camino::Utf8PathBuf; use clap::Parser; use nexus_config::NexusConfig; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use omicron_nexus::run_server; #[derive(Debug, Parser)] diff --git a/nexus/src/cidata.rs b/nexus/src/cidata.rs index 08e4926af11..b7329226f66 100644 --- a/nexus/src/cidata.rs +++ b/nexus/src/cidata.rs @@ -8,7 +8,7 @@ use uuid::Uuid; pub trait InstanceCiData { fn generate_cidata(&self, public_keys: &[String]) - -> Result, Error>; + -> Result, Error>; } impl InstanceCiData for Instance { @@ -108,11 +108,13 @@ mod tests { // somewhat arbitrarily-chosen prime numbers near 1 KiB and 256 bytes for md_size in (0..upper).step_by(1019) { for ud_size in (0..upper).step_by(269) { - assert!(super::build_vfat( - &vec![0x5a; md_size], - &vec![0xa5; ud_size] - ) - .is_ok()); + assert!( + super::build_vfat( + &vec![0x5a; md_size], + &vec![0xa5; ud_size] + ) + .is_ok() + ); } } } diff --git a/nexus/src/context.rs b/nexus/src/context.rs index ea3a0716055..36afa1d8129 100644 --- a/nexus/src/context.rs +++ b/nexus/src/context.rs @@ -5,20 +5,20 @@ use super::Nexus; use crate::saga_interface::SagaContext; use async_trait::async_trait; +use authn::external::HttpAuthnScheme; use authn::external::session_cookie::HttpAuthnSessionCookie; use authn::external::spoof::HttpAuthnSpoof; use authn::external::token::HttpAuthnToken; -use authn::external::HttpAuthnScheme; use camino::Utf8PathBuf; use chrono::Duration; use nexus_config::NexusConfig; use nexus_config::SchemeName; -use nexus_db_queries::authn::external::session_cookie::SessionStore; use nexus_db_queries::authn::ConsoleSessionWithSiloId; +use nexus_db_queries::authn::external::session_cookie::SessionStore; use nexus_db_queries::context::{OpContext, OpKind}; use nexus_db_queries::db::lookup::LookupPath; use nexus_db_queries::{authn, authz, db}; -use omicron_common::address::{Ipv6Subnet, AZ_PREFIX}; +use omicron_common::address::{AZ_PREFIX, Ipv6Subnet}; use omicron_uuid_kinds::GenericUuid; use oximeter::types::ProducerRegistry; use oximeter_instruments::http::{HttpService, LatencyTracker}; @@ -176,18 +176,18 @@ impl ServerContext { Some(config.pkg.console.static_dir.to_owned()) } else { match env::current_dir() { - Ok(root) => { - match Utf8PathBuf::try_from(root) { - Ok(root) => { - Some(root.join(&config.pkg.console.static_dir)) - } - Err(err) => { - error!(log, "Failed to convert current directory to UTF-8, \ - setting assets dir to None: {}", err); - None - } + Ok(root) => match Utf8PathBuf::try_from(root) { + Ok(root) => Some(root.join(&config.pkg.console.static_dir)), + Err(err) => { + error!( + log, + "Failed to convert current directory to UTF-8, \ + setting assets dir to None: {}", + err + ); + None } - } + }, Err(error) => { error!( log, @@ -203,7 +203,10 @@ impl ServerContext { // We don't want to fail outright yet, but we do want to try to make // problems slightly easier to debug. if static_dir.is_none() { - error!(log, "No assets directory configured. All console page and asset requests will 404."); + error!( + log, + "No assets directory configured. All console page and asset requests will 404." + ); } // TODO: check that asset directory exists, check for particular assets diff --git a/nexus/src/external_api/console_api.rs b/nexus/src/external_api/console_api.rs index 535ba0f95f2..06b312dfbb6 100644 --- a/nexus/src/external_api/console_api.rs +++ b/nexus/src/external_api/console_api.rs @@ -472,7 +472,7 @@ fn find_file( #[cfg(test)] mod test { - use super::{accept_gz, find_file, RelativeUri}; + use super::{RelativeUri, accept_gz, find_file}; use camino::{Utf8Path, Utf8PathBuf}; use http::StatusCode; @@ -534,12 +534,13 @@ mod test { let path_str = "tests/static/assets/a_symlink"; // the file in question does exist and is a symlink - assert!(root - .join(path_str) - .symlink_metadata() - .unwrap() - .file_type() - .is_symlink()); + assert!( + root.join(path_str) + .symlink_metadata() + .unwrap() + .file_type() + .is_symlink() + ); // so we 404 let error = find_file(Utf8Path::new(path_str), &root).unwrap_err(); diff --git a/nexus/src/external_api/http_entrypoints.rs b/nexus/src/external_api/http_entrypoints.rs index 887a6d35a65..94599e49755 100644 --- a/nexus/src/external_api/http_entrypoints.rs +++ b/nexus/src/external_api/http_entrypoints.rs @@ -13,9 +13,9 @@ use super::{ Utilization, Vpc, VpcRouter, VpcSubnet, }, }; +use crate::app::Unimpl; use crate::app::external_endpoints::authority_for_request; use crate::app::support_bundles::SupportBundleQueryType; -use crate::app::Unimpl; use crate::context::ApiContext; use crate::external_api::shared; use dropshot::Body; @@ -32,12 +32,12 @@ use dropshot::RequestContext; use dropshot::ResultsPage; use dropshot::TypedBody; use dropshot::WhichPage; -use dropshot::{http_response_found, http_response_see_other}; use dropshot::{ApiDescription, StreamingBody}; use dropshot::{HttpResponseAccepted, HttpResponseFound, HttpResponseSeeOther}; use dropshot::{HttpResponseCreated, HttpResponseHeaders}; use dropshot::{WebsocketChannelResult, WebsocketConnection}; -use http::{header, Response, StatusCode}; +use dropshot::{http_response_found, http_response_see_other}; +use http::{Response, StatusCode, header}; use ipnetwork::IpNetwork; use nexus_db_queries::authn::external::session_cookie::{self, SessionStore}; use nexus_db_queries::authz; @@ -54,19 +54,6 @@ use nexus_types::{ shared::{BfdStatus, ProbeInfo}, }, }; -use omicron_common::api::external::http_pagination::data_page_params_for; -use omicron_common::api::external::http_pagination::marker_for_id; -use omicron_common::api::external::http_pagination::marker_for_name; -use omicron_common::api::external::http_pagination::marker_for_name_or_id; -use omicron_common::api::external::http_pagination::name_or_id_pagination; -use omicron_common::api::external::http_pagination::PaginatedBy; -use omicron_common::api::external::http_pagination::PaginatedById; -use omicron_common::api::external::http_pagination::PaginatedByName; -use omicron_common::api::external::http_pagination::PaginatedByNameOrId; -use omicron_common::api::external::http_pagination::ScanById; -use omicron_common::api::external::http_pagination::ScanByName; -use omicron_common::api::external::http_pagination::ScanByNameOrId; -use omicron_common::api::external::http_pagination::ScanParams; use omicron_common::api::external::AddressLot; use omicron_common::api::external::AddressLotBlock; use omicron_common::api::external::AddressLotCreateResponse; @@ -99,14 +86,27 @@ use omicron_common::api::external::TufRepoGetResponse; use omicron_common::api::external::TufRepoInsertResponse; use omicron_common::api::external::VpcFirewallRuleUpdateParams; use omicron_common::api::external::VpcFirewallRules; +use omicron_common::api::external::http_pagination::PaginatedBy; +use omicron_common::api::external::http_pagination::PaginatedById; +use omicron_common::api::external::http_pagination::PaginatedByName; +use omicron_common::api::external::http_pagination::PaginatedByNameOrId; +use omicron_common::api::external::http_pagination::ScanById; +use omicron_common::api::external::http_pagination::ScanByName; +use omicron_common::api::external::http_pagination::ScanByNameOrId; +use omicron_common::api::external::http_pagination::ScanParams; +use omicron_common::api::external::http_pagination::data_page_params_for; +use omicron_common::api::external::http_pagination::marker_for_id; +use omicron_common::api::external::http_pagination::marker_for_name; +use omicron_common::api::external::http_pagination::marker_for_name_or_id; +use omicron_common::api::external::http_pagination::name_or_id_pagination; use omicron_common::bail_unless; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::SupportBundleUuid; +use propolis_client::support::WebSocketStream; use propolis_client::support::tungstenite::protocol::frame::coding::CloseCode; use propolis_client::support::tungstenite::protocol::{ CloseFrame, Role as WebSocketRole, }; -use propolis_client::support::WebSocketStream; use range_requests::RequestContextEx; use ref_cast::RefCast; @@ -7204,7 +7204,7 @@ impl NexusExternalApi for NexusExternalApiImpl { "error": "invalid_request", "error_description": error, }), - ) + ); } }; diff --git a/nexus/src/internal_api/http_entrypoints.rs b/nexus/src/internal_api/http_entrypoints.rs index 49cadf3b8b7..5cabe56a984 100644 --- a/nexus/src/internal_api/http_entrypoints.rs +++ b/nexus/src/internal_api/http_entrypoints.rs @@ -33,16 +33,16 @@ use nexus_types::internal_api::params::InstanceMigrateRequest; use nexus_types::internal_api::params::SledAgentInfo; use nexus_types::internal_api::params::SwitchPutRequest; use nexus_types::internal_api::params::SwitchPutResponse; -use nexus_types::internal_api::views::to_list; use nexus_types::internal_api::views::BackgroundTask; use nexus_types::internal_api::views::DemoSaga; use nexus_types::internal_api::views::Ipv4NatEntryView; use nexus_types::internal_api::views::Saga; -use omicron_common::api::external::http_pagination::data_page_params_for; +use nexus_types::internal_api::views::to_list; +use omicron_common::api::external::Instance; use omicron_common::api::external::http_pagination::PaginatedById; use omicron_common::api::external::http_pagination::ScanById; use omicron_common::api::external::http_pagination::ScanParams; -use omicron_common::api::external::Instance; +use omicron_common::api::external::http_pagination::data_page_params_for; use omicron_common::api::internal::nexus::DiskRuntimeState; use omicron_common::api::internal::nexus::DownstairsClientStopRequest; use omicron_common::api::internal::nexus::DownstairsClientStopped; diff --git a/nexus/src/lib.rs b/nexus/src/lib.rs index 34bfad2dd1e..a2ee375726a 100644 --- a/nexus/src/lib.rs +++ b/nexus/src/lib.rs @@ -18,8 +18,8 @@ mod internal_api; mod populate; mod saga_interface; -pub use app::test_interfaces::TestInterfaces; pub use app::Nexus; +pub use app::test_interfaces::TestInterfaces; use context::ApiContext; use context::ServerContext; use dropshot::ConfigDropshot; @@ -27,14 +27,15 @@ use external_api::http_entrypoints::external_api; use internal_api::http_entrypoints::internal_api; use nexus_config::NexusConfig; use nexus_db_model::RendezvousDebugDataset; -use nexus_types::deployment::blueprint_zone_type; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintZoneDisposition; use nexus_types::deployment::BlueprintZoneType; +use nexus_types::deployment::blueprint_zone_type; use nexus_types::internal_api::params::{ PhysicalDiskPutRequest, ZpoolPutRequest, }; use nexus_types::inventory::Collection; +use omicron_common::FileKv; use omicron_common::address::IpRange; use omicron_common::api::external::Error; use omicron_common::api::internal::nexus::{ProducerEndpoint, ProducerKind}; @@ -42,7 +43,6 @@ use omicron_common::api::internal::shared::{ AllowedSourceIps, ExternalPortDiscovery, RackNetworkConfig, SwitchLocation, }; use omicron_common::disk::DatasetKind; -use omicron_common::FileKv; use omicron_uuid_kinds::BlueprintUuid; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::GenericUuid as _; diff --git a/nexus/src/populate.rs b/nexus/src/populate.rs index 0438a53353e..4976d75130a 100644 --- a/nexus/src/populate.rs +++ b/nexus/src/populate.rs @@ -42,8 +42,8 @@ //! you define a single data-insertion step. We have tests that ensure that //! each populator behaves as expected in the above ways. -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::DataStore; use omicron_common::api::external::Error; @@ -349,9 +349,9 @@ const ALL_POPULATORS: [&dyn Populator; 10] = [ #[cfg(test)] mod test { + use super::ALL_POPULATORS; use super::PopulateArgs; use super::Populator; - use super::ALL_POPULATORS; use anyhow::Context; use nexus_db_queries::authn; use nexus_db_queries::authz; @@ -455,9 +455,7 @@ mod test { Err(error) => panic!( "populator {:?}: expected ServiceUnavailable when the database \ was down, but got {:#} ({:?})", - p, - error, - error + p, error, error ), }; info!(&log, "populator {:?} done", p); diff --git a/nexus/test-utils-macros/src/lib.rs b/nexus/test-utils-macros/src/lib.rs index a5fd743acca..f45501478d0 100644 --- a/nexus/test-utils-macros/src/lib.rs +++ b/nexus/test-utils-macros/src/lib.rs @@ -4,7 +4,7 @@ use std::collections::HashSet as Set; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; -use syn::{parse_macro_input, ItemFn, Token}; +use syn::{ItemFn, Token, parse_macro_input}; #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) enum NexusTestArg { diff --git a/nexus/test-utils/src/background.rs b/nexus/test-utils/src/background.rs index b7a30b88bfe..c25d2c8ddc1 100644 --- a/nexus/test-utils/src/background.rs +++ b/nexus/test-utils/src/background.rs @@ -11,7 +11,7 @@ use nexus_client::types::CurrentStatus; use nexus_client::types::LastResult; use nexus_client::types::LastResultCompleted; use nexus_types::internal_api::background::*; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use std::time::Duration; /// Return the most recent activate time for a background task, returning None diff --git a/nexus/test-utils/src/http_testing.rs b/nexus/test-utils/src/http_testing.rs index b23de347495..f0602bc54d3 100644 --- a/nexus/test-utils/src/http_testing.rs +++ b/nexus/test-utils/src/http_testing.rs @@ -4,12 +4,12 @@ //! Facilities for testing HTTP servers +use anyhow::Context; use anyhow::anyhow; use anyhow::ensure; -use anyhow::Context; use camino::Utf8Path; -use dropshot::test_util::ClientTestContext; use dropshot::ResultsPage; +use dropshot::test_util::ClientTestContext; use futures::TryStreamExt; use headers::authorization::Credentials; use http_body_util::BodyExt; @@ -787,8 +787,8 @@ pub struct Collection { /// functions. pub mod dropshot_compat { use super::NexusRequest; - use dropshot::{test_util::ClientTestContext, ResultsPage}; - use serde::{de::DeserializeOwned, Serialize}; + use dropshot::{ResultsPage, test_util::ClientTestContext}; + use serde::{Serialize, de::DeserializeOwned}; /// See [`dropshot::test_util::object_get`]. pub async fn object_get( diff --git a/nexus/test-utils/src/lib.rs b/nexus/test-utils/src/lib.rs index 6d35b5e4943..c8abc4adc75 100644 --- a/nexus/test-utils/src/lib.rs +++ b/nexus/test-utils/src/lib.rs @@ -9,35 +9,33 @@ use anyhow::Context; use anyhow::Result; use camino::Utf8Path; use chrono::Utc; -use dropshot::test_util::ClientTestContext; -use dropshot::test_util::LogContext; use dropshot::ConfigLogging; use dropshot::ConfigLoggingLevel; use dropshot::HandlerTaskMode; -use futures::future::BoxFuture; +use dropshot::test_util::ClientTestContext; +use dropshot::test_util::LogContext; use futures::FutureExt; +use futures::future::BoxFuture; use gateway_test_utils::setup::GatewayTestContext; +use hickory_resolver::TokioAsyncResolver; use hickory_resolver::config::NameServerConfig; use hickory_resolver::config::Protocol; use hickory_resolver::config::ResolverConfig; use hickory_resolver::config::ResolverOpts; -use hickory_resolver::TokioAsyncResolver; use internal_dns_types::config::DnsConfigBuilder; -use internal_dns_types::names::ServiceName; use internal_dns_types::names::DNS_ZONE_EXTERNAL_TESTING; +use internal_dns_types::names::ServiceName; use nexus_config::Database; use nexus_config::DpdConfig; use nexus_config::InternalDns; use nexus_config::MgdConfig; -use nexus_config::NexusConfig; use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; +use nexus_config::NexusConfig; use nexus_db_queries::db::pub_test_utils::crdb; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; use nexus_sled_agent_shared::inventory::OmicronZonesConfig; use nexus_sled_agent_shared::recovery_silo::RecoverySiloConfig; use nexus_test_interface::NexusServer; -use nexus_types::deployment::blueprint_zone_type; -use nexus_types::deployment::id_map::IdMap; use nexus_types::deployment::Blueprint; use nexus_types::deployment::BlueprintDatasetConfig; use nexus_types::deployment::BlueprintDatasetDisposition; @@ -52,6 +50,8 @@ use nexus_types::deployment::BlueprintZonesConfig; use nexus_types::deployment::CockroachDbPreserveDowngrade; use nexus_types::deployment::OmicronZoneExternalFloatingAddr; use nexus_types::deployment::OmicronZoneExternalFloatingIp; +use nexus_types::deployment::blueprint_zone_type; +use nexus_types::deployment::id_map::IdMap; use nexus_types::external_api::views::SledState; use nexus_types::internal_api::params::DnsConfigParams; use omicron_common::address::DNS_OPTE_IPV4_SUBNET; @@ -72,7 +72,7 @@ use omicron_common::disk::CompressionAlgorithm; use omicron_common::zpool_name::ZpoolName; use omicron_sled_agent::sim; use omicron_test_utils::dev; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use omicron_uuid_kinds::BlueprintUuid; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::ExternalIpUuid; @@ -87,7 +87,7 @@ use oximeter_producer::Server as ProducerServer; use sled_agent_client::types::EarlyNetworkConfig; use sled_agent_client::types::EarlyNetworkConfigBody; use sled_agent_client::types::RackNetworkConfigV2; -use slog::{debug, error, o, Logger}; +use slog::{Logger, debug, error, o}; use std::collections::BTreeMap; use std::collections::HashMap; use std::fmt::Debug; diff --git a/nexus/test-utils/src/resource_helpers.rs b/nexus/test-utils/src/resource_helpers.rs index 9fe2b62a276..770c3a8ef52 100644 --- a/nexus/test-utils/src/resource_helpers.rs +++ b/nexus/test-utils/src/resource_helpers.rs @@ -2,15 +2,15 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::http_testing::RequestBuilder; use crate::ControlPlaneTestContext; +use crate::http_testing::RequestBuilder; use super::http_testing::AuthnMode; use super::http_testing::NexusRequest; use crucible_agent_client::types::State as RegionState; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; use dropshot::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; use nexus_db_queries::db::fixed_data::silo::DEFAULT_SILO; use nexus_test_interface::NexusServer; @@ -55,8 +55,8 @@ use omicron_common::disk::DiskIdentity; use omicron_common::disk::SharedDatasetConfig; use omicron_common::zpool_name::ZpoolName; use omicron_sled_agent::sim::SledAgent; -use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; +use omicron_test_utils::dev::poll::wait_for_condition; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::PhysicalDiskUuid; diff --git a/nexus/tests/integration_tests/address_lots.rs b/nexus/tests/integration_tests/address_lots.rs index 7860dd463c0..ad2f1e37331 100644 --- a/nexus/tests/integration_tests/address_lots.rs +++ b/nexus/tests/integration_tests/address_lots.rs @@ -4,8 +4,8 @@ //! Integration tests for operating on Address Lots -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; diff --git a/nexus/tests/integration_tests/allow_list.rs b/nexus/tests/integration_tests/allow_list.rs index 336a33273df..fb59ecb81fe 100644 --- a/nexus/tests/integration_tests/allow_list.rs +++ b/nexus/tests/integration_tests/allow_list.rs @@ -120,9 +120,9 @@ async fn test_allow_list(cptestctx: &ControlPlaneTestContext) { .expect("failed to make PUT request") .parsed_body() .expect("failed to parse error response"); - assert!(err - .message - .contains("would prevent access from the current client")); + assert!( + err.message.contains("would prevent access from the current client") + ); // But we _should_ be able to make this self-defeating request through the // techport proxy server. diff --git a/nexus/tests/integration_tests/authn_http.rs b/nexus/tests/integration_tests/authn_http.rs index cb98b458784..27094f792fc 100644 --- a/nexus/tests/integration_tests/authn_http.rs +++ b/nexus/tests/integration_tests/authn_http.rs @@ -11,21 +11,21 @@ use async_trait::async_trait; use bytes::Bytes; use chrono::{DateTime, Duration, Utc}; -use dropshot::endpoint; -use dropshot::test_util::LogContext; -use dropshot::test_util::TestContext; use dropshot::ApiDescription; use dropshot::HttpErrorResponseBody; use dropshot::RequestContext; +use dropshot::endpoint; +use dropshot::test_util::LogContext; +use dropshot::test_util::TestContext; use headers::authorization::Credentials; use http::header::HeaderValue; +use nexus_db_queries::authn::external::AuthenticatorContext; +use nexus_db_queries::authn::external::HttpAuthnScheme; +use nexus_db_queries::authn::external::SiloUserSilo; use nexus_db_queries::authn::external::session_cookie; use nexus_db_queries::authn::external::spoof; use nexus_db_queries::authn::external::spoof::HttpAuthnSpoof; use nexus_db_queries::authn::external::spoof::SPOOF_SCHEME_NAME; -use nexus_db_queries::authn::external::AuthenticatorContext; -use nexus_db_queries::authn::external::HttpAuthnScheme; -use nexus_db_queries::authn::external::SiloUserSilo; use nexus_types::silo::DEFAULT_SILO_ID; use std::collections::HashMap; use std::sync::Mutex; diff --git a/nexus/tests/integration_tests/basic.rs b/nexus/tests/integration_tests/basic.rs index cd23b7dd875..1345bbe07ee 100644 --- a/nexus/tests/integration_tests/basic.rs +++ b/nexus/tests/integration_tests/basic.rs @@ -8,8 +8,8 @@ //! TODO-coverage add test for racks, sleds use dropshot::HttpErrorResponseBody; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_types::external_api::params; use nexus_types::external_api::views::{self, Project}; use omicron_common::api::external::IdentityMetadataCreateParams; @@ -50,7 +50,6 @@ async fn test_basic_failures(cptestctx: &ControlPlaneTestContext) { expected_error: "Not Found", body: None, }, - // Error case: a possible value that does not exist inside a collection // that does exist) from an authorized user results in a 404. TestCase { diff --git a/nexus/tests/integration_tests/certificates.rs b/nexus/tests/integration_tests/certificates.rs index 5d83848afcb..c592a31aab3 100644 --- a/nexus/tests/integration_tests/certificates.rs +++ b/nexus/tests/integration_tests/certificates.rs @@ -5,11 +5,11 @@ //! Integration tests for operating on certificates use display_error_chain::ErrorChainExt; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; +use dropshot::test_util::ClientTestContext; use futures::TryStreamExt; -use http::method::Method; use http::StatusCode; +use http::method::Method; use internal_dns_types::names::DNS_ZONE_EXTERNAL_TESTING; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; @@ -23,8 +23,8 @@ use nexus_types::external_api::views::Certificate; use omicron_common::api::external::IdentityMetadataCreateParams; use omicron_common::api::internal::nexus::Certificate as InternalCertificate; use omicron_test_utils::certificates::CertificateChain; -use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; +use omicron_test_utils::dev::poll::wait_for_condition; use oxide_client::ClientSessionExt; use oxide_client::ClientSilosExt; use oxide_client::ClientSystemSilosExt; diff --git a/nexus/tests/integration_tests/commands.rs b/nexus/tests/integration_tests/commands.rs index 7ae42235569..413c45e6333 100644 --- a/nexus/tests/integration_tests/commands.rs +++ b/nexus/tests/integration_tests/commands.rs @@ -9,13 +9,13 @@ // TODO-coverage: test success cases of nexus use expectorate::assert_contents; +use omicron_test_utils::dev::test_cmds::EXIT_FAILURE; +use omicron_test_utils::dev::test_cmds::EXIT_USAGE; use omicron_test_utils::dev::test_cmds::assert_exit_code; use omicron_test_utils::dev::test_cmds::error_for_enoent; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; use omicron_test_utils::dev::test_cmds::temp_file_path; -use omicron_test_utils::dev::test_cmds::EXIT_FAILURE; -use omicron_test_utils::dev::test_cmds::EXIT_USAGE; use std::fs; use std::path::PathBuf; use subprocess::Exec; diff --git a/nexus/tests/integration_tests/console_api.rs b/nexus/tests/integration_tests/console_api.rs index f321a817fa2..8cb39c30022 100644 --- a/nexus/tests/integration_tests/console_api.rs +++ b/nexus/tests/integration_tests/console_api.rs @@ -4,10 +4,10 @@ use anyhow::Context; use camino::Utf8PathBuf; -use dropshot::test_util::ClientTestContext; use dropshot::ResultsPage; +use dropshot::test_util::ClientTestContext; use http::header::HeaderName; -use http::{header, method::Method, StatusCode}; +use http::{StatusCode, header, method::Method}; use std::env::current_dir; use crate::integration_tests::saml::SAML_RESPONSE_IDP_DESCRIPTOR; @@ -23,7 +23,7 @@ use nexus_test_utils::resource_helpers::{ create_silo, grant_iam, object_create, }; use nexus_test_utils::{ - load_test_config, test_setup_with_config, TEST_SUITE_PASSWORD, + TEST_SUITE_PASSWORD, load_test_config, test_setup_with_config, }; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params::{ @@ -33,7 +33,7 @@ use nexus_types::external_api::shared::{SiloIdentityMode, SiloRole}; use nexus_types::external_api::{shared, views}; use omicron_common::api::external::IdentityMetadataCreateParams; use omicron_sled_agent::sim; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; type ControlPlaneTestContext = nexus_test_utils::ControlPlaneTestContext; diff --git a/nexus/tests/integration_tests/crucible_replacements.rs b/nexus/tests/integration_tests/crucible_replacements.rs index 84c53d4a606..b9ed74041ce 100644 --- a/nexus/tests/integration_tests/crucible_replacements.rs +++ b/nexus/tests/integration_tests/crucible_replacements.rs @@ -15,9 +15,9 @@ use nexus_db_model::RegionReplacementState; use nexus_db_model::RegionSnapshotReplacementState; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::region_snapshot_replacement::*; use nexus_db_queries::db::lookup::LookupPath; -use nexus_db_queries::db::DataStore; use nexus_test_utils::background::*; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; @@ -35,11 +35,11 @@ use nexus_types::identity::Resource; use nexus_types::internal_api::background::*; use omicron_common::api::external; use omicron_common::api::external::IdentityMetadataCreateParams; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::VolumeUuid; -use slog::info; use slog::Logger; +use slog::info; use std::collections::HashSet; use std::net::SocketAddr; use std::sync::Arc; @@ -1649,7 +1649,10 @@ mod region_snapshot_replacement { InsertStepResult::Inserted { .. } => {} _ => { - assert!(false, "bad result from create_region_snapshot_replacement_step"); + assert!( + false, + "bad result from create_region_snapshot_replacement_step" + ); } } } @@ -1664,12 +1667,13 @@ mod region_snapshot_replacement { .await .unwrap(); - assert!(self - .datastore - .read_only_target_addr(®ion_snapshot_replace_request) - .await - .unwrap() - .is_none()); + assert!( + self.datastore + .read_only_target_addr(®ion_snapshot_replace_request) + .await + .unwrap() + .is_none() + ); } pub async fn remove_disk_from_snapshot_rop(&self) { @@ -2045,16 +2049,20 @@ async fn test_replacement_sanity(cptestctx: &ControlPlaneTestContext) { wait_for_all_replacements(&datastore, &internal_client).await; // Validate all regions are on non-expunged physical disks - assert!(datastore - .find_read_write_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); - assert!(datastore - .find_read_only_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .find_read_write_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); + assert!( + datastore + .find_read_only_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); } /// Tests that multiple replacements can occur until completion @@ -2164,16 +2172,20 @@ async fn test_region_replacement_triple_sanity( assert!(snapshot_allocated_regions.iter().all(|(_, r)| r.read_only())); // Validate all regions are on non-expunged physical disks - assert!(datastore - .find_read_write_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); - assert!(datastore - .find_read_only_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .find_read_write_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); + assert!( + datastore + .find_read_only_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); } /// Tests that multiple replacements can occur until completion, after expunging @@ -2323,16 +2335,20 @@ async fn test_region_replacement_triple_sanity_2( assert!(snapshot_allocated_regions.iter().all(|(_, r)| r.read_only())); // Validate all regions are on non-expunged physical disks - assert!(datastore - .find_read_write_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); - assert!(datastore - .find_read_only_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .find_read_write_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); + assert!( + datastore + .find_read_only_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); } /// Tests that replacement can occur until completion twice - meaning region @@ -2556,14 +2572,18 @@ async fn test_read_only_replacement_sanity( wait_for_all_replacements(&datastore, &internal_client).await; // Validate all regions are on non-expunged physical disks - assert!(datastore - .find_read_write_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); - assert!(datastore - .find_read_only_regions_on_expunged_physical_disks(&opctx) - .await - .unwrap() - .is_empty()); + assert!( + datastore + .find_read_write_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); + assert!( + datastore + .find_read_only_regions_on_expunged_physical_disks(&opctx) + .await + .unwrap() + .is_empty() + ); } diff --git a/nexus/tests/integration_tests/demo_saga.rs b/nexus/tests/integration_tests/demo_saga.rs index 888fa35965b..b09a2917442 100644 --- a/nexus/tests/integration_tests/demo_saga.rs +++ b/nexus/tests/integration_tests/demo_saga.rs @@ -9,8 +9,8 @@ use nexus_client::types::Saga; use nexus_client::types::SagaState; use nexus_test_interface::NexusServer; use nexus_test_utils_macros::nexus_test; -use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; +use omicron_test_utils::dev::poll::wait_for_condition; use std::time::Duration; type ControlPlaneTestContext = diff --git a/nexus/tests/integration_tests/device_auth.rs b/nexus/tests/integration_tests/device_auth.rs index 65730f6cc85..40ee0d40ba9 100644 --- a/nexus/tests/integration_tests/device_auth.rs +++ b/nexus/tests/integration_tests/device_auth.rs @@ -11,7 +11,7 @@ use nexus_types::external_api::{ }, }; -use http::{header, method::Method, StatusCode}; +use http::{StatusCode, header, method::Method}; use serde::Deserialize; use uuid::Uuid; @@ -81,14 +81,16 @@ async fn test_device_auth_flow(cptestctx: &ControlPlaneTestContext) { .expect("failed to redirect to login on auth failure"); // Authenticated requests get the console verification page. - assert!(NexusRequest::object_get(testctx, "/device/verify") - .console_asset() - .authn_as(AuthnMode::PrivilegedUser) - .execute() - .await - .expect("failed to get verification page") - .body - .starts_with(b"")); + assert!( + NexusRequest::object_get(testctx, "/device/verify") + .console_asset() + .authn_as(AuthnMode::PrivilegedUser) + .execute() + .await + .expect("failed to get verification page") + .body + .starts_with(b"") + ); let confirm_params = DeviceAuthVerify { user_code }; diff --git a/nexus/tests/integration_tests/disks.rs b/nexus/tests/integration_tests/disks.rs index a4cf2941b25..9dfa6ac835b 100644 --- a/nexus/tests/integration_tests/disks.rs +++ b/nexus/tests/integration_tests/disks.rs @@ -7,18 +7,19 @@ use super::instances::instance_wait_for_state; use super::metrics::{get_latest_silo_metric, query_for_metrics}; use chrono::Utc; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; -use http::method::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; +use http::method::Method; use nexus_config::RegionAllocationStrategy; use nexus_db_model::PhysicalDiskPolicy; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::datastore::REGION_REDUNDANCY_THRESHOLD; use nexus_db_queries::db::datastore::RegionAllocationFor; use nexus_db_queries::db::datastore::RegionAllocationParameters; -use nexus_db_queries::db::datastore::REGION_REDUNDANCY_THRESHOLD; use nexus_db_queries::db::fixed_data::FLEET_ID; use nexus_db_queries::db::lookup::LookupPath; +use nexus_test_utils::SLED_AGENT_UUID; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::Collection; use nexus_test_utils::http_testing::NexusRequest; @@ -31,7 +32,6 @@ use nexus_test_utils::resource_helpers::create_instance_with; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::objects_list_page_authz; use nexus_test_utils::wait_for_producer; -use nexus_test_utils::SLED_AGENT_UUID; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use nexus_types::silo::DEFAULT_SILO_ID; @@ -43,9 +43,9 @@ use omicron_common::api::external::InstanceState; use omicron_common::api::external::Name; use omicron_common::api::external::NameOrId; use omicron_common::api::external::{ByteCount, SimpleIdentityOrName as _}; -use omicron_nexus::app::{MAX_DISK_SIZE_BYTES, MIN_DISK_SIZE_BYTES}; use omicron_nexus::Nexus; use omicron_nexus::TestInterfaces as _; +use omicron_nexus::app::{MAX_DISK_SIZE_BYTES, MIN_DISK_SIZE_BYTES}; use omicron_uuid_kinds::VolumeUuid; use omicron_uuid_kinds::{GenericUuid, InstanceUuid}; use oximeter::types::Datum; diff --git a/nexus/tests/integration_tests/endpoints.rs b/nexus/tests/integration_tests/endpoints.rs index 11d8e9f14eb..6ef5d895316 100644 --- a/nexus/tests/integration_tests/endpoints.rs +++ b/nexus/tests/integration_tests/endpoints.rs @@ -139,13 +139,14 @@ pub static DEMO_SILO_USER_ID_DELETE_URL: LazyLock = DEFAULT_SILO.identity().name, ) }); -pub static DEMO_SILO_USER_ID_SET_PASSWORD_URL: LazyLock = - LazyLock::new(|| { +pub static DEMO_SILO_USER_ID_SET_PASSWORD_URL: LazyLock = LazyLock::new( + || { format!( - "/v1/system/identity-providers/local/users/{{id}}/set-password?silo={}", - DEFAULT_SILO.identity().name, - ) - }); + "/v1/system/identity-providers/local/users/{{id}}/set-password?silo={}", + DEFAULT_SILO.identity().name, + ) + }, +); // Project used for testing pub static DEMO_PROJECT_NAME: LazyLock = @@ -600,10 +601,10 @@ pub const DEMO_SWITCH_PORT_URL: &'static str = pub static DEMO_SWITCH_PORT_SETTINGS_APPLY_URL: LazyLock = LazyLock::new(|| { format!( - "/v1/system/hardware/switch-port/qsfp7/settings?rack_id={}&switch_location={}", - uuid::Uuid::new_v4(), - "switch0", - ) + "/v1/system/hardware/switch-port/qsfp7/settings?rack_id={}&switch_location={}", + uuid::Uuid::new_v4(), + "switch0", + ) }); pub static DEMO_SWITCH_PORT_SETTINGS: LazyLock< params::SwitchPortApplySettings, diff --git a/nexus/tests/integration_tests/external_ips.rs b/nexus/tests/integration_tests/external_ips.rs index 15fcadb9373..8624f2a6dc9 100644 --- a/nexus/tests/integration_tests/external_ips.rs +++ b/nexus/tests/integration_tests/external_ips.rs @@ -10,8 +10,8 @@ use std::net::Ipv4Addr; use crate::integration_tests::instances::fetch_instance_external_ips; use crate::integration_tests::instances::instance_simulate; use crate::integration_tests::instances::instance_wait_for_state; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; +use dropshot::test_util::ClientTestContext; use http::Method; use http::StatusCode; use nexus_db_queries::db::fixed_data::silo::DEFAULT_SILO; @@ -73,7 +73,9 @@ pub fn instance_ephemeral_ip_url( instance_name: &str, project_name: &str, ) -> String { - format!("/v1/instances/{instance_name}/external-ips/ephemeral?project={project_name}") + format!( + "/v1/instances/{instance_name}/external-ips/ephemeral?project={project_name}" + ) } pub fn attach_floating_ip_url( @@ -815,10 +817,12 @@ async fn test_external_ip_live_attach_detach( assert_eq!(eip_list.len(), 2); assert!(eip_list.contains(&eph_resp)); - assert!(eip_list - .iter() - .any(|v| matches!(v, views::ExternalIp::Floating(..)) - && v.ip() == fip_resp.ip)); + assert!( + eip_list + .iter() + .any(|v| matches!(v, views::ExternalIp::Floating(..)) + && v.ip() == fip_resp.ip) + ); assert_eq!(fip.ip, fip_resp.ip); // Check for idempotency: repeat requests should return same values. diff --git a/nexus/tests/integration_tests/host_phase1_updater.rs b/nexus/tests/integration_tests/host_phase1_updater.rs index b2e4a5bc1c1..aec8166b216 100644 --- a/nexus/tests/integration_tests/host_phase1_updater.rs +++ b/nexus/tests/integration_tests/host_phase1_updater.rs @@ -14,8 +14,8 @@ use omicron_nexus::app::test_interfaces::{ use rand::RngCore; use sp_sim::SimulatedSp; use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; diff --git a/nexus/tests/integration_tests/images.rs b/nexus/tests/integration_tests/images.rs index 9d608937cef..998a4283b18 100644 --- a/nexus/tests/integration_tests/images.rs +++ b/nexus/tests/integration_tests/images.rs @@ -5,16 +5,16 @@ //! Tests images support in the API use dropshot::ResultsPage; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_db_queries::db::fixed_data::silo::DEFAULT_SILO; use nexus_db_queries::db::fixed_data::silo_user::USER_TEST_UNPRIVILEGED; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; +use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::grant_iam; -use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::shared::ProjectRole; use nexus_types::external_api::shared::SiloRole; diff --git a/nexus/tests/integration_tests/initialization.rs b/nexus/tests/integration_tests/initialization.rs index a15b3e8d4b3..8775176ad6d 100644 --- a/nexus/tests/integration_tests/initialization.rs +++ b/nexus/tests/integration_tests/initialization.rs @@ -5,13 +5,13 @@ use nexus_config::Database; use nexus_config::InternalDns; use nexus_test_interface::NexusServer; -use nexus_test_utils::{load_test_config, ControlPlaneTestContextBuilder}; +use nexus_test_utils::{ControlPlaneTestContextBuilder, load_test_config}; use omicron_common::address::MGS_PORT; use omicron_common::api::internal::shared::SwitchLocation; use std::collections::HashMap; +use tokio::time::Duration; use tokio::time::sleep; use tokio::time::timeout; -use tokio::time::Duration; #[tokio::test] async fn test_nexus_boots_before_cockroach() { diff --git a/nexus/tests/integration_tests/instances.rs b/nexus/tests/integration_tests/instances.rs index 2470bd5c24e..ceb13c99d38 100644 --- a/nexus/tests/integration_tests/instances.rs +++ b/nexus/tests/integration_tests/instances.rs @@ -8,17 +8,18 @@ use super::external_ips::floating_ip_get; use super::external_ips::get_floating_ip_by_id_url; use super::metrics::{get_latest_silo_metric, get_latest_system_metric}; -use http::method::Method; use http::StatusCode; +use http::method::Method; use itertools::Itertools; use nexus_auth::authz::Action; use nexus_db_queries::context::OpContext; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::fixed_data::silo::DEFAULT_SILO; use nexus_db_queries::db::lookup::LookupPath; -use nexus_db_queries::db::DataStore; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; +use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::assert_ip_pool_utilization; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_disk; @@ -34,7 +35,6 @@ use nexus_test_utils::resource_helpers::object_delete; use nexus_test_utils::resource_helpers::object_delete_error; use nexus_test_utils::resource_helpers::object_put; use nexus_test_utils::resource_helpers::objects_list_page_authz; -use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::wait_for_producer; use nexus_types::external_api::params::SshKeyCreate; use nexus_types::external_api::shared::IpKind; @@ -63,11 +63,11 @@ use omicron_common::api::external::Vni; use omicron_common::api::internal::shared::ResolvedVpcRoute; use omicron_common::api::internal::shared::RouterId; use omicron_common::api::internal::shared::RouterKind; +use omicron_nexus::Nexus; +use omicron_nexus::TestInterfaces as _; use omicron_nexus::app::MAX_MEMORY_BYTES_PER_INSTANCE; use omicron_nexus::app::MAX_VCPU_PER_INSTANCE; use omicron_nexus::app::MIN_MEMORY_BYTES_PER_INSTANCE; -use omicron_nexus::Nexus; -use omicron_nexus::TestInterfaces as _; use omicron_sled_agent::sim::SledAgent; use omicron_test_utils::dev::poll::wait_for_condition; use omicron_uuid_kinds::PropolisUuid; @@ -2018,9 +2018,11 @@ async fn test_instances_invalid_creation_returns_bad_request( ) .await .unwrap_err(); - assert!(error - .message - .starts_with("unable to parse JSON body: EOF while parsing an object")); + assert!( + error.message.starts_with( + "unable to parse JSON body: EOF while parsing an object" + ) + ); let request_body = r##" { @@ -2150,7 +2152,7 @@ async fn test_instance_create_saga_removes_instance_database_record( }; let interface_params = params::InstanceNetworkInterfaceAttachment::Create(vec![ - if0_params.clone() + if0_params.clone(), ]); // Create the parameters for the instance itself, and create it. @@ -2229,7 +2231,7 @@ async fn test_instance_create_saga_removes_instance_database_record( }; let interface_params = params::InstanceNetworkInterfaceAttachment::Create(vec![ - if0_params.clone() + if0_params.clone(), ]); let instance_params = params::InstanceCreate { network_interfaces: interface_params, @@ -2271,7 +2273,7 @@ async fn test_instance_with_single_explicit_ip_address( }; let interface_params = params::InstanceNetworkInterfaceAttachment::Create(vec![ - if0_params.clone() + if0_params.clone(), ]); // Create the parameters for the instance itself, and create it. @@ -3381,10 +3383,9 @@ async fn test_instance_create_attach_disks_undo( // set `faulted_disk` to the faulted state let apictx = &cptestctx.server.server_context(); let nexus = &apictx.nexus; - assert!(nexus - .set_disk_as_faulted(&faulted_disk.identity.id) - .await - .unwrap()); + assert!( + nexus.set_disk_as_faulted(&faulted_disk.identity.id).await.unwrap() + ); // Assert regular and faulted disks were created let disks: Vec = diff --git a/nexus/tests/integration_tests/internet_gateway.rs b/nexus/tests/integration_tests/internet_gateway.rs index 11c3addee5a..c7f9a40cfc8 100644 --- a/nexus/tests/integration_tests/internet_gateway.rs +++ b/nexus/tests/integration_tests/internet_gateway.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use dropshot::{test_util::ClientTestContext, ResultsPage}; +use dropshot::{ResultsPage, test_util::ClientTestContext}; use http::{Method, StatusCode}; use nexus_db_queries::db::fixed_data::silo::DEFAULT_SILO; use nexus_test_utils::{ diff --git a/nexus/tests/integration_tests/ip_pools.rs b/nexus/tests/integration_tests/ip_pools.rs index e148d5b2391..cb42b7d4d4c 100644 --- a/nexus/tests/integration_tests/ip_pools.rs +++ b/nexus/tests/integration_tests/ip_pools.rs @@ -7,11 +7,11 @@ use std::net::Ipv4Addr; use crate::integration_tests::instances::instance_wait_for_state; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; use dropshot::ResultsPage; -use http::method::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; +use http::method::Method; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::datastore::SERVICE_IP_POOL_NAME; diff --git a/nexus/tests/integration_tests/metrics.rs b/nexus/tests/integration_tests/metrics.rs index 68ee5aceadc..45e3b639c95 100644 --- a/nexus/tests/integration_tests/metrics.rs +++ b/nexus/tests/integration_tests/metrics.rs @@ -5,7 +5,7 @@ use std::time::Duration; use crate::integration_tests::instances::{ - create_project_and_pool, instance_post, instance_simulate, InstanceOp, + InstanceOp, create_project_and_pool, instance_post, instance_simulate, }; use chrono::Utc; use dropshot::test_util::ClientTestContext; @@ -13,24 +13,24 @@ use dropshot::{HttpErrorResponseBody, ResultsPage}; use http::{Method, StatusCode}; use nexus_auth::authn::USER_TEST_UNPRIVILEGED; use nexus_db_queries::db::identity::Asset; +use nexus_test_utils::ControlPlaneTestContext; use nexus_test_utils::background::activate_background_task; use nexus_test_utils::http_testing::{AuthnMode, NexusRequest, RequestBuilder}; use nexus_test_utils::resource_helpers::{ - create_default_ip_pool, create_disk, create_instance, create_project, - grant_iam, object_create_error, objects_list_page_authz, DiskTest, + DiskTest, create_default_ip_pool, create_disk, create_instance, + create_project, grant_iam, object_create_error, objects_list_page_authz, }; use nexus_test_utils::wait_for_producer; -use nexus_test_utils::ControlPlaneTestContext; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::shared::ProjectRole; use nexus_types::external_api::views::OxqlQueryResult; use nexus_types::silo::DEFAULT_SILO_ID; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use omicron_uuid_kinds::{GenericUuid, InstanceUuid}; +use oximeter::TimeseriesSchema; use oximeter::types::Datum; use oximeter::types::FieldValue; use oximeter::types::Measurement; -use oximeter::TimeseriesSchema; use std::borrow::Borrow; use std::collections::HashMap; use uuid::Uuid; @@ -950,16 +950,20 @@ async fn test_mgs_metrics( n_points > 0, "{name} timeseries {fields:?} should have points" ); - let serial_str: &str = match timeseries.fields.get("chassis_serial") - { - Some(FieldValue::String(s)) => s.borrow(), - Some(x) => panic!( - "{name} `chassis_serial` field should be a string, but got: {x:?}" - ), - None => { - panic!("{name} timeseries should have a `chassis_serial` field") - } - }; + let serial_str: &str = match timeseries + .fields + .get("chassis_serial") + { + Some(FieldValue::String(s)) => s.borrow(), + Some(x) => panic!( + "{name} `chassis_serial` field should be a string, but got: {x:?}" + ), + None => { + panic!( + "{name} timeseries should have a `chassis_serial` field" + ) + } + }; if let Some(count) = found.get_mut(serial_str) { *count += 1; } else { diff --git a/nexus/tests/integration_tests/oximeter.rs b/nexus/tests/integration_tests/oximeter.rs index a722deafba0..53527272216 100644 --- a/nexus/tests/integration_tests/oximeter.rs +++ b/nexus/tests/integration_tests/oximeter.rs @@ -7,7 +7,7 @@ use nexus_test_interface::NexusServer; use nexus_test_utils::wait_for_producer; use nexus_test_utils_macros::nexus_test; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use oximeter_db::DbWrite; use std::time::Duration; use uuid::Uuid; @@ -198,8 +198,10 @@ async fn test_oximeter_reregistration() { ) { assert_eq!(timeseries.timeseries_name, new_timeseries.timeseries_name); assert_eq!(timeseries.target, new_timeseries.target); - assert!(timeseries.measurements.len() <= new_timeseries.measurements.len(), - "New timeseries should have at least as many measurements as the original"); + assert!( + timeseries.measurements.len() <= new_timeseries.measurements.len(), + "New timeseries should have at least as many measurements as the original" + ); let n_measurements = timeseries.measurements.len(); assert_eq!( timeseries.measurements, diff --git a/nexus/tests/integration_tests/pantry.rs b/nexus/tests/integration_tests/pantry.rs index 37e5aa63299..fc5becdb0e2 100644 --- a/nexus/tests/integration_tests/pantry.rs +++ b/nexus/tests/integration_tests/pantry.rs @@ -6,17 +6,17 @@ use crate::integration_tests::instances::instance_wait_for_state; use dropshot::test_util::ClientTestContext; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; use nexus_test_utils::identity_eq; +use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_instance; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::object_create; -use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use nexus_types::external_api::views::Snapshot; diff --git a/nexus/tests/integration_tests/password_login.rs b/nexus/tests/integration_tests/password_login.rs index 23f86484c9c..12bf526f50a 100644 --- a/nexus/tests/integration_tests/password_login.rs +++ b/nexus/tests/integration_tests/password_login.rs @@ -3,7 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use dropshot::test_util::ClientTestContext; -use http::{header, method::Method, StatusCode}; +use http::{StatusCode, header, method::Method}; use nexus_test_utils::http_testing::{AuthnMode, NexusRequest, RequestBuilder}; use nexus_test_utils::resource_helpers::grant_iam; use nexus_test_utils::resource_helpers::{create_local_user, create_silo}; diff --git a/nexus/tests/integration_tests/probe.rs b/nexus/tests/integration_tests/probe.rs index 53ad6a3ef91..197e5410f0a 100644 --- a/nexus/tests/integration_tests/probe.rs +++ b/nexus/tests/integration_tests/probe.rs @@ -1,9 +1,9 @@ use dropshot::HttpErrorResponseBody; use http::{Method, StatusCode}; use nexus_test_utils::{ + SLED_AGENT_UUID, http_testing::{AuthnMode, NexusRequest}, resource_helpers::{create_default_ip_pool, create_project}, - SLED_AGENT_UUID, }; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::{params::ProbeCreate, shared::ProbeInfo}; diff --git a/nexus/tests/integration_tests/projects.rs b/nexus/tests/integration_tests/projects.rs index d9752b1949f..66328755b54 100644 --- a/nexus/tests/integration_tests/projects.rs +++ b/nexus/tests/integration_tests/projects.rs @@ -2,17 +2,17 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; -use http::method::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; use nexus_test_utils::resource_helpers::create_floating_ip; use nexus_test_utils::resource_helpers::{ - create_default_ip_pool, create_disk, create_project, create_vpc, - object_create, project_get, projects_list, DiskTest, + DiskTest, create_default_ip_pool, create_disk, create_project, create_vpc, + object_create, project_get, projects_list, }; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; diff --git a/nexus/tests/integration_tests/quotas.rs b/nexus/tests/integration_tests/quotas.rs index b7c6c0e53f5..a94cc2c14cd 100644 --- a/nexus/tests/integration_tests/quotas.rs +++ b/nexus/tests/integration_tests/quotas.rs @@ -1,17 +1,17 @@ use anyhow::Error; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; +use dropshot::test_util::ClientTestContext; use http::Method; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; use nexus_test_utils::http_testing::TestResponse; +use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::create_ip_pool; use nexus_test_utils::resource_helpers::create_local_user; use nexus_test_utils::resource_helpers::grant_iam; use nexus_test_utils::resource_helpers::link_ip_pool; use nexus_test_utils::resource_helpers::object_create; -use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use nexus_types::external_api::shared; diff --git a/nexus/tests/integration_tests/rack.rs b/nexus/tests/integration_tests/rack.rs index f4b67e0afd8..c7cc8a65b73 100644 --- a/nexus/tests/integration_tests/rack.rs +++ b/nexus/tests/integration_tests/rack.rs @@ -10,10 +10,10 @@ use nexus_db_model::SledBaseboard; use nexus_db_model::SledSystemHardware; use nexus_db_model::SledUpdate; use nexus_sled_agent_shared::inventory::SledRole; +use nexus_test_utils::TEST_SUITE_PASSWORD; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; -use nexus_test_utils::TEST_SUITE_PASSWORD; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use nexus_types::external_api::shared::UninitializedSled; diff --git a/nexus/tests/integration_tests/role_assignments.rs b/nexus/tests/integration_tests/role_assignments.rs index 91c0b7c6b73..7cdb952ad77 100644 --- a/nexus/tests/integration_tests/role_assignments.rs +++ b/nexus/tests/integration_tests/role_assignments.rs @@ -5,9 +5,9 @@ //! Basic test for role assignments use dropshot::test_util::ClientTestContext; -use futures::future::BoxFuture; use futures::Future; use futures::FutureExt; +use futures::future::BoxFuture; use http::Method; use http::StatusCode; use nexus_db_queries::authn::USER_TEST_UNPRIVILEGED; diff --git a/nexus/tests/integration_tests/rot_updater.rs b/nexus/tests/integration_tests/rot_updater.rs index 6be83e8ed0a..4a1ba366788 100644 --- a/nexus/tests/integration_tests/rot_updater.rs +++ b/nexus/tests/integration_tests/rot_updater.rs @@ -12,11 +12,11 @@ use hubtools::{CabooseBuilder, HubrisArchiveBuilder}; use omicron_nexus::app::test_interfaces::{ MgsClients, RotUpdater, UpdateProgress, }; -use sp_sim::SimulatedSp; use sp_sim::SIM_ROT_BOARD; +use sp_sim::SimulatedSp; use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; diff --git a/nexus/tests/integration_tests/router_routes.rs b/nexus/tests/integration_tests/router_routes.rs index dcc2b24589d..6da0ba39cda 100644 --- a/nexus/tests/integration_tests/router_routes.rs +++ b/nexus/tests/integration_tests/router_routes.rs @@ -2,9 +2,9 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; use dropshot::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; use itertools::Itertools; use nexus_test_utils::http_testing::AuthnMode; @@ -80,10 +80,30 @@ async fn get_system_routes( let mut subnet_route = None; for route in system_router_routes { match (&route.kind, &route.destination, &route.target) { - (RouterRouteKind::Default, RouteDestination::IpNet(IpNet::V4(_)), RouteTarget::InternetGateway(_)) => {v4_route = Some(route);}, - (RouterRouteKind::Default, RouteDestination::IpNet(IpNet::V6(_)), RouteTarget::InternetGateway(_)) => {v6_route = Some(route);}, - (RouterRouteKind::VpcSubnet, RouteDestination::Subnet(n0), RouteTarget::Subnet(n1)) if n0 == n1 && n0.as_str() == "default" => {subnet_route = Some(route);}, - _ => panic!("unexpected system route {route:?} -- wanted gateway and subnet"), + ( + RouterRouteKind::Default, + RouteDestination::IpNet(IpNet::V4(_)), + RouteTarget::InternetGateway(_), + ) => { + v4_route = Some(route); + } + ( + RouterRouteKind::Default, + RouteDestination::IpNet(IpNet::V6(_)), + RouteTarget::InternetGateway(_), + ) => { + v6_route = Some(route); + } + ( + RouterRouteKind::VpcSubnet, + RouteDestination::Subnet(n0), + RouteTarget::Subnet(n1), + ) if n0 == n1 && n0.as_str() == "default" => { + subnet_route = Some(route); + } + _ => panic!( + "unexpected system route {route:?} -- wanted gateway and subnet" + ), } } diff --git a/nexus/tests/integration_tests/saml.rs b/nexus/tests/integration_tests/saml.rs index a83bcf3d471..4b1795a67bc 100644 --- a/nexus/tests/integration_tests/saml.rs +++ b/nexus/tests/integration_tests/saml.rs @@ -17,9 +17,9 @@ use omicron_nexus::TestInterfaces; use base64::Engine; use dropshot::ResultsPage; -use http::method::Method; use http::StatusCode; -use httptest::{matchers::*, responders::*, Expectation, Server}; +use http::method::Method; +use httptest::{Expectation, Server, matchers::*, responders::*}; use uuid::Uuid; type ControlPlaneTestContext = @@ -146,13 +146,11 @@ async fn test_create_a_saml_idp(cptestctx: &ControlPlaneTestContext) { .await .expect("expected success"); - assert!(result.headers["Location"] - .to_str() - .unwrap() - .to_string() - .starts_with( + assert!( + result.headers["Location"].to_str().unwrap().to_string().starts_with( "https://idp.example.org/SAML2/SSO/Redirect?SAMLRequest=", - )); + ) + ); } // Fail to create a SAML IdP out of an invalid descriptor @@ -240,8 +238,10 @@ async fn test_create_a_saml_idp_invalid_descriptor_no_redirect_binding( .join("\n") }; - assert!(!saml_idp_descriptor - .contains("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")); + assert!( + !saml_idp_descriptor + .contains("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect") + ); let server = Server::run(); server.expect( @@ -464,13 +464,11 @@ async fn test_create_a_hidden_silo_saml_idp( .await .expect("expected success"); - assert!(result.headers["Location"] - .to_str() - .unwrap() - .to_string() - .starts_with( + assert!( + result.headers["Location"].to_str().unwrap().to_string().starts_with( "https://idp.example.org/SAML2/SSO/Redirect?SAMLRequest=", - )); + ) + ); } // Can't create a SAML IdP if the metadata URL returns something that's not 200 @@ -1341,11 +1339,13 @@ async fn test_post_saml_response_with_relay_state( .await .expect("expected success"); - assert!(result_with_relay_state.headers["Location"] - .to_str() - .unwrap() - .to_string() - .ends_with("/some/actual/nexus/url")); + assert!( + result_with_relay_state.headers["Location"] + .to_str() + .unwrap() + .to_string() + .ends_with("/some/actual/nexus/url") + ); let result_with_invalid_relay_state = NexusRequest::new( RequestBuilder::new( diff --git a/nexus/tests/integration_tests/schema.rs b/nexus/tests/integration_tests/schema.rs index 9cc42800e88..8f798aed70b 100644 --- a/nexus/tests/integration_tests/schema.rs +++ b/nexus/tests/integration_tests/schema.rs @@ -11,9 +11,9 @@ use nexus_config::SchemaConfig; use nexus_db_model::EARLIEST_SUPPORTED_VERSION; use nexus_db_model::SCHEMA_VERSION as LATEST_SCHEMA_VERSION; use nexus_db_model::{AllSchemaVersions, SchemaVersion}; -use nexus_db_queries::db::pub_test_utils::TestDatabase; use nexus_db_queries::db::DISALLOW_FULL_TABLE_SCAN_SQL; -use nexus_test_utils::{load_test_config, ControlPlaneTestContextBuilder}; +use nexus_db_queries::db::pub_test_utils::TestDatabase; +use nexus_test_utils::{ControlPlaneTestContextBuilder, load_test_config}; use omicron_common::api::external::SemverVersion; use omicron_common::api::internal::shared::SwitchLocation; use omicron_test_utils::dev::db::{Client, CockroachInstance}; @@ -24,8 +24,8 @@ use similar_asserts; use slog::Logger; use std::collections::BTreeMap; use std::net::IpAddr; -use tokio::time::timeout; use tokio::time::Duration; +use tokio::time::timeout; use uuid::Uuid; const SCHEMA_DIR: &'static str = @@ -981,10 +981,10 @@ async fn dbinit_equals_sum_of_all_up() { // with a `type with ID $NUM does not exist` error. { use async_bb8_diesel::AsyncRunQueryDsl; - use nexus_db_model::schema::sled_resource::dsl; use nexus_db_model::Resources; use nexus_db_model::SledResource; use nexus_db_model::SledResourceKind; + use nexus_db_model::schema::sled_resource::dsl; diesel::insert_into(dsl::sled_resource) .values(SledResource { diff --git a/nexus/tests/integration_tests/silo_users.rs b/nexus/tests/integration_tests/silo_users.rs index ca3039f19b5..025f81ea238 100644 --- a/nexus/tests/integration_tests/silo_users.rs +++ b/nexus/tests/integration_tests/silo_users.rs @@ -3,7 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use dropshot::test_util::ClientTestContext; -use http::{method::Method, StatusCode}; +use http::{StatusCode, method::Method}; use nexus_db_queries::authn::USER_TEST_UNPRIVILEGED; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; diff --git a/nexus/tests/integration_tests/silos.rs b/nexus/tests/integration_tests/silos.rs index 90166cc1ac7..32a90dc6721 100644 --- a/nexus/tests/integration_tests/silos.rs +++ b/nexus/tests/integration_tests/silos.rs @@ -31,7 +31,7 @@ use omicron_common::api::external::{ }; use omicron_common::api::external::{ObjectIdentity, UserId}; use omicron_test_utils::certificates::CertificateChain; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fmt::Write; @@ -39,9 +39,9 @@ use std::str::FromStr; use base64::Engine; use hickory_resolver::error::ResolveErrorKind; -use http::method::Method; use http::StatusCode; -use httptest::{matchers::*, responders::*, Expectation, Server}; +use http::method::Method; +use httptest::{Expectation, Server, matchers::*, responders::*}; use nexus_types::external_api::shared::{FleetRole, SiloRole}; use std::convert::Infallible; use std::net::Ipv4Addr; @@ -305,16 +305,18 @@ async fn test_silo_admin_group(cptestctx: &ControlPlaneTestContext) { .await .unwrap(); - assert!(nexus - .datastore() - .silo_group_optional_lookup( - &authn_opctx, - &authz_silo, - "administrator".into(), - ) - .await - .unwrap() - .is_some()); + assert!( + nexus + .datastore() + .silo_group_optional_lookup( + &authn_opctx, + &authz_silo, + "administrator".into(), + ) + .await + .unwrap() + .is_some() + ); // Test that a user is granted privileges from their group membership let admin_group_user = nexus @@ -631,13 +633,11 @@ async fn test_saml_idp_metadata_data_valid( .await .expect("expected success"); - assert!(result.headers["Location"] - .to_str() - .unwrap() - .to_string() - .starts_with( + assert!( + result.headers["Location"].to_str().unwrap().to_string().starts_with( "https://idp.example.org/SAML2/SSO/Redirect?SAMLRequest=", - )); + ) + ); } // Fail to create a Silo with a SAML IdP document string that isn't valid @@ -1429,16 +1429,18 @@ async fn test_silo_delete_clean_up_groups(cptestctx: &ControlPlaneTestContext) { .expect("failed to make request"); // Expect the group is gone - assert!(nexus - .datastore() - .silo_group_optional_lookup( - &opctx_external_authn, - &authz_silo, - "a-group".into(), - ) - .await - .expect("silo_group_optional_lookup") - .is_none()); + assert!( + nexus + .datastore() + .silo_group_optional_lookup( + &opctx_external_authn, + &authz_silo, + "a-group".into(), + ) + .await + .expect("silo_group_optional_lookup") + .is_none() + ); // Expect the group membership is gone let memberships = nexus diff --git a/nexus/tests/integration_tests/sleds.rs b/nexus/tests/integration_tests/sleds.rs index ef30cdf1f48..8735bd568e4 100644 --- a/nexus/tests/integration_tests/sleds.rs +++ b/nexus/tests/integration_tests/sleds.rs @@ -10,17 +10,17 @@ use nexus_db_model::PhysicalDisk as DbPhysicalDisk; use nexus_db_model::PhysicalDiskKind as DbPhysicalDiskKind; use nexus_db_queries::context::OpContext; use nexus_test_interface::NexusServer; +use nexus_test_utils::SLED_AGENT_UUID; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_instance; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::objects_list_page_authz; use nexus_test_utils::start_sled_agent; -use nexus_test_utils::SLED_AGENT_UUID; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::views::SledInstance; use nexus_types::external_api::views::{PhysicalDisk, Sled}; use omicron_sled_agent::sim; -use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; +use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::SledUuid; @@ -174,9 +174,11 @@ async fn test_sled_instance_list(cptestctx: &ControlPlaneTestContext) { let sled_id = sled.identity.id; let instances_url = format!("/v1/system/hardware/sleds/{sled_id}/instances"); - assert!(sled_instance_list(&external_client, &instances_url) - .await - .is_empty()); + assert!( + sled_instance_list(&external_client, &instances_url) + .await + .is_empty() + ); } // Create an IP pool and project that we'll use for testing. diff --git a/nexus/tests/integration_tests/snapshots.rs b/nexus/tests/integration_tests/snapshots.rs index d51a73e057e..ccad463f611 100644 --- a/nexus/tests/integration_tests/snapshots.rs +++ b/nexus/tests/integration_tests/snapshots.rs @@ -7,18 +7,19 @@ use crate::integration_tests::instances::instance_simulate; use chrono::Utc; use dropshot::test_util::ClientTestContext; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_config::RegionAllocationStrategy; use nexus_db_model::to_db_typed_uuid; use nexus_db_queries::authz; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; +use nexus_db_queries::db::datastore::REGION_REDUNDANCY_THRESHOLD; use nexus_db_queries::db::datastore::RegionAllocationFor; use nexus_db_queries::db::datastore::RegionAllocationParameters; -use nexus_db_queries::db::datastore::REGION_REDUNDANCY_THRESHOLD; use nexus_db_queries::db::identity::Resource; use nexus_db_queries::db::lookup::LookupPath; +use nexus_test_utils::SLED_AGENT_UUID; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; @@ -26,7 +27,6 @@ use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_disk; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::object_create; -use nexus_test_utils::SLED_AGENT_UUID; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use nexus_types::external_api::views; diff --git a/nexus/tests/integration_tests/sp_updater.rs b/nexus/tests/integration_tests/sp_updater.rs index 6e482bc1adf..cbd3c9d67d0 100644 --- a/nexus/tests/integration_tests/sp_updater.rs +++ b/nexus/tests/integration_tests/sp_updater.rs @@ -16,8 +16,8 @@ use sp_sim::SIM_GIMLET_BOARD; use sp_sim::SIM_SIDECAR_BOARD; use sp_sim::{SimSpHandledRequest, SimulatedSp}; use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; diff --git a/nexus/tests/integration_tests/ssh_keys.rs b/nexus/tests/integration_tests/ssh_keys.rs index 8d9fcc9c565..0187a4aa55f 100644 --- a/nexus/tests/integration_tests/ssh_keys.rs +++ b/nexus/tests/integration_tests/ssh_keys.rs @@ -1,6 +1,6 @@ //! Sanity-tests for public SSH keys -use http::{method::Method, StatusCode}; +use http::{StatusCode, method::Method}; use nexus_test_utils::http_testing::{AuthnMode, NexusRequest}; use nexus_test_utils::resource_helpers::objects_list_page_authz; diff --git a/nexus/tests/integration_tests/subnet_allocation.rs b/nexus/tests/integration_tests/subnet_allocation.rs index f504d771808..f17f78cc2b8 100644 --- a/nexus/tests/integration_tests/subnet_allocation.rs +++ b/nexus/tests/integration_tests/subnet_allocation.rs @@ -5,10 +5,10 @@ //! Tests that subnet allocation will successfully allocate the entire space of a //! subnet and error appropriately when the space is exhausted. -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; -use http::method::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; +use http::method::Method; use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; @@ -186,8 +186,7 @@ async fn test_subnet_allocation(cptestctx: &ControlPlaneTestContext) { .zip(subnet.addr_iter().skip(NUM_INITIAL_RESERVED_IP_ADDRESSES)) { assert_eq!( - iface.ip, - addr, + iface.ip, addr, "Nexus should provide auto-assigned IP addresses in order within an IP subnet" ); } diff --git a/nexus/tests/integration_tests/support_bundles.rs b/nexus/tests/integration_tests/support_bundles.rs index a49dfcb748a..d542d13d825 100644 --- a/nexus/tests/integration_tests/support_bundles.rs +++ b/nexus/tests/integration_tests/support_bundles.rs @@ -6,10 +6,10 @@ use anyhow::Context; use anyhow::Result; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; -use http::method::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; +use http::method::Method; use nexus_client::types::LastResult; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; diff --git a/nexus/tests/integration_tests/switch_port.rs b/nexus/tests/integration_tests/switch_port.rs index 89ddfe11ac6..f54ea64b328 100644 --- a/nexus/tests/integration_tests/switch_port.rs +++ b/nexus/tests/integration_tests/switch_port.rs @@ -4,8 +4,8 @@ //! Integration tests for operating on Ports -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::{AuthnMode, NexusRequest, RequestBuilder}; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params::{ diff --git a/nexus/tests/integration_tests/unauthorized.rs b/nexus/tests/integration_tests/unauthorized.rs index 7ec33d97f89..5eae01db280 100644 --- a/nexus/tests/integration_tests/unauthorized.rs +++ b/nexus/tests/integration_tests/unauthorized.rs @@ -7,12 +7,12 @@ use super::endpoints::*; use crate::integration_tests::saml::SAML_IDP_DESCRIPTOR; -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; +use dropshot::test_util::ClientTestContext; use headers::authorization::Credentials; -use http::method::Method; use http::StatusCode; -use httptest::{matchers::*, responders::*, Expectation, ServerBuilder}; +use http::method::Method; +use httptest::{Expectation, ServerBuilder, matchers::*, responders::*}; use nexus_db_queries::authn::external::spoof; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; diff --git a/nexus/tests/integration_tests/updates.rs b/nexus/tests/integration_tests/updates.rs index 37821a1b881..29715ef62a5 100644 --- a/nexus/tests/integration_tests/updates.rs +++ b/nexus/tests/integration_tests/updates.rs @@ -7,7 +7,7 @@ // - test that an unknown artifact returns 404, not 500 // - tests around target names and artifact names that contain dangerous paths like `../` -use anyhow::{ensure, Context, Result}; +use anyhow::{Context, Result, ensure}; use camino::Utf8Path; use camino_tempfile::{Builder, Utf8TempPath}; use clap::Parser; @@ -147,11 +147,10 @@ async fn test_repo_upload() -> Result<()> { .collect::>(), ["zone1", "zone2"] ); - assert!(!initial_description - .artifacts - .iter() - .any(|artifact| artifact.id.kind - == KnownArtifactKind::ControlPlane.into())); + assert!( + !initial_description.artifacts.iter().any(|artifact| artifact.id.kind + == KnownArtifactKind::ControlPlane.into()) + ); // The artifact replication background task should have been activated, and // we should see a local repo and successful PUTs. diff --git a/nexus/tests/integration_tests/utilization.rs b/nexus/tests/integration_tests/utilization.rs index 7d733c66b82..a65d5e89af2 100644 --- a/nexus/tests/integration_tests/utilization.rs +++ b/nexus/tests/integration_tests/utilization.rs @@ -3,11 +3,11 @@ use http::StatusCode; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; +use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils::resource_helpers::create_default_ip_pool; use nexus_test_utils::resource_helpers::create_instance; use nexus_test_utils::resource_helpers::create_project; use nexus_test_utils::resource_helpers::objects_list_page_authz; -use nexus_test_utils::resource_helpers::DiskTest; use nexus_test_utils_macros::nexus_test; use nexus_types::external_api::params; use nexus_types::external_api::params::SiloQuotasCreate; diff --git a/nexus/tests/integration_tests/volume_management.rs b/nexus/tests/integration_tests/volume_management.rs index ba5f41f6631..a6dfeec78bc 100644 --- a/nexus/tests/integration_tests/volume_management.rs +++ b/nexus/tests/integration_tests/volume_management.rs @@ -13,31 +13,31 @@ use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::SelectableHelper; use dropshot::test_util::ClientTestContext; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_config::RegionAllocationStrategy; -use nexus_db_model::to_db_typed_uuid; use nexus_db_model::CrucibleDataset; use nexus_db_model::RegionSnapshotReplacement; use nexus_db_model::RegionSnapshotReplacementState; use nexus_db_model::Volume; use nexus_db_model::VolumeResourceUsage; use nexus_db_model::VolumeResourceUsageRecord; +use nexus_db_model::to_db_typed_uuid; use nexus_db_queries::context::OpContext; use nexus_db_queries::db; +use nexus_db_queries::db::DataStore; use nexus_db_queries::db::datastore::CrucibleResources; use nexus_db_queries::db::datastore::ExistingTarget; use nexus_db_queries::db::datastore::RegionAllocationFor; use nexus_db_queries::db::datastore::RegionAllocationParameters; use nexus_db_queries::db::datastore::ReplacementTarget; +use nexus_db_queries::db::datastore::SQL_BATCH_SIZE; use nexus_db_queries::db::datastore::VolumeReplaceResult; use nexus_db_queries::db::datastore::VolumeToDelete; use nexus_db_queries::db::datastore::VolumeWithTarget; -use nexus_db_queries::db::datastore::SQL_BATCH_SIZE; use nexus_db_queries::db::lookup::LookupPath; -use nexus_db_queries::db::pagination::paginated; use nexus_db_queries::db::pagination::Paginator; -use nexus_db_queries::db::DataStore; +use nexus_db_queries::db::pagination::paginated; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; @@ -57,8 +57,8 @@ use omicron_common::api::external::Disk; use omicron_common::api::external::IdentityMetadataCreateParams; use omicron_common::api::external::Name; use omicron_common::api::internal; -use omicron_test_utils::dev::poll::wait_for_condition; use omicron_test_utils::dev::poll::CondCheckError; +use omicron_test_utils::dev::poll::wait_for_condition; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::DownstairsRegionUuid; use omicron_uuid_kinds::DownstairsUuid; @@ -69,7 +69,7 @@ use omicron_uuid_kinds::UpstairsUuid; use omicron_uuid_kinds::VolumeUuid; use omicron_uuid_kinds::ZpoolUuid; use rand::prelude::SliceRandom; -use rand::{rngs::StdRng, SeedableRng}; +use rand::{SeedableRng, rngs::StdRng}; use sled_agent_client::{CrucibleOpts, VolumeConstructionRequest}; use std::collections::HashSet; use std::net::{SocketAddr, SocketAddrV6}; @@ -3718,23 +3718,30 @@ impl TestReadOnlyRegionReferenceUsage { } pub async fn validate_region_returned_for_cleanup(&self) { - assert!(self - .datastore - .regions_to_delete(&self.last_resources_to_delete.as_ref().unwrap()) - .await - .unwrap() - .into_iter() - .any(|(_, r)| r.id() == self.region.id())); + assert!( + self.datastore + .regions_to_delete( + &self.last_resources_to_delete.as_ref().unwrap() + ) + .await + .unwrap() + .into_iter() + .any(|(_, r)| r.id() == self.region.id()) + ); } pub async fn validate_region_not_returned_for_cleanup(&self) { - assert!(!self - .datastore - .regions_to_delete(&self.last_resources_to_delete.as_ref().unwrap()) - .await - .unwrap() - .into_iter() - .any(|(_, r)| r.id() == self.region.id())); + assert!( + !self + .datastore + .regions_to_delete( + &self.last_resources_to_delete.as_ref().unwrap() + ) + .await + .unwrap() + .into_iter() + .any(|(_, r)| r.id() == self.region.id()) + ); } // read-only regions should never be returned by find_deleted_volume_regions @@ -3742,10 +3749,12 @@ impl TestReadOnlyRegionReferenceUsage { let freed_crucible_resources = self.datastore.find_deleted_volume_regions().await.unwrap(); - assert!(!freed_crucible_resources - .datasets_and_regions - .into_iter() - .any(|(_, r)| r.id() == self.region.id())); + assert!( + !freed_crucible_resources + .datasets_and_regions + .into_iter() + .any(|(_, r)| r.id() == self.region.id()) + ); } pub async fn create_first_volume_region_in_rop(&self) { @@ -4148,15 +4157,17 @@ async fn test_read_only_region_reference_counting( let read_only_region_address: SocketAddrV6 = nexus.region_addr(&opctx.log, read_only_region.id()).await.unwrap(); - assert!(datastore - .find_volumes_referencing_socket_addr( - &opctx, - read_only_region_address.into() - ) - .await - .unwrap() - .iter() - .any(|volume| volume.id() == db_disk_from_snapshot.volume_id())); + assert!( + datastore + .find_volumes_referencing_socket_addr( + &opctx, + read_only_region_address.into() + ) + .await + .unwrap() + .iter() + .any(|volume| volume.id() == db_disk_from_snapshot.volume_id()) + ); // Expect that there are two read-only region references now: one in the // snapshot volume, and one in the disk-from-snap volume. @@ -4172,9 +4183,11 @@ async fn test_read_only_region_reference_counting( assert_eq!(usage.len(), 2); assert!(usage.iter().any(|r| r.volume_id() == db_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id())); + assert!( + usage + .iter() + .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id()) + ); // Deleting the snapshot should _not_ cause the region to get deleted from // CRDB @@ -4409,15 +4422,17 @@ async fn test_read_only_region_reference_counting_layers( let read_only_region_address: SocketAddrV6 = nexus.region_addr(&opctx.log, read_only_region.id()).await.unwrap(); - assert!(datastore - .find_volumes_referencing_socket_addr( - &opctx, - read_only_region_address.into() - ) - .await - .unwrap() - .iter() - .any(|volume| volume.id() == db_disk_from_snapshot.volume_id())); + assert!( + datastore + .find_volumes_referencing_socket_addr( + &opctx, + read_only_region_address.into() + ) + .await + .unwrap() + .iter() + .any(|volume| volume.id() == db_disk_from_snapshot.volume_id()) + ); // Expect that there are two read-only region references now: one in the // snapshot volume, and one in the disk-from-snap volume. @@ -4433,9 +4448,11 @@ async fn test_read_only_region_reference_counting_layers( assert_eq!(usage.len(), 2); assert!(usage.iter().any(|r| r.volume_id() == db_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id())); + assert!( + usage + .iter() + .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id()) + ); // Take a snapshot of the disk-from-snapshot disk @@ -4471,12 +4488,14 @@ async fn test_read_only_region_reference_counting_layers( assert_eq!(usage.len(), 3); assert!(usage.iter().any(|r| r.volume_id() == db_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_double_snapshot.volume_id())); + assert!( + usage + .iter() + .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id()) + ); + assert!( + usage.iter().any(|r| r.volume_id() == db_double_snapshot.volume_id()) + ); // Delete resources, assert volume resource usage records along the way @@ -4499,9 +4518,9 @@ async fn test_read_only_region_reference_counting_layers( assert_eq!(usage.len(), 2); assert!(usage.iter().any(|r| r.volume_id() == db_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_double_snapshot.volume_id())); + assert!( + usage.iter().any(|r| r.volume_id() == db_double_snapshot.volume_id()) + ); NexusRequest::object_delete(client, &get_snapshot_url("snapshot")) .authn_as(AuthnMode::PrivilegedUser) @@ -4521,9 +4540,9 @@ async fn test_read_only_region_reference_counting_layers( .unwrap(); assert_eq!(usage.len(), 1); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_double_snapshot.volume_id())); + assert!( + usage.iter().any(|r| r.volume_id() == db_double_snapshot.volume_id()) + ); NexusRequest::object_delete(client, &get_snapshot_url("double-snapshot")) .authn_as(AuthnMode::PrivilegedUser) @@ -4852,9 +4871,11 @@ async fn test_volume_remove_rop_respects_accounting( assert_eq!(usage.len(), 2); assert!(usage.iter().any(|r| r.volume_id() == db_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id())); + assert!( + usage + .iter() + .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id()) + ); } // Remove the ROP from disk-from-snapshot @@ -5034,9 +5055,11 @@ async fn test_volume_remove_rop_respects_accounting_no_modify_others( assert_eq!(usage.len(), 3); assert!(usage.iter().any(|r| r.volume_id() == db_snapshot.volume_id())); - assert!(usage - .iter() - .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id())); + assert!( + usage + .iter() + .any(|r| r.volume_id() == db_disk_from_snapshot.volume_id()) + ); assert!(usage.iter().any( |r| r.volume_id() == db_another_disk_from_snapshot.volume_id() )); @@ -5124,8 +5147,10 @@ async fn perform_migration(datastore: &DataStore) { "../../../schema/crdb/crucible-ref-count-records/up08.sql" ); - assert!(MIGRATION_TO_REF_COUNT_WITH_RECORDS_SQL - .contains("INSERT INTO volume_resource_usage")); + assert!( + MIGRATION_TO_REF_COUNT_WITH_RECORDS_SQL + .contains("INSERT INTO volume_resource_usage") + ); let conn = datastore.pool_connection_for_tests().await.unwrap(); @@ -5344,11 +5369,9 @@ async fn test_migrate_to_ref_count_with_records_soft_delete_volume( // Assert that the region snapshots did not have deleted set to true - assert!(datastore - .snapshots_to_delete(&resources) - .await - .unwrap() - .is_empty()); + assert!( + datastore.snapshots_to_delete(&resources).await.unwrap().is_empty() + ); // This means that the snapshot volume is soft-deleted, make sure the // migration does not make usage records for it! diff --git a/nexus/tests/integration_tests/vpc_firewall.rs b/nexus/tests/integration_tests/vpc_firewall.rs index b06e01b5395..83bc5599ba8 100644 --- a/nexus/tests/integration_tests/vpc_firewall.rs +++ b/nexus/tests/integration_tests/vpc_firewall.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::{AuthnMode, NexusRequest}; use nexus_test_utils::resource_helpers::{ create_project, create_vpc, object_get, object_put, object_put_error, @@ -319,7 +319,10 @@ async fn test_firewall_rules_same_name(cptestctx: &ControlPlaneTestContext) { ) .await; assert_eq!(error.error_code, Some("InvalidValue".to_string())); - assert_eq!(error.message, "unsupported value for \"rules\": Rule names must be unique. Duplicates: [\"dupe\"]"); + assert_eq!( + error.message, + "unsupported value for \"rules\": Rule names must be unique. Duplicates: [\"dupe\"]" + ); } #[nexus_test] diff --git a/nexus/tests/integration_tests/vpc_routers.rs b/nexus/tests/integration_tests/vpc_routers.rs index c364bc26bf1..205b2fde689 100644 --- a/nexus/tests/integration_tests/vpc_routers.rs +++ b/nexus/tests/integration_tests/vpc_routers.rs @@ -5,8 +5,8 @@ use crate::integration_tests::instances::assert_sled_vpc_routes; use crate::integration_tests::instances::instance_simulate; use dropshot::test_util::ClientTestContext; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_db_queries::context::OpContext; use nexus_db_queries::db::lookup::LookupPath; use nexus_test_utils::http_testing::AuthnMode; diff --git a/nexus/tests/integration_tests/vpc_subnets.rs b/nexus/tests/integration_tests/vpc_subnets.rs index f063c7e9a26..9d9cbea3982 100644 --- a/nexus/tests/integration_tests/vpc_subnets.rs +++ b/nexus/tests/integration_tests/vpc_subnets.rs @@ -2,13 +2,13 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::integration_tests::instances::InstanceOp; use crate::integration_tests::instances::instance_post; use crate::integration_tests::instances::instance_simulate; use crate::integration_tests::instances::instance_wait_for_state; -use crate::integration_tests::instances::InstanceOp; use dropshot::HttpErrorResponseBody; -use http::method::Method; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; diff --git a/nexus/tests/integration_tests/vpcs.rs b/nexus/tests/integration_tests/vpcs.rs index 1ceebd8cff4..054a28334e4 100644 --- a/nexus/tests/integration_tests/vpcs.rs +++ b/nexus/tests/integration_tests/vpcs.rs @@ -2,10 +2,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use dropshot::test_util::ClientTestContext; use dropshot::HttpErrorResponseBody; -use http::method::Method; +use dropshot::test_util::ClientTestContext; use http::StatusCode; +use http::method::Method; use nexus_test_utils::http_testing::AuthnMode; use nexus_test_utils::http_testing::NexusRequest; use nexus_test_utils::http_testing::RequestBuilder; diff --git a/nexus/types/src/authn/cookies.rs b/nexus/types/src/authn/cookies.rs index 35e697475be..85614828696 100644 --- a/nexus/types/src/authn/cookies.rs +++ b/nexus/types/src/authn/cookies.rs @@ -59,8 +59,8 @@ impl SharedExtractor for Cookies { mod test { use super::parse_cookies; use http::{ - header::{ACCEPT, COOKIE}, HeaderMap, + header::{ACCEPT, COOKIE}, }; #[test] diff --git a/nexus/types/src/deployment.rs b/nexus/types/src/deployment.rs index 41d0ac9434e..4c6aaf7dd17 100644 --- a/nexus/types/src/deployment.rs +++ b/nexus/types/src/deployment.rs @@ -89,14 +89,14 @@ pub use planning_input::SledLookupError; pub use planning_input::SledLookupErrorKind; pub use planning_input::SledResources; pub use planning_input::ZpoolFilter; -pub use zone_type::blueprint_zone_type; pub use zone_type::BlueprintZoneType; pub use zone_type::DurableDataset; +pub use zone_type::blueprint_zone_type; use blueprint_display::{ - constants::*, BpDiffState, BpGeneration, BpOmicronZonesTableSchema, + BpDiffState, BpGeneration, BpOmicronZonesTableSchema, BpPhysicalDisksTableSchema, BpTable, BpTableData, BpTableRow, - KvListWithHeading, + KvListWithHeading, constants::*, }; use id_map::{IdMap, IdMappable}; diff --git a/nexus/types/src/deployment/blueprint_diff.rs b/nexus/types/src/deployment/blueprint_diff.rs index c43476a353b..ffd93e50a29 100644 --- a/nexus/types/src/deployment/blueprint_diff.rs +++ b/nexus/types/src/deployment/blueprint_diff.rs @@ -5,18 +5,17 @@ //! Types helpful for diffing blueprints. use super::blueprint_display::{ - constants::*, linear_table_modified, linear_table_unchanged, BpClickhouseServersTableSchema, BpDatasetsTableSchema, BpDiffState, BpGeneration, BpOmicronZonesTableSchema, BpPhysicalDisksTableSchema, BpTable, BpTableColumn, BpTableData, BpTableRow, KvListWithHeading, KvPair, + constants::*, linear_table_modified, linear_table_unchanged, }; use super::{ - unwrap_or_none, zone_sort_key, BlueprintDatasetConfigDiff, - BlueprintDatasetDisposition, BlueprintDatasetsConfigDiff, BlueprintDiff, - BlueprintMetadata, BlueprintPhysicalDiskConfig, - BlueprintPhysicalDisksConfigDiff, BlueprintZoneConfigDiff, - BlueprintZonesConfigDiff, ClickhouseClusterConfig, - CockroachDbPreserveDowngrade, + BlueprintDatasetConfigDiff, BlueprintDatasetDisposition, + BlueprintDatasetsConfigDiff, BlueprintDiff, BlueprintMetadata, + BlueprintPhysicalDiskConfig, BlueprintPhysicalDisksConfigDiff, + BlueprintZoneConfigDiff, BlueprintZonesConfigDiff, ClickhouseClusterConfig, + CockroachDbPreserveDowngrade, unwrap_or_none, zone_sort_key, }; use daft::Diffable; use nexus_sled_agent_shared::inventory::ZoneKind; @@ -2025,11 +2024,7 @@ impl fmt::Display for BlueprintDiffDisplay<'_> { } fn display_none_if_empty(value: &str) -> &str { - if value.is_empty() { - NONE_PARENS - } else { - value - } + if value.is_empty() { NONE_PARENS } else { value } } fn display_optional_preserve_downgrade( diff --git a/nexus/types/src/deployment/execution/dns.rs b/nexus/types/src/deployment/execution/dns.rs index 764a320c086..7f7f9c79971 100644 --- a/nexus/types/src/deployment/execution/dns.rs +++ b/nexus/types/src/deployment/execution/dns.rs @@ -13,14 +13,14 @@ use omicron_uuid_kinds::SledUuid; use crate::{ deployment::{ - blueprint_zone_type, Blueprint, BlueprintZoneDisposition, - BlueprintZoneType, + Blueprint, BlueprintZoneDisposition, BlueprintZoneType, + blueprint_zone_type, }, internal_api::params::{DnsConfigZone, DnsRecord}, silo::{default_silo_name, silo_dns_name}, }; -use super::{blueprint_nexus_external_ips, Overridables, Sled}; +use super::{Overridables, Sled, blueprint_nexus_external_ips}; /// Returns the expected contents of internal DNS based on the given blueprint pub fn blueprint_internal_dns_config( diff --git a/nexus/types/src/deployment/execution/overridables.rs b/nexus/types/src/deployment/execution/overridables.rs index bc7b28a63a2..9c35622547a 100644 --- a/nexus/types/src/deployment/execution/overridables.rs +++ b/nexus/types/src/deployment/execution/overridables.rs @@ -2,12 +2,12 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use omicron_common::address::get_switch_zone_address; -use omicron_common::address::Ipv6Subnet; use omicron_common::address::DENDRITE_PORT; +use omicron_common::address::Ipv6Subnet; use omicron_common::address::MGD_PORT; use omicron_common::address::MGS_PORT; use omicron_common::address::SLED_PREFIX; +use omicron_common::address::get_switch_zone_address; use omicron_uuid_kinds::SledUuid; use std::collections::BTreeMap; use std::net::Ipv6Addr; diff --git a/nexus/types/src/deployment/execution/utils.rs b/nexus/types/src/deployment/execution/utils.rs index bae09b9b2e2..bd5a4d5de01 100644 --- a/nexus/types/src/deployment/execution/utils.rs +++ b/nexus/types/src/deployment/execution/utils.rs @@ -9,7 +9,7 @@ use omicron_common::address::{Ipv6Subnet, SLED_PREFIX}; use omicron_uuid_kinds::SledUuid; use crate::deployment::{ - blueprint_zone_type, Blueprint, BlueprintZoneDisposition, BlueprintZoneType, + Blueprint, BlueprintZoneDisposition, BlueprintZoneType, blueprint_zone_type, }; /// The minimal information needed to represent a sled in the context of diff --git a/nexus/types/src/deployment/id_map.rs b/nexus/types/src/deployment/id_map.rs index 178ad71b5ed..ee5d85c4054 100644 --- a/nexus/types/src/deployment/id_map.rs +++ b/nexus/types/src/deployment/id_map.rs @@ -6,12 +6,12 @@ use daft::BTreeMapDiff; use daft::Diffable; use derive_where::derive_where; use schemars::JsonSchema; -use serde::de::Error as _; -use serde::de::Visitor; use serde::Deserialize; use serde::Serialize; -use std::collections::btree_map; +use serde::de::Error as _; +use serde::de::Visitor; use std::collections::BTreeMap; +use std::collections::btree_map; use std::fmt; use std::fmt::Debug; use std::marker::PhantomData; @@ -391,8 +391,8 @@ impl<'a, T: IdMappable> OccupiedEntry<'a, T> { mod tests { use super::*; use daft::Diffable; - use test_strategy::proptest; use test_strategy::Arbitrary; + use test_strategy::proptest; #[derive( Debug, diff --git a/nexus/types/src/deployment/network_resources.rs b/nexus/types/src/deployment/network_resources.rs index e5ac1003da5..fdd2f3cee87 100644 --- a/nexus/types/src/deployment/network_resources.rs +++ b/nexus/types/src/deployment/network_resources.rs @@ -351,14 +351,18 @@ impl TriMapEntry for OmicronZoneNicEntry { #[derive(Debug, Error)] pub enum AddNetworkResourceError { - #[error("associating Omicron zone {zone_id} with {ip:?} failed due to duplicates")] + #[error( + "associating Omicron zone {zone_id} with {ip:?} failed due to duplicates" + )] DuplicateOmicronZoneExternalIp { zone_id: OmicronZoneUuid, ip: OmicronZoneExternalIp, #[source] err: anyhow::Error, }, - #[error("associating Omicron zone {zone_id} with {nic:?} failed due to duplicates")] + #[error( + "associating Omicron zone {zone_id} with {nic:?} failed due to duplicates" + )] DuplicateOmicronZoneNic { zone_id: OmicronZoneUuid, nic: OmicronZoneNic, diff --git a/nexus/types/src/deployment/planning_input.rs b/nexus/types/src/deployment/planning_input.rs index 19ab6560059..7e39ff8d99d 100644 --- a/nexus/types/src/deployment/planning_input.rs +++ b/nexus/types/src/deployment/planning_input.rs @@ -33,8 +33,8 @@ use omicron_uuid_kinds::ZpoolUuid; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::error; use std::fmt; use strum::IntoEnumIterator; @@ -976,7 +976,9 @@ pub struct SledDetails { pub enum PlanningInputBuildError { #[error("duplicate sled ID: {0}")] DuplicateSledId(SledUuid), - #[error("Omicron zone {zone_id} has a range of IPs ({ip:?}), only a single IP is supported")] + #[error( + "Omicron zone {zone_id} has a range of IPs ({ip:?}), only a single IP is supported" + )] NotSingleIp { zone_id: OmicronZoneUuid, ip: IpNetwork }, #[error(transparent)] AddNetworkResource(#[from] AddNetworkResourceError), diff --git a/nexus/types/src/deployment/tri_map.rs b/nexus/types/src/deployment/tri_map.rs index f5432759f11..7b9575325d1 100644 --- a/nexus/types/src/deployment/tri_map.rs +++ b/nexus/types/src/deployment/tri_map.rs @@ -4,7 +4,7 @@ use std::{ borrow::Borrow, - collections::{hash_map, BTreeSet, HashMap}, + collections::{BTreeSet, HashMap, hash_map}, fmt, hash::Hash, }; @@ -169,7 +169,7 @@ impl TriMap { /// an explicit check for tests. #[cfg(test)] fn validate(&self) -> anyhow::Result<()> { - use anyhow::{ensure, Context}; + use anyhow::{Context, ensure}; // Check that all the maps are of the right size. ensure!( @@ -324,7 +324,7 @@ mod tests { use super::*; use prop::sample::SizeRange; use proptest::prelude::*; - use test_strategy::{proptest, Arbitrary}; + use test_strategy::{Arbitrary, proptest}; #[derive( Clone, Debug, Eq, PartialEq, Arbitrary, Serialize, Deserialize, @@ -518,7 +518,9 @@ mod tests { ) } (None, Err(error)) => { - panic!("unexpected error: {error}, deserialization should have succeeded") + panic!( + "unexpected error: {error}, deserialization should have succeeded" + ) } (Some(first_error), Err(error)) => { // first_error is the error from the map, and error is the diff --git a/nexus/types/src/external_api/params.rs b/nexus/types/src/external_api/params.rs index e87acd4e590..bba10ab38b0 100644 --- a/nexus/types/src/external_api/params.rs +++ b/nexus/types/src/external_api/params.rs @@ -21,8 +21,8 @@ use oxnet::{IpNet, Ipv4Net, Ipv6Net}; use parse_display::Display; use schemars::JsonSchema; use serde::{ - de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer, + de::{self, Visitor}, }; use std::collections::BTreeMap; use std::collections::BTreeSet; diff --git a/nexus/types/src/external_api/shared.rs b/nexus/types/src/external_api/shared.rs index ae8214a637c..6d344cb6afe 100644 --- a/nexus/types/src/external_api/shared.rs +++ b/nexus/types/src/external_api/shared.rs @@ -15,10 +15,10 @@ use omicron_common::api::internal::shared::NetworkInterface; use omicron_uuid_kinds::SupportBundleUuid; use parse_display::FromStr; use schemars::JsonSchema; -use serde::de::Error as _; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; +use serde::de::Error as _; use strum::EnumIter; use uuid::Uuid; @@ -376,8 +376,8 @@ impl JsonSchema for SwitchLinkState { #[cfg(test)] mod test { - use super::Policy; use super::MAX_ROLE_ASSIGNMENTS_PER_RESOURCE; + use super::Policy; use serde::Deserialize; #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] diff --git a/oximeter/collector/src/agent.rs b/oximeter/collector/src/agent.rs index cb1eccc5213..8db08479b2e 100644 --- a/oximeter/collector/src/agent.rs +++ b/oximeter/collector/src/agent.rs @@ -6,20 +6,20 @@ // Copyright 2024 Oxide Computer Company +use crate::DbConfig; +use crate::Error; +use crate::ProducerEndpoint; use crate::collection_task::CollectionTaskHandle; use crate::collection_task::CollectionTaskOutput; use crate::collection_task::ForcedCollectionError; use crate::results_sink; use crate::self_stats; -use crate::DbConfig; -use crate::Error; -use crate::ProducerEndpoint; use anyhow::anyhow; use chrono::DateTime; use chrono::Utc; use futures::TryStreamExt; -use nexus_client::types::IdSortMode; use nexus_client::Client as NexusClient; +use nexus_client::types::IdSortMode; use omicron_common::backoff; use omicron_common::backoff::BackoffError; use oximeter_api::ProducerDetails; @@ -28,24 +28,24 @@ use oximeter_db::DbWrite; use qorb::claim::Handle; use qorb::pool::Pool; use qorb::resolver::BoxedResolver; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; use slog::trace; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::net::SocketAddrV6; use std::ops::Bound; use std::sync::Arc; use std::sync::Mutex as StdMutex; use std::time::Duration; -use tokio::sync::mpsc; use tokio::sync::Mutex; use tokio::sync::MutexGuard; +use tokio::sync::mpsc; use uuid::Uuid; /// The internal agent the oximeter server uses to collect metrics from producers. @@ -599,9 +599,9 @@ mod tests { use std::net::Ipv6Addr; use std::net::SocketAddr; use std::net::SocketAddrV6; + use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; - use std::sync::Arc; use std::time::Duration; use tokio::time::Instant; use uuid::Uuid; diff --git a/oximeter/collector/src/bin/clickhouse-schema-updater.rs b/oximeter/collector/src/bin/clickhouse-schema-updater.rs index 847baa04ebf..567eee09a77 100644 --- a/oximeter/collector/src/bin/clickhouse-schema-updater.rs +++ b/oximeter/collector/src/bin/clickhouse-schema-updater.rs @@ -6,8 +6,8 @@ // Copyright 2023 Oxide Computer Company -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use camino::Utf8PathBuf; use clap::Parser; use clap::Subcommand; diff --git a/oximeter/collector/src/bin/oximeter.rs b/oximeter/collector/src/bin/oximeter.rs index 16be3b69e22..c5bb8fa6d05 100644 --- a/oximeter/collector/src/bin/oximeter.rs +++ b/oximeter/collector/src/bin/oximeter.rs @@ -6,15 +6,15 @@ // Copyright 2023 Oxide Computer Company -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use clap::Parser; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; -use oximeter_collector::standalone_nexus_api; +use omicron_common::cmd::fatal; use oximeter_collector::Config; use oximeter_collector::Oximeter; use oximeter_collector::OximeterArguments; use oximeter_collector::StandaloneNexus; +use oximeter_collector::standalone_nexus_api; use slog::Level; use std::net::Ipv6Addr; use std::net::SocketAddr; diff --git a/oximeter/collector/src/collection_task.rs b/oximeter/collector/src/collection_task.rs index 716f87421f7..8c34992d55a 100644 --- a/oximeter/collector/src/collection_task.rs +++ b/oximeter/collector/src/collection_task.rs @@ -6,8 +6,8 @@ // Copyright 2024 Oxide Computer Company -use crate::self_stats; use crate::Error; +use crate::self_stats; use chrono::DateTime; use chrono::Utc; use omicron_common::api::internal::nexus::ProducerEndpoint; @@ -16,21 +16,21 @@ use oximeter::types::ProducerResultsItem; use oximeter_api::FailedCollection; use oximeter_api::ProducerDetails; use oximeter_api::SuccessfulCollection; +use slog::Logger; use slog::debug; use slog::error; use slog::o; use slog::trace; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; use std::time::Duration; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; use tokio::sync::oneshot; use tokio::sync::watch; -use tokio::time::interval; use tokio::time::Instant; use tokio::time::Interval; +use tokio::time::interval; /// A token used to force a collection. /// diff --git a/oximeter/collector/src/lib.rs b/oximeter/collector/src/lib.rs index 54044b0068a..92349f00815 100644 --- a/oximeter/collector/src/lib.rs +++ b/oximeter/collector/src/lib.rs @@ -13,11 +13,11 @@ use dropshot::HttpError; use dropshot::HttpServer; use dropshot::ServerBuilder; use internal_dns_types::names::ServiceName; -use omicron_common::address::get_internal_dns_server_addresses; +use omicron_common::FileKv; use omicron_common::address::DNS_PORT; +use omicron_common::address::get_internal_dns_server_addresses; use omicron_common::api::internal::nexus::ProducerEndpoint; use omicron_common::backoff; -use omicron_common::FileKv; use qorb::backend; use qorb::resolver::BoxedResolver; use qorb::resolvers::dns::DnsResolver; @@ -26,13 +26,13 @@ use qorb::resolvers::single_host::SingleHostResolver; use qorb::service; use serde::Deserialize; use serde::Serialize; +use slog::Drain; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; use slog::warn; -use slog::Drain; -use slog::Logger; use std::net::SocketAddr; use std::net::SocketAddrV6; use std::path::Path; @@ -50,8 +50,8 @@ mod standalone; pub use agent::OximeterAgent; pub use http_entrypoints::oximeter_api; -pub use standalone::standalone_nexus_api; pub use standalone::Server as StandaloneNexus; +pub use standalone::standalone_nexus_api; /// Errors collecting metric data #[derive(Debug, Error)] diff --git a/oximeter/collector/src/results_sink.rs b/oximeter/collector/src/results_sink.rs index 3013d472b6d..13ddcdc9360 100644 --- a/oximeter/collector/src/results_sink.rs +++ b/oximeter/collector/src/results_sink.rs @@ -13,12 +13,12 @@ use crate::collection_task::CollectionTaskOutput; use oximeter::types::ProducerResultsItem; use oximeter_db::Client; use oximeter_db::DbWrite as _; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::trace; use slog::warn; -use slog::Logger; use slog_error_chain::InlineErrorChain; use std::time::Duration; use tokio::sync::mpsc; diff --git a/oximeter/collector/src/self_stats.rs b/oximeter/collector/src/self_stats.rs index ff8776c0313..2d85185534d 100644 --- a/oximeter/collector/src/self_stats.rs +++ b/oximeter/collector/src/self_stats.rs @@ -7,10 +7,10 @@ // Copyright 2023 Oxide Computer Company use crate::ProducerEndpoint; -use oximeter::types::Cumulative; -use oximeter::types::ProducerResultsItem; use oximeter::MetricsError; use oximeter::Sample; +use oximeter::types::Cumulative; +use oximeter::types::ProducerResultsItem; use reqwest::StatusCode; use std::borrow::Cow; use std::collections::BTreeMap; diff --git a/oximeter/collector/src/standalone.rs b/oximeter/collector/src/standalone.rs index d70bfef9e0e..954d9904fca 100644 --- a/oximeter/collector/src/standalone.rs +++ b/oximeter/collector/src/standalone.rs @@ -8,7 +8,6 @@ // Copyright 2024 Oxide Computer Company use crate::Error; -use dropshot::endpoint; use dropshot::ApiDescription; use dropshot::ConfigDropshot; use dropshot::HttpError; @@ -18,18 +17,19 @@ use dropshot::HttpServer; use dropshot::RequestContext; use dropshot::ServerBuilder; use dropshot::TypedBody; +use dropshot::endpoint; use nexus_types::internal_api::params::OximeterInfo; +use omicron_common::FileKv; use omicron_common::api::internal::nexus::ProducerEndpoint; use omicron_common::api::internal::nexus::ProducerRegistrationResponse; -use omicron_common::FileKv; use rand::seq::IteratorRandom; +use slog::Drain; +use slog::Level; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; -use slog::Drain; -use slog::Level; -use slog::Logger; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::Arc; diff --git a/oximeter/collector/tests/test_commands.rs b/oximeter/collector/tests/test_commands.rs index 3a772d736c4..9b0cf021b01 100644 --- a/oximeter/collector/tests/test_commands.rs +++ b/oximeter/collector/tests/test_commands.rs @@ -8,7 +8,7 @@ use std::path::PathBuf; use expectorate::assert_contents; use omicron_test_utils::dev::test_cmds::{ - assert_exit_code, path_to_executable, run_command, EXIT_USAGE, + EXIT_USAGE, assert_exit_code, path_to_executable, run_command, }; use subprocess::Exec; diff --git a/oximeter/db/src/bin/oxdb/main.rs b/oximeter/db/src/bin/oxdb/main.rs index f5701c0ef1a..7a9fe9f8e15 100644 --- a/oximeter/db/src/bin/oxdb/main.rs +++ b/oximeter/db/src/bin/oxdb/main.rs @@ -7,16 +7,16 @@ // Copyright 2024 Oxide Computer Company -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use chrono::{DateTime, Utc}; use clap::{Args, Parser}; use omicron_common::address::CLICKHOUSE_TCP_PORT; use oximeter::{ - types::{Cumulative, Sample}, Metric, Target, + types::{Cumulative, Sample}, }; -use oximeter_db::{make_client, query, Client, DbWrite}; -use slog::{debug, info, o, Drain, Level, Logger}; +use oximeter_db::{Client, DbWrite, make_client, query}; +use slog::{Drain, Level, Logger, debug, info, o}; use std::net::IpAddr; use uuid::Uuid; diff --git a/oximeter/db/src/client/dbwrite.rs b/oximeter/db/src/client/dbwrite.rs index 69974df26e0..57a84ca7936 100644 --- a/oximeter/db/src/client/dbwrite.rs +++ b/oximeter/db/src/client/dbwrite.rs @@ -6,18 +6,18 @@ // Copyright 2024 Oxide Computer Company +use crate::Error; use crate::client::Client; use crate::model; use crate::model::to_block::ToBlock as _; use crate::native::block::Block; -use crate::Error; use camino::Utf8PathBuf; use oximeter::Sample; use oximeter::TimeseriesSchema; use slog::debug; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; #[derive(Debug)] pub(super) struct UnrolledSampleRows { diff --git a/oximeter/db/src/client/mod.rs b/oximeter/db/src/client/mod.rs index bc52d446fb8..4c3e7d8dee9 100644 --- a/oximeter/db/src/client/mod.rs +++ b/oximeter/db/src/client/mod.rs @@ -15,46 +15,46 @@ mod sql; pub use self::dbwrite::DbWrite; pub use self::dbwrite::TestDbWrite; +use crate::Error; +use crate::Metric; +use crate::Target; +use crate::Timeseries; +use crate::TimeseriesPageSelector; +use crate::TimeseriesScanParams; +use crate::TimeseriesSchema; use crate::client::query_summary::QuerySummary; use crate::model::columns; use crate::model::fields::FieldSelectRow; use crate::model::from_block::FromBlock; use crate::native; +use crate::native::QueryResult; use crate::native::block::Block; use crate::native::block::ValueArray; -use crate::native::QueryResult; use crate::query; -use crate::Error; -use crate::Metric; -use crate::Target; -use crate::Timeseries; -use crate::TimeseriesPageSelector; -use crate::TimeseriesScanParams; -use crate::TimeseriesSchema; use debug_ignore::DebugIgnore; use dropshot::EmptyScanParams; use dropshot::PaginationOrder; use dropshot::ResultsPage; use dropshot::WhichPage; use omicron_common::backoff; -use oximeter::schema::TimeseriesKey; -use oximeter::types::Sample; use oximeter::Measurement; use oximeter::TimeseriesName; +use oximeter::schema::TimeseriesKey; +use oximeter::types::Sample; use qorb::pool::Pool; use qorb::resolver::BoxedResolver; use qorb::resolvers::single_host::SingleHostResolver; use regex::Regex; use regex::RegexBuilder; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::trace; use slog::warn; -use slog::Logger; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; use std::convert::TryFrom; use std::io::ErrorKind; use std::net::SocketAddr; @@ -1375,13 +1375,13 @@ mod tests { use native::block::Column; use omicron_test_utils::dev::clickhouse::ClickHouseDeployment; use omicron_test_utils::dev::test_setup_log; - use oximeter::histogram::Histogram; - use oximeter::types::MissingDatum; use oximeter::Datum; use oximeter::FieldValue; use oximeter::Measurement; use oximeter::Metric; use oximeter::Target; + use oximeter::histogram::Histogram; + use oximeter::types::MissingDatum; use std::net::Ipv6Addr; use std::path::PathBuf; use std::pin::Pin; @@ -1542,20 +1542,24 @@ mod tests { ), ( "test_field_record_count_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_field_record_count_impl(db, client)) }), ), ( "test_differentiate_by_timeseries_name_replicated", Box::new(move |db, client| { - Box::pin(test_differentiate_by_timeseries_name_impl(db, client)) + Box::pin(test_differentiate_by_timeseries_name_impl( + db, client, + )) }), ), ( "test_select_timeseries_with_select_one_replicated", - Box::new(move |db, client|{ - Box::pin(test_select_timeseries_with_select_one_impl(db, client)) + Box::new(move |db, client| { + Box::pin(test_select_timeseries_with_select_one_impl( + db, client, + )) }), ), ( @@ -1572,43 +1576,45 @@ mod tests { ), ( "test_select_timeseries_with_all_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_select_timeseries_with_all_impl(db, client)) }), ), ( "test_select_timeseries_with_start_time_replicated", - Box::new(move |db, client|{ - Box::pin(test_select_timeseries_with_start_time_impl(db, client)) + Box::new(move |db, client| { + Box::pin(test_select_timeseries_with_start_time_impl( + db, client, + )) }), ), ( "test_select_timeseries_with_limit_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_select_timeseries_with_limit_impl(db, client)) }), ), ( "test_select_timeseries_with_order_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_select_timeseries_with_order_impl(db, client)) }), ), ( "test_get_schema_no_new_values_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_get_schema_no_new_values_impl(db, client)) }), ), ( "test_timeseries_schema_list_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_timeseries_schema_list_impl(db, client)) }), ), ( "test_list_timeseries_replicated", - Box::new(move |db, client|{ + Box::new(move |db, client| { Box::pin(test_list_timeseries_impl(db, client)) }), ), @@ -1621,25 +1627,33 @@ mod tests { ( "test_database_version_update_idempotent_replicated", Box::new(move |db, client| { - Box::pin(test_database_version_update_is_idempotent_impl(db, client)) + Box::pin(test_database_version_update_is_idempotent_impl( + db, client, + )) }), ), ( "test_database_version_will_not_downgrade_replicated", Box::new(move |db, client| { - Box::pin(test_database_version_will_not_downgrade_impl(db, client)) + Box::pin(test_database_version_will_not_downgrade_impl( + db, client, + )) }), ), ( "test_database_version_will_not_upgrade_replicated", Box::new(move |db, client| { - Box::pin(test_database_version_will_not_upgrade_impl(db, client)) + Box::pin(test_database_version_will_not_upgrade_impl( + db, client, + )) }), ), ( "test_update_schema_cache_on_new_sample_replicated", Box::new(move |db, client| { - Box::pin(test_update_schema_cache_on_new_sample_impl(db, client)) + Box::pin(test_update_schema_cache_on_new_sample_impl( + db, client, + )) }), ), ( @@ -1651,7 +1665,9 @@ mod tests { ( "test_new_schema_removed_when_not_inserted_replicated", Box::new(move |db, client| { - Box::pin(test_new_schema_removed_when_not_inserted_impl(db, client)) + Box::pin(test_new_schema_removed_when_not_inserted_impl( + db, client, + )) }), ), ( @@ -1827,9 +1843,9 @@ mod tests { let result = client.verify_or_cache_sample_schema(&sample).await.unwrap(); assert!( - matches!(result, Some(_)), - "When verifying a new sample, the rows to be inserted should be returned" - ); + matches!(result, Some(_)), + "When verifying a new sample, the rows to be inserted should be returned" + ); // Clear the internal caches of seen schema client.schema.lock().await.clear(); @@ -1851,10 +1867,9 @@ mod tests { ) .clone(); assert_eq!( - actual_schema, - expected_schema, - "The timeseries schema for a new sample was not correctly inserted into internal cache", - ); + actual_schema, expected_schema, + "The timeseries schema for a new sample was not correctly inserted into internal cache", + ); // This should no longer return a new row to be inserted for the schema of this sample, as // any schema have been included above. @@ -1947,9 +1962,11 @@ mod tests { let expected_measurements = samples.iter().map(|sample| &sample.measurement); let actual_measurements = timeseries.measurements.iter(); - assert!(actual_measurements - .zip(expected_measurements) - .all(|(first, second)| first == second)); + assert!( + actual_measurements + .zip(expected_measurements) + .all(|(first, second)| first == second) + ); assert_eq!(timeseries.target.name, "virtual_machine"); // Compare fields, but order might be different. fn field_cmp<'a>( @@ -2243,10 +2260,11 @@ mod tests { } #[tokio::test] - async fn test_select_timeseries_with_select_multiple_fields_with_multiple_values( - ) { - let logctx = - test_setup_log("test_select_timeseries_with_select_multiple_fields_with_multiple_values"); + async fn test_select_timeseries_with_select_multiple_fields_with_multiple_values() + { + let logctx = test_setup_log( + "test_select_timeseries_with_select_multiple_fields_with_multiple_values", + ); let mut db = ClickHouseDeployment::new_single_node(&logctx).await.unwrap(); let client = Client::new(db.native_address().into(), &logctx.log); @@ -2889,7 +2907,7 @@ mod tests { ( "timeseries_name".to_string(), Column::from(ValueArray::String(vec![ - TIMESERIES_NAME.to_string() + TIMESERIES_NAME.to_string(), ])), ), ( @@ -2899,7 +2917,7 @@ mod tests { ( "field_name".to_string(), Column::from(ValueArray::String(vec![ - FIELD_NAME.to_string() + FIELD_NAME.to_string(), ])), ), ("field_value".to_string(), Column::from(values)), diff --git a/oximeter/db/src/client/oxql.rs b/oximeter/db/src/client/oxql.rs index fe10f1e961a..cc859fdc132 100644 --- a/oximeter/db/src/client/oxql.rs +++ b/oximeter/db/src/client/oxql.rs @@ -7,25 +7,25 @@ // Copyright 2024 Oxide Computer Company use super::query_summary::QuerySummary; +use crate::Error; +use crate::Metric; +use crate::Target; use crate::client::Client; use crate::model::columns; use crate::model::from_block::FromBlock as _; use crate::oxql; +use crate::oxql::Query; use crate::oxql::ast::table_ops::filter; use crate::oxql::ast::table_ops::filter::Filter; use crate::oxql::ast::table_ops::limit::Limit; use crate::oxql::ast::table_ops::limit::LimitKind; -use crate::oxql::Query; use crate::query::field_table_name; -use crate::Error; -use crate::Metric; -use crate::Target; -use oximeter::schema::TimeseriesKey; use oximeter::Measurement; use oximeter::TimeseriesSchema; +use oximeter::schema::TimeseriesKey; +use slog::Logger; use slog::debug; use slog::trace; -use slog::Logger; use std::collections::BTreeMap; use std::time::Duration; use std::time::Instant; @@ -962,7 +962,7 @@ impl Client { db_name = crate::DATABASE_NAME, field_table = field_table_name(field_schema.field_type), timeseries_name = schema.timeseries_name, - ) + ), ) } _ => { @@ -1177,18 +1177,18 @@ mod tests { use super::ConsistentKeyGroup; use crate::client::oxql::chunk_consistent_key_groups_impl; use crate::oxql::ast::grammar::query_parser; - use crate::{Client, DbWrite, DATABASE_TIMESTAMP_FORMAT}; + use crate::{Client, DATABASE_TIMESTAMP_FORMAT, DbWrite}; use crate::{Metric, Target}; use chrono::{DateTime, NaiveDate, Utc}; use dropshot::test_util::LogContext; use omicron_test_utils::dev::clickhouse::ClickHouseDeployment; use omicron_test_utils::dev::test_setup_log; - use oximeter::{types::Cumulative, FieldValue}; use oximeter::{ AuthzScope, DatumType, FieldSchema, FieldSource, FieldType, Sample, TimeseriesSchema, Units, }; - use oxql_types::{point::Points, Table, Timeseries}; + use oximeter::{FieldValue, types::Cumulative}; + use oxql_types::{Table, Timeseries, point::Points}; use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; @@ -1440,17 +1440,14 @@ mod tests { let mut it = ctx.test_data.samples_by_timeseries.iter(); let (entire, only_part) = (it.next().unwrap(), it.next().unwrap()); - let entire_filter = exact_filter_for(&entire.0 .0, entire.0 .1); - let only_part_filter = - exact_filter_for(&only_part.0 .0, only_part.0 .1); + let entire_filter = exact_filter_for(&entire.0.0, entire.0.1); + let only_part_filter = exact_filter_for(&only_part.0.0, only_part.0.1); let start_timestamp = only_part.1[6].measurement.timestamp(); let only_part_timestamp_filter = format_timestamp(start_timestamp); let query = format!( "get some_target:some_metric | filter ({}) || (timestamp >= @{} && {})", - entire_filter, - only_part_timestamp_filter, - only_part_filter, + entire_filter, only_part_timestamp_filter, only_part_filter, ); let result = ctx .client @@ -1467,7 +1464,7 @@ mod tests { // Check that we fetched the entire timeseries for the first one. let expected_timeseries = - find_timeseries_in_table(table, &entire.0 .0, &entire.0 .1) + find_timeseries_in_table(table, &entire.0.0, &entire.0.1) .expect("failed to fetch all of the first timeseries"); let measurements: Vec<_> = entire.1.iter().map(|s| s.measurement.clone()).collect(); @@ -1480,7 +1477,7 @@ mod tests { // And that we only get the last portion of the second timeseries. let expected_timeseries = - find_timeseries_in_table(table, &only_part.0 .0, &only_part.0 .1) + find_timeseries_in_table(table, &only_part.0.0, &only_part.0.1) .expect("failed to fetch part of the second timeseries"); let measurements: Vec<_> = only_part .1 diff --git a/oximeter/db/src/client/sql.rs b/oximeter/db/src/client/sql.rs index 6b7a78981c4..23dc2388c31 100644 --- a/oximeter/db/src/client/sql.rs +++ b/oximeter/db/src/client/sql.rs @@ -18,11 +18,11 @@ // Copyright 2024 Oxide Computer Company +use crate::Error; use crate::client::Client; use crate::sql::QueryResult; pub use crate::sql::RestrictedQuery; use crate::sql::Table; -use crate::Error; use slog::debug; impl Client { diff --git a/oximeter/db/src/lib.rs b/oximeter/db/src/lib.rs index 6479cc6b551..7afbf6e9bb6 100644 --- a/oximeter/db/src/lib.rs +++ b/oximeter/db/src/lib.rs @@ -10,16 +10,16 @@ use crate::query::StringFieldSelector; use anyhow::Context as _; use chrono::DateTime; use chrono::Utc; -pub use oximeter::schema::FieldSchema; -pub use oximeter::schema::FieldSource; -use oximeter::schema::TimeseriesKey; -pub use oximeter::schema::TimeseriesName; -pub use oximeter::schema::TimeseriesSchema; pub use oximeter::DatumType; pub use oximeter::Field; pub use oximeter::FieldType; pub use oximeter::Measurement; pub use oximeter::Sample; +pub use oximeter::schema::FieldSchema; +pub use oximeter::schema::FieldSource; +use oximeter::schema::TimeseriesKey; +pub use oximeter::schema::TimeseriesName; +pub use oximeter::schema::TimeseriesSchema; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -47,12 +47,12 @@ pub mod shells; #[cfg(any(feature = "sql", test))] pub mod sql; -#[cfg(any(feature = "oxql", test))] -pub use client::oxql::OxqlResult; -pub use client::query_summary::QuerySummary; pub use client::Client; pub use client::DbWrite; pub use client::TestDbWrite; +#[cfg(any(feature = "oxql", test))] +pub use client::oxql::OxqlResult; +pub use client::query_summary::QuerySummary; pub use model::OXIMETER_VERSION; #[derive(Debug, Error)] @@ -87,13 +87,19 @@ pub enum Error { #[error("Timeseries not found for: {0}")] TimeseriesNotFound(String), - #[error("The field comparison operation '{op}' is not valid for field '{field_name}' with type {field_type}")] + #[error( + "The field comparison operation '{op}' is not valid for field '{field_name}' with type {field_type}" + )] InvalidSelectionOp { op: String, field_name: String, field_type: FieldType }, - #[error("Timeseries '{timeseries_name}' does not contain a field with name '{field_name}'")] + #[error( + "Timeseries '{timeseries_name}' does not contain a field with name '{field_name}'" + )] NoSuchField { timeseries_name: String, field_name: String }, - #[error("Field '{field_name}' requires a value of type {expected_type}, found {found_type}")] + #[error( + "Field '{field_name}' requires a value of type {expected_type}, found {found_type}" + )] IncorrectFieldType { field_name: String, expected_type: FieldType, @@ -108,7 +114,9 @@ pub enum Error { )] InvalidFieldSelectorString { selector: String }, - #[error("Invalid value for field '{field_name}' with type {field_type}: '{value}'")] + #[error( + "Invalid value for field '{field_name}' with type {field_type}: '{value}'" + )] InvalidFieldValue { field_name: String, field_type: FieldType, diff --git a/oximeter/db/src/model/fields.rs b/oximeter/db/src/model/fields.rs index 7c70beaf90a..2f3a6c982b4 100644 --- a/oximeter/db/src/model/fields.rs +++ b/oximeter/db/src/model/fields.rs @@ -8,16 +8,15 @@ use super::columns; use super::from_block::FromBlock; +use crate::Metric; +use crate::Target; +use crate::native::Error; use crate::native::block::Block; use crate::native::block::Column; use crate::native::block::DataType; use crate::native::block::ValueArray; -use crate::native::Error; use crate::query::field_table_name; -use crate::Metric; -use crate::Target; use indexmap::IndexMap; -use oximeter::schema::TimeseriesKey; use oximeter::Field; use oximeter::FieldSchema; use oximeter::FieldSource; @@ -25,6 +24,7 @@ use oximeter::FieldType; use oximeter::FieldValue; use oximeter::Sample; use oximeter::TimeseriesSchema; +use oximeter::schema::TimeseriesKey; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::net::IpAddr; diff --git a/oximeter/db/src/model/from_block.rs b/oximeter/db/src/model/from_block.rs index cff41c4c6ac..97609848c2c 100644 --- a/oximeter/db/src/model/from_block.rs +++ b/oximeter/db/src/model/from_block.rs @@ -7,16 +7,13 @@ //! Trait for deserializing an array of values from a `Block`. use super::columns; +use crate::native::Error; use crate::native::block::Block; use crate::native::block::DataType; use crate::native::block::ValueArray; -use crate::native::Error; use chrono::DateTime; use chrono::TimeZone as _; use chrono_tz::Tz; -use oximeter::histogram::Histogram; -use oximeter::types::Cumulative; -use oximeter::types::MissingDatum; use oximeter::AuthzScope; use oximeter::Datum; use oximeter::DatumType; @@ -26,6 +23,9 @@ use oximeter::Quantile; use oximeter::TimeseriesDescription; use oximeter::TimeseriesSchema; use oximeter::Units; +use oximeter::histogram::Histogram; +use oximeter::types::Cumulative; +use oximeter::types::MissingDatum; use std::collections::BTreeSet; use std::num::NonZeroU8; diff --git a/oximeter/db/src/model/measurements.rs b/oximeter/db/src/model/measurements.rs index 2b0699b8430..4b938c53c2a 100644 --- a/oximeter/db/src/model/measurements.rs +++ b/oximeter/db/src/model/measurements.rs @@ -17,12 +17,12 @@ use crate::query::measurement_table_name; use chrono::TimeZone as _; use chrono_tz::Tz; use indexmap::IndexMap; -use oximeter::histogram::Histogram; -use oximeter::traits::HistogramSupport; -use oximeter::types::MissingDatum; use oximeter::Datum; use oximeter::DatumType; use oximeter::Sample; +use oximeter::histogram::Histogram; +use oximeter::traits::HistogramSupport; +use oximeter::types::MissingDatum; use strum::IntoEnumIterator as _; /// Extract the table name and a data block for a sample's measurement. @@ -46,25 +46,27 @@ pub(crate) fn extract_measurement_as_block_impl( measurement: &oximeter::Measurement, ) -> (String, Block) { // Construct the column arrays for those columns shared by all tables. - let mut columns = IndexMap::from([ - ( - String::from(columns::TIMESERIES_NAME), - Column::from(ValueArray::from(vec![timeseries_name])), - ), - ( - String::from(columns::TIMESERIES_KEY), - Column::from(ValueArray::from(vec![timeseries_key])), - ), - ( - String::from(columns::TIMESTAMP), - Column::from(ValueArray::DateTime64 { - precision: Precision::MAX, - tz: Tz::UTC, - values: vec![Tz::UTC - .from_utc_datetime(&measurement.timestamp().naive_utc())], - }), - ), - ]); + let mut columns = + IndexMap::from([ + ( + String::from(columns::TIMESERIES_NAME), + Column::from(ValueArray::from(vec![timeseries_name])), + ), + ( + String::from(columns::TIMESERIES_KEY), + Column::from(ValueArray::from(vec![timeseries_key])), + ), + ( + String::from(columns::TIMESTAMP), + Column::from(ValueArray::DateTime64 { + precision: Precision::MAX, + tz: Tz::UTC, + values: vec![Tz::UTC.from_utc_datetime( + &measurement.timestamp().naive_utc(), + )], + }), + ), + ]); // Insert an array of start times if needed. if let Some(start_time) = measurement.start_time() { @@ -73,7 +75,9 @@ pub(crate) fn extract_measurement_as_block_impl( Column::from(ValueArray::DateTime64 { precision: Precision::MAX, tz: Tz::UTC, - values: vec![Tz::UTC.from_utc_datetime(&start_time.naive_utc())], + values: vec![ + Tz::UTC.from_utc_datetime(&start_time.naive_utc()), + ], }), ); } @@ -497,11 +501,11 @@ mod tests { use crate::native::block::ValueArray; use bytes::Bytes; use indexmap::IndexMap; + use oximeter::Datum; + use oximeter::Sample; use oximeter::histogram::Histogram; use oximeter::histogram::Record as _; use oximeter::types::Cumulative; - use oximeter::Datum; - use oximeter::Sample; #[test] fn test_insert_datum_columns_scalar() { @@ -655,7 +659,9 @@ mod tests { .column_values(columns::TIMESTAMP) .expect("Should have a `timestamp` column"); let ValueArray::DateTime64 { values, .. } = col else { - panic!("Expected a DateTime64 column for the timestamps, found {col:#?}"); + panic!( + "Expected a DateTime64 column for the timestamps, found {col:#?}" + ); }; assert_eq!(values, &[sample.measurement.timestamp()]); @@ -720,7 +726,9 @@ mod tests { .column_values(columns::START_TIME) .expect("Should have a `start_time` column"); let ValueArray::DateTime64 { values, .. } = col else { - panic!("Expected a DateTime64 column for the start_time, found {col:#?}"); + panic!( + "Expected a DateTime64 column for the start_time, found {col:#?}" + ); }; assert_eq!(values, &[sample.measurement.start_time().unwrap()]); @@ -728,7 +736,9 @@ mod tests { .column_values(columns::TIMESTAMP) .expect("Should have a `timestamp` column"); let ValueArray::DateTime64 { values, .. } = col else { - panic!("Expected a DateTime64 column for the timestamps, found {col:#?}"); + panic!( + "Expected a DateTime64 column for the timestamps, found {col:#?}" + ); }; assert_eq!(values, &[sample.measurement.timestamp()]); @@ -736,10 +746,14 @@ mod tests { .column_values(columns::DATUM) .expect("Should have a `datum` column"); let ValueArray::Nullable { is_null, values } = col else { - panic!("Expected a Nullable(UInt64) column for the datum, found {col:#?}"); + panic!( + "Expected a Nullable(UInt64) column for the datum, found {col:#?}" + ); }; let ValueArray::UInt64(values) = &**values else { - panic!("Expected a Nullable(UInt64) column for the datum, found {values:#?}"); + panic!( + "Expected a Nullable(UInt64) column for the datum, found {values:#?}" + ); }; assert_eq!(is_null, &[false]); assert_eq!(values, &[1]); @@ -788,7 +802,9 @@ mod tests { .column_values(columns::START_TIME) .expect("Should have a `start_time` column"); let ValueArray::DateTime64 { values, .. } = col else { - panic!("Expected a DateTime64 column for the start_time, found {col:#?}"); + panic!( + "Expected a DateTime64 column for the start_time, found {col:#?}" + ); }; assert_eq!(values, &[sample.measurement.start_time().unwrap()]); @@ -796,7 +812,9 @@ mod tests { .column_values(columns::TIMESTAMP) .expect("Should have a `timestamp` column"); let ValueArray::DateTime64 { values, .. } = col else { - panic!("Expected a DateTime64 column for the timestamps, found {col:#?}"); + panic!( + "Expected a DateTime64 column for the timestamps, found {col:#?}" + ); }; assert_eq!(values, &[sample.measurement.timestamp()]); diff --git a/oximeter/db/src/model/to_block.rs b/oximeter/db/src/model/to_block.rs index 70f4307dec5..a4a52001c05 100644 --- a/oximeter/db/src/model/to_block.rs +++ b/oximeter/db/src/model/to_block.rs @@ -7,12 +7,12 @@ //! Trait for serializing an array of values into a `Block`. use super::columns; +use crate::native::Error; use crate::native::block::Block; use crate::native::block::Column; use crate::native::block::DataType; use crate::native::block::Precision; use crate::native::block::ValueArray; -use crate::native::Error; use chrono::TimeZone as _; use chrono_tz::Tz; use indexmap::IndexMap; diff --git a/oximeter/db/src/native/block.rs b/oximeter/db/src/native/block.rs index bd681003c2f..9677c9a4184 100644 --- a/oximeter/db/src/native/block.rs +++ b/oximeter/db/src/native/block.rs @@ -6,12 +6,13 @@ //! Types for working with actual blocks and columns of data. -use super::packets::server::ColumnDescription; use super::Error; +use super::packets::server::ColumnDescription; use chrono::DateTime; use chrono::NaiveDate; use chrono_tz::Tz; use indexmap::IndexMap; +use nom::IResult; use nom::branch::alt; use nom::bytes::complete::tag; use nom::bytes::complete::take_while1; @@ -29,7 +30,6 @@ use nom::sequence::delimited; use nom::sequence::preceded; use nom::sequence::separated_pair; use nom::sequence::tuple; -use nom::IResult; use oximeter::DatumType; use std::fmt; use std::net::IpAddr; @@ -731,11 +731,7 @@ impl Precision { pub const MAX: Self = Self(Self::MAX_U8); pub fn new(precision: u8) -> Option { - if precision <= Self::MAX_U8 { - Some(Self(precision)) - } else { - None - } + if precision <= Self::MAX_U8 { Some(Self(precision)) } else { None } } /// Return a conversion function that takes an i64 count and converts it to @@ -1167,14 +1163,14 @@ impl std::str::FromStr for DataType { #[cfg(test)] mod tests { - use super::enum8; use super::Block; use super::BlockInfo; use super::Column; + use super::DEFAULT_TIMEZONE; use super::DataType; use super::Precision; use super::ValueArray; - use super::DEFAULT_TIMEZONE; + use super::enum8; use crate::native::block::datetime; use crate::native::block::datetime64; use crate::native::block::enum_variant; diff --git a/oximeter/db/src/native/connection.rs b/oximeter/db/src/native/connection.rs index 48deea97a10..92cae455840 100644 --- a/oximeter/db/src/native/connection.rs +++ b/oximeter/db/src/native/connection.rs @@ -6,13 +6,14 @@ //! A connection and pool for talking to the ClickHouse server. +use super::Error; use super::block::Block; use super::io::packet::client::Encoder; use super::io::packet::server::Decoder; +use super::packets::client::OXIMETER_HELLO; use super::packets::client::Packet as ClientPacket; use super::packets::client::Query; use super::packets::client::QueryResult; -use super::packets::client::OXIMETER_HELLO; use super::packets::client::VERSION_MAJOR; use super::packets::client::VERSION_MINOR; use super::packets::client::VERSION_PATCH; @@ -20,16 +21,15 @@ use super::packets::server::Hello as ServerHello; use super::packets::server::Packet as ServerPacket; use super::packets::server::Progress; use super::packets::server::REVISION; -use super::Error; use crate::native::probes; use futures::SinkExt as _; use futures::StreamExt as _; use qorb::backend; use qorb::backend::Error as QorbError; use std::net::SocketAddr; +use tokio::net::TcpStream; use tokio::net::tcp::OwnedReadHalf; use tokio::net::tcp::OwnedWriteHalf; -use tokio::net::TcpStream; use tokio_util::codec::FramedRead; use tokio_util::codec::FramedWrite; use uuid::Uuid; @@ -382,7 +382,7 @@ impl Connection { } } ServerPacket::Exception(exceptions) => { - break Err(Error::Exception { exceptions }) + break Err(Error::Exception { exceptions }); } ServerPacket::Progress(progress) => { query_result.progress += progress @@ -415,8 +415,8 @@ mod tests { use omicron_test_utils::dev::clickhouse::ClickHouseDeployment; use omicron_test_utils::dev::test_setup_log; use std::sync::Arc; - use tokio::sync::oneshot; use tokio::sync::Mutex; + use tokio::sync::oneshot; #[tokio::test] async fn test_exchange_hello() { diff --git a/oximeter/db/src/native/io/block.rs b/oximeter/db/src/native/io/block.rs index ac76a5dbd17..f58d6acfb7f 100644 --- a/oximeter/db/src/native/io/block.rs +++ b/oximeter/db/src/native/io/block.rs @@ -6,10 +6,10 @@ //! Encoding and decoding data blocks. +use crate::native::Error; use crate::native::block::Block; use crate::native::block::BlockInfo; use crate::native::io; -use crate::native::Error; use bytes::Buf as _; use bytes::BufMut as _; use bytes::BytesMut; diff --git a/oximeter/db/src/native/io/column.rs b/oximeter/db/src/native/io/column.rs index bc952e0d311..aa55c2b8ad3 100644 --- a/oximeter/db/src/native/io/column.rs +++ b/oximeter/db/src/native/io/column.rs @@ -6,11 +6,11 @@ //! Encode / decode a column. +use crate::native::Error; use crate::native::block::Column; use crate::native::block::DataType; use crate::native::block::ValueArray; use crate::native::io; -use crate::native::Error; use bytes::Buf as _; use bytes::BufMut as _; use bytes::BytesMut; @@ -105,9 +105,7 @@ macro_rules! copyin_pod_values_raw { } macro_rules! copyin_pod_as_values { - ($data_type:ty, $src:expr, $n_rows:expr) => {{ - ValueArray::from(copyin_pod_values_raw!($data_type, $src, $n_rows)) - }}; + ($data_type:ty, $src:expr, $n_rows:expr) => {{ ValueArray::from(copyin_pod_values_raw!($data_type, $src, $n_rows)) }}; } /// Decode an array of values in a column. @@ -756,8 +754,7 @@ mod tests { }); assert_eq!(name, "foo"); assert_eq!( - col, - decoded, + col, decoded, "Failed encode/decode round-trip for column with type '{typ:?}'" ); } diff --git a/oximeter/db/src/native/io/exception.rs b/oximeter/db/src/native/io/exception.rs index 31c6ddd23cc..f9ae508d2bc 100644 --- a/oximeter/db/src/native/io/exception.rs +++ b/oximeter/db/src/native/io/exception.rs @@ -6,9 +6,9 @@ //! Decode server exception packets. +use crate::native::Error; use crate::native::io; use crate::native::packets::server::Exception; -use crate::native::Error; use bytes::Buf as _; /// Decode a list of Exception packets from the server, if possible. diff --git a/oximeter/db/src/native/io/packet/client.rs b/oximeter/db/src/native/io/packet/client.rs index 78e9fd09df3..06cfa390fd7 100644 --- a/oximeter/db/src/native/io/packet/client.rs +++ b/oximeter/db/src/native/io/packet/client.rs @@ -6,6 +6,7 @@ //! Encode client packets destined for the server. +use crate::native::Error; use crate::native::block::Block; use crate::native::io; use crate::native::packets::client::ClientInfo; @@ -16,7 +17,6 @@ use crate::native::packets::client::QueryKind; use crate::native::packets::client::Settings; use crate::native::packets::client::Stage; use crate::native::probes; -use crate::native::Error; use bytes::BufMut as _; use bytes::BytesMut; diff --git a/oximeter/db/src/native/io/packet/server.rs b/oximeter/db/src/native/io/packet/server.rs index 1fd9e2cac45..981c5512f87 100644 --- a/oximeter/db/src/native/io/packet/server.rs +++ b/oximeter/db/src/native/io/packet/server.rs @@ -6,12 +6,12 @@ //! Decode packets from the ClickHouse server. +use crate::native::Error; use crate::native::io; use crate::native::packets::server::Hello; use crate::native::packets::server::Packet; use crate::native::packets::server::PasswordComplexityRule; use crate::native::probes; -use crate::native::Error; use bytes::Buf as _; use bytes::BytesMut; diff --git a/oximeter/db/src/native/io/table_columns.rs b/oximeter/db/src/native/io/table_columns.rs index f7227d68613..e9755ac4f94 100644 --- a/oximeter/db/src/native/io/table_columns.rs +++ b/oximeter/db/src/native/io/table_columns.rs @@ -20,10 +20,12 @@ //! `details` field. use super::string; +use crate::native::Error; use crate::native::block::DataType; use crate::native::packets::server::ColumnDefaults; use crate::native::packets::server::ColumnDescription; -use crate::native::Error; +use nom::Err as NomErr; +use nom::IResult; use nom::bytes::streaming::is_not; use nom::bytes::streaming::tag; use nom::character::streaming::u64 as nom_u64; @@ -31,8 +33,6 @@ use nom::error::ErrorKind; use nom::sequence::delimited; use nom::sequence::separated_pair; use nom::sequence::terminated; -use nom::Err as NomErr; -use nom::IResult; /// Decode an array of `ColumnDescription`s from a buffer. pub fn decode( @@ -76,7 +76,7 @@ fn column_descriptions( return Err(Error::InvalidPacket { kind: "TableColumns", msg: format!("failed to parse header: {e}"), - }) + }); } }; @@ -104,7 +104,7 @@ fn column_descriptions( return Err(Error::InvalidPacket { kind: "TableColumns", msg: format!("failed to parse description: {e}"), - }) + }); } }; out.push(col); @@ -163,11 +163,11 @@ fn column_description(s: &str) -> IResult<&str, ColumnDescription> { #[cfg(test)] mod tests { + use super::NomErr; use super::backtick_quoted_column_name; use super::column_count; use super::column_description; use super::column_descriptions; - use super::NomErr; use crate::native::block::DataType; #[test] diff --git a/oximeter/db/src/native/packets/client.rs b/oximeter/db/src/native/packets/client.rs index 2a5ac1646e3..f3c0736db4c 100644 --- a/oximeter/db/src/native/packets/client.rs +++ b/oximeter/db/src/native/packets/client.rs @@ -8,8 +8,8 @@ use super::server::ProfileInfo; use super::server::Progress; -use crate::native::block::Block; use crate::QuerySummary; +use crate::native::block::Block; use std::borrow::Cow; use std::collections::BTreeMap; use std::net::SocketAddr; diff --git a/oximeter/db/src/oxql/ast/grammar.rs b/oximeter/db/src/oxql/ast/grammar.rs index 62182ec553a..f4d5d67c520 100644 --- a/oximeter/db/src/oxql/ast/grammar.rs +++ b/oximeter/db/src/oxql/ast/grammar.rs @@ -725,8 +725,10 @@ mod tests { assert!(query_parser::duration_literal_impl("-1m").is_err()); let too_big: i64 = i64::from(u32::MAX) + 1; - assert!(query_parser::duration_literal_impl(&format!("{too_big}s")) - .is_err()); + assert!( + query_parser::duration_literal_impl(&format!("{too_big}s")) + .is_err() + ); } #[test] @@ -740,14 +742,16 @@ mod tests { ID ); - assert!(query_parser::uuid_literal_impl( - &as_string[1..as_string.len() - 2] - ) - .is_err()); - assert!(query_parser::uuid_literal_impl( - &without_dashes[1..without_dashes.len() - 2] - ) - .is_err()); + assert!( + query_parser::uuid_literal_impl(&as_string[1..as_string.len() - 2]) + .is_err() + ); + assert!( + query_parser::uuid_literal_impl( + &without_dashes[1..without_dashes.len() - 2] + ) + .is_err() + ); } #[test] @@ -784,10 +788,14 @@ mod tests { ); // Out of range in either direction - assert!(query_parser::integer_literal_impl("0xFFFFFFFFFFFFFFFFFFFF") - .is_err()); - assert!(query_parser::integer_literal_impl("-0xFFFFFFFFFFFFFFFFFFFF") - .is_err()); + assert!( + query_parser::integer_literal_impl("0xFFFFFFFFFFFFFFFFFFFF") + .is_err() + ); + assert!( + query_parser::integer_literal_impl("-0xFFFFFFFFFFFFFFFFFFFF") + .is_err() + ); assert!(query_parser::integer_literal_impl("-0x1.0").is_err()); assert!(query_parser::integer_literal_impl("-0x1.").is_err()); @@ -884,8 +892,10 @@ mod tests { expected ); } - assert!(query_parser::string_literal_impl(r#"' cannot have ' in it'"#) - .is_err()); + assert!( + query_parser::string_literal_impl(r#"' cannot have ' in it'"#) + .is_err() + ); } #[test] @@ -907,8 +917,10 @@ mod tests { ); } - assert!(query_parser::string_literal_impl(r#"" cannot have " in it""#) - .is_err()); + assert!( + query_parser::string_literal_impl(r#"" cannot have " in it""#) + .is_err() + ); } #[test] @@ -1266,17 +1278,23 @@ mod tests { #[test] fn test_query_starts_with_get() { - assert!(query_parser::query("{ get a:b }") - .unwrap() - .all_gets_at_query_start()); - assert!(query_parser::query("{ get a:b; get a:b } | join") + assert!( + query_parser::query("{ get a:b }") + .unwrap() + .all_gets_at_query_start() + ); + assert!( + query_parser::query("{ get a:b; get a:b } | join") + .unwrap() + .all_gets_at_query_start() + ); + assert!( + query_parser::query( + "{ { get a:b ; get a:b } | join; get c:d } | join" + ) .unwrap() - .all_gets_at_query_start()); - assert!(query_parser::query( - "{ { get a:b ; get a:b } | join; get c:d } | join" - ) - .unwrap() - .all_gets_at_query_start()); + .all_gets_at_query_start() + ); assert!(query_parser::query("{ get a:b; filter foo == 0 }").is_err()); assert!(query_parser::query("{ get a:b; filter foo == 0 }").is_err()); @@ -1386,11 +1404,10 @@ mod tests { Limit { kind: LimitKind::Last, count: 100.try_into().unwrap() }, ); - assert!(query_parser::limit(&format!( - "first {}", - usize::MAX as i128 + 1 - )) - .is_err()); + assert!( + query_parser::limit(&format!("first {}", usize::MAX as i128 + 1)) + .is_err() + ); assert!(query_parser::limit("first 0").is_err()); assert!(query_parser::limit("first -1").is_err()); assert!(query_parser::limit("first \"foo\"").is_err()); diff --git a/oximeter/db/src/oxql/ast/literal.rs b/oximeter/db/src/oxql/ast/literal.rs index 4420a09fa67..83f541aeb4b 100644 --- a/oximeter/db/src/oxql/ast/literal.rs +++ b/oximeter/db/src/oxql/ast/literal.rs @@ -6,8 +6,8 @@ // Copyright 2024 Oxide Computer Company -use crate::oxql::ast::cmp::Comparison; use crate::oxql::Error; +use crate::oxql::ast::cmp::Comparison; use anyhow::Context; use chrono::DateTime; use chrono::Utc; @@ -325,9 +325,9 @@ impl fmt::Display for Literal { #[cfg(test)] mod tests { + use super::Literal; use super::duration_consts::*; use super::duration_to_db_interval; - use super::Literal; use crate::oxql::ast::cmp::Comparison; use oximeter::FieldValue; diff --git a/oximeter/db/src/oxql/ast/table_ops/align.rs b/oximeter/db/src/oxql/ast/table_ops/align.rs index 3e4db0f9388..ef3cf3db525 100644 --- a/oximeter/db/src/oxql/ast/table_ops/align.rs +++ b/oximeter/db/src/oxql/ast/table_ops/align.rs @@ -11,14 +11,14 @@ use anyhow::Error; use chrono::DateTime; use chrono::TimeDelta; use chrono::Utc; +use oxql_types::Alignment; +use oxql_types::Table; +use oxql_types::Timeseries; use oxql_types::point::DataType; use oxql_types::point::MetricType; use oxql_types::point::Points; use oxql_types::point::ValueArray; use oxql_types::point::Values; -use oxql_types::Alignment; -use oxql_types::Table; -use oxql_types::Timeseries; use std::fmt; use std::time::Duration; @@ -706,18 +706,19 @@ mod tests { .is_err()); // Sanity check for way below the threshold. - assert!(verify_max_upsampling_ratio( - timestamps, - &Duration::from_nanos(1), - ) - .is_err()); + assert!( + verify_max_upsampling_ratio(timestamps, &Duration::from_nanos(1),) + .is_err() + ); // Arrays where we can't compute an interval are fine. - assert!(verify_max_upsampling_ratio( - ×tamps[..1], - &Duration::from_nanos(1), - ) - .is_ok()); + assert!( + verify_max_upsampling_ratio( + ×tamps[..1], + &Duration::from_nanos(1), + ) + .is_ok() + ); assert!( verify_max_upsampling_ratio(&[], &Duration::from_nanos(1),).is_ok() ); diff --git a/oximeter/db/src/oxql/ast/table_ops/filter/mod.rs b/oximeter/db/src/oxql/ast/table_ops/filter/mod.rs index 3cb834ba851..aab59e39095 100644 --- a/oximeter/db/src/oxql/ast/table_ops/filter/mod.rs +++ b/oximeter/db/src/oxql/ast/table_ops/filter/mod.rs @@ -6,6 +6,7 @@ // Copyright 2024 Oxide Computer Company +use crate::oxql::Error; use crate::oxql::ast::cmp::Comparison; use crate::oxql::ast::ident::Ident; use crate::oxql::ast::literal::Literal; @@ -13,18 +14,17 @@ use crate::oxql::ast::logical_op::LogicalOp; use crate::oxql::ast::table_ops::limit::Limit; use crate::oxql::ast::table_ops::limit::LimitKind; use crate::oxql::schema::TableSchema; -use crate::oxql::Error; use crate::shells::special_idents; use chrono::DateTime; use chrono::Utc; use oximeter::FieldType; use oximeter::FieldValue; +use oxql_types::Table; +use oxql_types::Timeseries; use oxql_types::point::DataType; use oxql_types::point::MetricType; use oxql_types::point::Points; use oxql_types::point::ValueArray; -use oxql_types::Table; -use oxql_types::Timeseries; use regex::Regex; use std::collections::BTreeSet; use std::fmt; @@ -1288,13 +1288,13 @@ mod tests { use crate::oxql::ast::logical_op::LogicalOp; use chrono::Utc; use oximeter::FieldValue; + use oxql_types::Table; + use oxql_types::Timeseries; use oxql_types::point::DataType; use oxql_types::point::MetricType; use oxql_types::point::Points; use oxql_types::point::ValueArray; use oxql_types::point::Values; - use oxql_types::Table; - use oxql_types::Timeseries; use std::time::Duration; use uuid::Uuid; @@ -1427,29 +1427,35 @@ mod tests { ("!(a == 0)", "!(a == 0)"), ("a == 0 || b == 1", "a == 0 || b == 1"), ("a == 0 && b == 1", "a == 0 && b == 1"), - // Rewrite of XOR - ("a == 0 ^ b == 1", "(a == 0 && !(b == 1)) || (!(a == 0) && (b == 1))"), - + ( + "a == 0 ^ b == 1", + "(a == 0 && !(b == 1)) || (!(a == 0) && (b == 1))", + ), // Simple applications of distribution rules. // // Distribute conjunction over disjunction. - ("a == 0 && (b == 1 || c == 2)", "(a == 0 && b == 1) || (a == 0 && c == 2)"), - ("a == 0 && (b == 1 || c == 2 || d == 3)", "(a == 0 && b == 1) || (a == 0 && c == 2) || (a == 0 && d == 3)"), - ("a == 0 && (b == 1 || c == 2 || d == 3 || e == 4)", "(a == 0 && b == 1) || (a == 0 && c == 2) || (a == 0 && d == 3) || (a == 0 && e == 4)"), + ( + "a == 0 && (b == 1 || c == 2)", + "(a == 0 && b == 1) || (a == 0 && c == 2)", + ), + ( + "a == 0 && (b == 1 || c == 2 || d == 3)", + "(a == 0 && b == 1) || (a == 0 && c == 2) || (a == 0 && d == 3)", + ), + ( + "a == 0 && (b == 1 || c == 2 || d == 3 || e == 4)", + "(a == 0 && b == 1) || (a == 0 && c == 2) || (a == 0 && d == 3) || (a == 0 && e == 4)", + ), ]; for (input, expected) in cases.iter() { let parsed_input = query_parser::filter_expr(input).unwrap(); let simplified = parsed_input.simplify_to_dnf().unwrap(); let parsed_expected = query_parser::filter_expr(expected).unwrap(); assert_eq!( - simplified, - parsed_expected, + simplified, parsed_expected, "\ninput expression: {}\nparsed to: {}\nsimplifed to: {}\nexpected: {}\n", - input, - parsed_input, - simplified, - expected, + input, parsed_input, simplified, expected, ); } } diff --git a/oximeter/db/src/oxql/ast/table_ops/filter/visit.rs b/oximeter/db/src/oxql/ast/table_ops/filter/visit.rs index 7d8347d7fd6..a32c03a65cd 100644 --- a/oximeter/db/src/oxql/ast/table_ops/filter/visit.rs +++ b/oximeter/db/src/oxql/ast/table_ops/filter/visit.rs @@ -12,11 +12,11 @@ use super::CompoundFilter; use super::Filter; use super::FilterExpr; use super::SimpleFilter; +use crate::oxql::Error; use crate::oxql::ast::cmp::Comparison; use crate::oxql::ast::literal::Literal; use crate::oxql::ast::logical_op::LogicalOp; use crate::oxql::schema::TableSchema; -use crate::oxql::Error; use crate::shells::special_idents; /// A trait for visiting a tree of filter nodes. diff --git a/oximeter/db/src/oxql/ast/table_ops/group_by.rs b/oximeter/db/src/oxql/ast/table_ops/group_by.rs index 933bf1d155b..881dde3791f 100644 --- a/oximeter/db/src/oxql/ast/table_ops/group_by.rs +++ b/oximeter/db/src/oxql/ast/table_ops/group_by.rs @@ -12,13 +12,13 @@ use chrono::Utc; use crate::oxql::ast::ident::Ident; use anyhow::Error; use oximeter::schema::TimeseriesKey; +use oxql_types::Table; +use oxql_types::Timeseries; use oxql_types::point::DataType; use oxql_types::point::MetricType; use oxql_types::point::ValueArray; -use oxql_types::Table; -use oxql_types::Timeseries; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::fmt; /// A table operation for grouping data by fields, apply a reducer to the @@ -404,7 +404,10 @@ impl GroupBy { }) .collect(); let old = sample_counts_by_group.insert(key, counts); - assert!(old.is_none(), "Should not have counts entry for first timeseries in the group"); + assert!( + old.is_none(), + "Should not have counts entry for first timeseries in the group" + ); output_table.insert(new_timeseries)?; } } @@ -457,8 +460,8 @@ mod tests { use chrono::{DateTime, Utc}; use oximeter::FieldValue; use oxql_types::{ - point::{DataType, MetricType, ValueArray}, Table, Timeseries, + point::{DataType, MetricType, ValueArray}, }; use std::{collections::BTreeMap, time::Duration}; diff --git a/oximeter/db/src/oxql/ast/table_ops/join.rs b/oximeter/db/src/oxql/ast/table_ops/join.rs index 2893f6cf3e0..4e1253e7873 100644 --- a/oximeter/db/src/oxql/ast/table_ops/join.rs +++ b/oximeter/db/src/oxql/ast/table_ops/join.rs @@ -8,8 +8,8 @@ use anyhow::Context; use anyhow::Error; -use oxql_types::point::MetricType; use oxql_types::Table; +use oxql_types::point::MetricType; /// An AST node for a natural inner join. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/oximeter/db/src/oxql/ast/table_ops/limit.rs b/oximeter/db/src/oxql/ast/table_ops/limit.rs index e093246d684..f730b8203a6 100644 --- a/oximeter/db/src/oxql/ast/table_ops/limit.rs +++ b/oximeter/db/src/oxql/ast/table_ops/limit.rs @@ -86,8 +86,8 @@ mod tests { use chrono::Utc; use oximeter::FieldValue; use oxql_types::{ - point::{DataType, MetricType}, Timeseries, + point::{DataType, MetricType}, }; use std::{collections::BTreeMap, time::Duration}; @@ -220,8 +220,7 @@ mod tests { let limit = Limit { kind, count: 100.try_into().unwrap() }; let limited = limit.apply(&tables).expect("This should be infallible"); assert_eq!( - limited, - tables, + limited, tables, "Limiting tables to more than their length should return the same thing" ); } diff --git a/oximeter/db/src/oxql/ast/table_ops/mod.rs b/oximeter/db/src/oxql/ast/table_ops/mod.rs index 81f72dfa98d..6988d8ae300 100644 --- a/oximeter/db/src/oxql/ast/table_ops/mod.rs +++ b/oximeter/db/src/oxql/ast/table_ops/mod.rs @@ -20,8 +20,8 @@ use self::filter::Filter; use self::group_by::GroupBy; use self::join::Join; use self::limit::Limit; -use crate::oxql::ast::Query; use crate::oxql::Error; +use crate::oxql::ast::Query; use chrono::DateTime; use chrono::Utc; use oximeter::TimeseriesName; @@ -122,9 +122,9 @@ impl TableOp { #[cfg(test)] mod test { use super::GroupedTableOp; + use crate::oxql::ast::Query; use crate::oxql::ast::table_ops::BasicTableOp; use crate::oxql::ast::table_ops::TableOp; - use crate::oxql::ast::Query; #[test] fn test_grouped_table_op_display() { diff --git a/oximeter/db/src/oxql/plan/align.rs b/oximeter/db/src/oxql/plan/align.rs index d04c70a1c68..dea435b5880 100644 --- a/oximeter/db/src/oxql/plan/align.rs +++ b/oximeter/db/src/oxql/plan/align.rs @@ -91,9 +91,9 @@ fn align_input_schema( #[cfg(test)] mod test { + use super::TableSchema; use super::align; use super::align_input_schema; - use super::TableSchema; use oximeter::FieldType; use oxql_types::point::DataType; use oxql_types::point::MetricType; diff --git a/oximeter/db/src/oxql/plan/node.rs b/oximeter/db/src/oxql/plan/node.rs index 62f19083867..5678f747559 100644 --- a/oximeter/db/src/oxql/plan/node.rs +++ b/oximeter/db/src/oxql/plan/node.rs @@ -6,6 +6,7 @@ // Copyright 2024 Oxide Computer Company +use crate::oxql::plan::Plan; use crate::oxql::plan::align::Align; use crate::oxql::plan::delta::Delta; use crate::oxql::plan::filter::Filter; @@ -15,7 +16,6 @@ use crate::oxql::plan::join::Join; use crate::oxql::plan::limit::Limit; use crate::oxql::plan::plan::TableOpData; use crate::oxql::plan::plan::TableOpOutput; -use crate::oxql::plan::Plan; /// A node in the query plan. /// diff --git a/oximeter/db/src/oxql/plan/plan.rs b/oximeter/db/src/oxql/plan/plan.rs index 8d8fa8a22c7..bc6af9b7033 100644 --- a/oximeter/db/src/oxql/plan/plan.rs +++ b/oximeter/db/src/oxql/plan/plan.rs @@ -6,11 +6,11 @@ // Copyright 2025 Oxide Computer Company -use crate::oxql::ast::table_ops::align; +use crate::oxql::ast::Query; use crate::oxql::ast::table_ops::BasicTableOp; use crate::oxql::ast::table_ops::GroupedTableOp; use crate::oxql::ast::table_ops::TableOp; -use crate::oxql::ast::Query; +use crate::oxql::ast::table_ops::align; use crate::oxql::plan::align::Align; use crate::oxql::plan::delta::Delta; use crate::oxql::plan::filter::Filter; @@ -934,8 +934,8 @@ pub(super) mod test_utils { static ALL_SCHEMA: OnceCell> = OnceCell::const_new(); - pub async fn all_schema( - ) -> &'static BTreeMap { + pub async fn all_schema() + -> &'static BTreeMap { ALL_SCHEMA.get_or_init(load_schema).await } } @@ -943,9 +943,9 @@ pub(super) mod test_utils { #[cfg(test)] mod tests { use crate::oxql::ast::grammar::query_parser; + use crate::oxql::plan::Plan; use crate::oxql::plan::node::Node; use crate::oxql::plan::plan::test_utils::all_schema; - use crate::oxql::plan::Plan; use oxql_types::point::DataType; use oxql_types::point::MetricType; @@ -1108,11 +1108,7 @@ mod tests { .field_schema .iter() .find_map(|s| { - if s.name == field { - Some(s.field_type) - } else { - None - } + if s.name == field { Some(s.field_type) } else { None } }) .unwrap(); assert_eq!( @@ -1249,7 +1245,8 @@ mod tests { "Should fail to plan query with an incomparable filter", ); assert!( - err.to_string().contains("is not compatible with the expected type"), + err.to_string() + .contains("is not compatible with the expected type"), "Error message should complain that a filter cannot compare \ a field against an incompatible type, but the error message is: {:#?}", err, diff --git a/oximeter/db/src/oxql/plan/predicates.rs b/oximeter/db/src/oxql/plan/predicates.rs index 4079fd5c3d0..7cd0ad855cf 100644 --- a/oximeter/db/src/oxql/plan/predicates.rs +++ b/oximeter/db/src/oxql/plan/predicates.rs @@ -446,11 +446,11 @@ impl std::ops::Deref for OptionalDisjunctions { #[cfg(test)] mod tests { use crate::oxql::ast::grammar::query_parser; + use crate::oxql::plan::Plan; use crate::oxql::plan::node::Node; use crate::oxql::plan::plan::test_utils::all_schema; use crate::oxql::plan::predicates::Predicates; use crate::oxql::plan::predicates::SplitPredicates; - use crate::oxql::plan::Plan; #[tokio::test] async fn push_single_predicate_through_alignment() { diff --git a/oximeter/db/src/oxql/query/mod.rs b/oximeter/db/src/oxql/query/mod.rs index ec5b578ffd6..13fed9bdf67 100644 --- a/oximeter/db/src/oxql/query/mod.rs +++ b/oximeter/db/src/oxql/query/mod.rs @@ -8,21 +8,21 @@ use std::collections::BTreeSet; +use super::ast::SplitQuery; use super::ast::ident::Ident; use super::ast::logical_op::LogicalOp; +use super::ast::table_ops::BasicTableOp; +use super::ast::table_ops::TableOp; use super::ast::table_ops::filter::CompoundFilter; use super::ast::table_ops::filter::FilterExpr; use super::ast::table_ops::group_by::GroupBy; use super::ast::table_ops::limit::Limit; -use super::ast::table_ops::BasicTableOp; -use super::ast::table_ops::TableOp; -use super::ast::SplitQuery; +use crate::TimeseriesName; +use crate::oxql::Error; +use crate::oxql::ast::Query as QueryNode; use crate::oxql::ast::grammar; use crate::oxql::ast::table_ops::filter::Filter; -use crate::oxql::ast::Query as QueryNode; use crate::oxql::fmt_parse_error; -use crate::oxql::Error; -use crate::TimeseriesName; use chrono::DateTime; use chrono::Utc; @@ -407,18 +407,18 @@ mod tests { use super::Filter; use super::Ident; use super::Query; + use crate::oxql::ast::SplitQuery; use crate::oxql::ast::cmp::Comparison; use crate::oxql::ast::literal::Literal; use crate::oxql::ast::logical_op::LogicalOp; + use crate::oxql::ast::table_ops::BasicTableOp; + use crate::oxql::ast::table_ops::TableOp; use crate::oxql::ast::table_ops::filter::CompoundFilter; use crate::oxql::ast::table_ops::filter::FilterExpr; use crate::oxql::ast::table_ops::filter::SimpleFilter; use crate::oxql::ast::table_ops::join::Join; use crate::oxql::ast::table_ops::limit::Limit; use crate::oxql::ast::table_ops::limit::LimitKind; - use crate::oxql::ast::table_ops::BasicTableOp; - use crate::oxql::ast::table_ops::TableOp; - use crate::oxql::ast::SplitQuery; use crate::oxql::query::restrict_filter_idents; use chrono::NaiveDateTime; use chrono::Utc; @@ -754,7 +754,8 @@ mod tests { .unwrap(); assert_eq!( inner, - expected_predicate.merge(&expected_inner_predicate, LogicalOp::And), + expected_predicate + .merge(&expected_inner_predicate, LogicalOp::And), "Predicates passed into an inner subquery should be preserved, \ and merged with any subquery predicates", ); @@ -816,8 +817,7 @@ mod tests { )) .unwrap(); assert_eq!( - q.end_time, - then, + q.end_time, then, "Query with a compound less-than-or-equal filter and a timestamp should \ set the query end time" ); @@ -831,8 +831,7 @@ mod tests { )) .unwrap(); assert_eq!( - q.end_time, - then, + q.end_time, then, "Query with two less-than timestamp filters should use the later timestamp" ); @@ -947,8 +946,8 @@ mod tests { } #[test] - fn test_coalesce_limits_do_not_rearrange_around_incompatible_timestamp_filters( - ) { + fn test_coalesce_limits_do_not_rearrange_around_incompatible_timestamp_filters() + { let qs = [ "get a:b | filter timestamp < @now() | last 10", "get a:b | filter timestamp > @now() | first 10", diff --git a/oximeter/db/src/query.rs b/oximeter/db/src/query.rs index 551feb12602..df97bc13c66 100644 --- a/oximeter/db/src/query.rs +++ b/oximeter/db/src/query.rs @@ -5,7 +5,7 @@ //! Functions for querying the timeseries database. // Copyright 2024 Oxide Computer Company -use crate::{Error, FieldSchema, FieldSource, TimeseriesSchema, DATABASE_NAME}; +use crate::{DATABASE_NAME, Error, FieldSchema, FieldSource, TimeseriesSchema}; use chrono::{DateTime, Utc}; use dropshot::PaginationOrder; use oximeter::schema::TimeseriesKey; @@ -1230,7 +1230,8 @@ mod tests { "filter0.timeseries_name = filter1.timeseries_name AND ", "filter0.timeseries_key = filter1.timeseries_key) ", "ORDER BY (filter0.timeseries_name, filter0.timeseries_key)", - )); + ) + ); let keys = &[0, 1]; assert_eq!( query.measurement_query(keys).trim(), diff --git a/oximeter/db/src/shells/native.rs b/oximeter/db/src/shells/native.rs index acdb0d81088..72311c20f7c 100644 --- a/oximeter/db/src/shells/native.rs +++ b/oximeter/db/src/shells/native.rs @@ -6,7 +6,7 @@ // Copyright 2024 Oxide Computer Company -use crate::native::{self, block::ValueArray, QueryResult}; +use crate::native::{self, QueryResult, block::ValueArray}; use anyhow::Context as _; use crossterm::style::Stylize; use display_error_chain::DisplayErrorChain; @@ -172,11 +172,7 @@ fn values_to_string<'a>( ValueArray::Nullable { is_null, values } => { let inner = values_to_string(values); let it = is_null.iter().zip(inner).map(|(is_null, value)| { - if *is_null { - String::from("NULL") - } else { - value.to_string() - } + if *is_null { String::from("NULL") } else { value.to_string() } }); Box::new(it) } diff --git a/oximeter/db/src/shells/oxql.rs b/oximeter/db/src/shells/oxql.rs index 02dccdc57ea..59051c03058 100644 --- a/oximeter/db/src/shells/oxql.rs +++ b/oximeter/db/src/shells/oxql.rs @@ -7,7 +7,7 @@ // Copyright 2024 Oxide Computer use super::{list_timeseries, prepare_columns}; -use crate::{make_client, Client, OxqlResult}; +use crate::{Client, OxqlResult, make_client}; use clap::Args; use crossterm::style::Stylize; use oxql_types::Table; diff --git a/oximeter/db/src/shells/sql.rs b/oximeter/db/src/shells/sql.rs index f75713da3b9..bdc15204a76 100644 --- a/oximeter/db/src/shells/sql.rs +++ b/oximeter/db/src/shells/sql.rs @@ -7,8 +7,8 @@ // Copyright 2024 Oxide Computer Company use super::prepare_columns; -use crate::sql::{function_allow_list, QueryResult, Table}; -use crate::{make_client, Client, QuerySummary}; +use crate::sql::{QueryResult, Table, function_allow_list}; +use crate::{Client, QuerySummary, make_client}; use clap::Args; use dropshot::EmptyScanParams; use dropshot::WhichPage; diff --git a/oximeter/db/src/sql/mod.rs b/oximeter/db/src/sql/mod.rs index 134c58ad095..6d1e7a37443 100644 --- a/oximeter/db/src/sql/mod.rs +++ b/oximeter/db/src/sql/mod.rs @@ -27,14 +27,14 @@ // Copyright 2023 Oxide Computer Company -use crate::query::field_table_name; -use crate::query::measurement_table_name; use crate::DatumType; use crate::Error as OxdbError; use crate::FieldType; use crate::QuerySummary; use crate::TimeseriesName; use crate::TimeseriesSchema; +use crate::query::field_table_name; +use crate::query::measurement_table_name; use indexmap::IndexSet; use oximeter::MetricsError; use sqlparser::ast::BinaryOperator; @@ -856,8 +856,8 @@ impl RestrictedQuery { } _ => { return unsupported!( - "Query must select from concrete tables or subqueries on them" - ) + "Query must select from concrete tables or subqueries on them" + ); } } } diff --git a/oximeter/db/tests/integration_test.rs b/oximeter/db/tests/integration_test.rs index eedc7b08623..0a0ffeef62d 100644 --- a/oximeter/db/tests/integration_test.rs +++ b/oximeter/db/tests/integration_test.rs @@ -9,7 +9,7 @@ use omicron_test_utils::dev::poll; use omicron_test_utils::dev::test_setup_log; use oximeter_db::{Client, DbWrite, OxqlResult, Sample, TestDbWrite}; use oximeter_test_utils::wait_for_keepers; -use slog::{info, Logger}; +use slog::{Logger, info}; use std::collections::BTreeSet; use std::default::Default; use std::time::Duration; diff --git a/oximeter/instruments/src/http.rs b/oximeter/instruments/src/http.rs index de5f71f96d3..74e569b30cc 100644 --- a/oximeter/instruments/src/http.rs +++ b/oximeter/instruments/src/http.rs @@ -10,7 +10,7 @@ use dropshot::{HttpError, HttpResponse, RequestContext, ServerContext}; use futures::Future; use http::StatusCode; use oximeter::{ - histogram::Histogram, histogram::Record, MetricsError, Producer, Sample, + MetricsError, Producer, Sample, histogram::Histogram, histogram::Record, }; use std::collections::HashMap; use std::hash::{DefaultHasher, Hash as _, Hasher}; diff --git a/oximeter/instruments/src/kstat/link.rs b/oximeter/instruments/src/kstat/link.rs index f3e5edc51fa..c0d18de1251 100644 --- a/oximeter/instruments/src/kstat/link.rs +++ b/oximeter/instruments/src/kstat/link.rs @@ -4,21 +4,21 @@ //! Report metrics about Ethernet data links on the host system -use crate::kstat::hrtime_to_utc; use crate::kstat::ConvertNamedData; use crate::kstat::Error; use crate::kstat::KstatList; use crate::kstat::KstatTarget; +use crate::kstat::hrtime_to_utc; use chrono::DateTime; use chrono::Utc; use kstat_rs::Data; use kstat_rs::Kstat; use kstat_rs::Named; -use oximeter::types::Cumulative; use oximeter::FieldType; use oximeter::FieldValue; use oximeter::Sample; use oximeter::Target; +use oximeter::types::Cumulative; use uuid::Uuid; oximeter::use_timeseries!("sled-data-link.toml"); @@ -178,22 +178,22 @@ impl Target for SledDataLink { #[cfg(all(test, target_os = "illumos"))] mod tests { use super::*; - use crate::kstat::sampler::KstatPath; - use crate::kstat::sampler::CREATION_TIME_PRUNE_INTERVAL; use crate::kstat::CollectionDetails; use crate::kstat::KstatSampler; use crate::kstat::TargetStatus; + use crate::kstat::sampler::CREATION_TIME_PRUNE_INTERVAL; + use crate::kstat::sampler::KstatPath; use kstat_rs::Ctl; use oximeter::Producer; - use rand::distributions::Uniform; use rand::Rng; - use slog::info; + use rand::distributions::Uniform; use slog::Drain; use slog::Logger; + use slog::info; use std::time::Duration; use tokio::time::Instant; - use uuid::uuid; use uuid::Uuid; + use uuid::uuid; fn test_logger() -> Logger { let dec = diff --git a/oximeter/instruments/src/kstat/sampler.rs b/oximeter/instruments/src/kstat/sampler.rs index c6101ac06a8..25c104d9211 100644 --- a/oximeter/instruments/src/kstat/sampler.rs +++ b/oximeter/instruments/src/kstat/sampler.rs @@ -4,32 +4,32 @@ //! Generate oximeter samples from kernel statistics. -use super::now; use super::Timestamp; -use crate::kstat::hrtime_to_utc; +use super::now; use crate::kstat::Error; use crate::kstat::Expiration; use crate::kstat::ExpirationReason; use crate::kstat::KstatTarget; +use crate::kstat::hrtime_to_utc; use chrono::DateTime; use chrono::Utc; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; use kstat_rs::Ctl; use kstat_rs::Kstat; -use oximeter::types::Cumulative; use oximeter::Metric; use oximeter::MetricsError; use oximeter::Sample; +use oximeter::types::Cumulative; +use slog::Logger; use slog::debug; use slog::error; use slog::o; use slog::trace; use slog::warn; -use slog::Logger; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; use std::fmt; use std::pin::Pin; use std::sync::Arc; @@ -39,9 +39,9 @@ use std::task::Poll; use std::time::Duration; use tokio::sync::mpsc; use tokio::sync::oneshot; +use tokio::time::Sleep; use tokio::time::interval; use tokio::time::sleep; -use tokio::time::Sleep; // The `KstatSampler` generates some statistics about its own operation, mostly // for surfacing failures to collect and dropped samples. diff --git a/oximeter/oximeter-macro-impl/src/lib.rs b/oximeter/oximeter-macro-impl/src/lib.rs index 499cd82d0aa..80990978da1 100644 --- a/oximeter/oximeter-macro-impl/src/lib.rs +++ b/oximeter/oximeter-macro-impl/src/lib.rs @@ -55,9 +55,9 @@ fn target_impl(tokens: TokenStream) -> syn::Result { vec![] } else { return Err(Error::new( - item.span(), - "Can only be derived for structs with named fields or unit structs", - )); + item.span(), + "Can only be derived for structs with named fields or unit structs", + )); }; return Ok(build_target_trait_impl(&name, &fields[..])); } diff --git a/oximeter/oximeter/src/lib.rs b/oximeter/oximeter/src/lib.rs index 913318b8a89..20bad5ba694 100644 --- a/oximeter/oximeter/src/lib.rs +++ b/oximeter/oximeter/src/lib.rs @@ -192,8 +192,8 @@ pub use oximeter_types::*; #[cfg(test)] mod test { use oximeter_schema::ir::load_schema; - use oximeter_types::schema::{FieldSource, SCHEMA_DIRECTORY}; use oximeter_types::TimeseriesSchema; + use oximeter_types::schema::{FieldSource, SCHEMA_DIRECTORY}; use std::collections::BTreeMap; use std::fs; diff --git a/oximeter/oxql-types/src/point.rs b/oximeter/oxql-types/src/point.rs index d8fddc18be4..808ceb7bc03 100644 --- a/oximeter/oxql-types/src/point.rs +++ b/oximeter/oxql-types/src/point.rs @@ -11,10 +11,10 @@ use anyhow::Error; use chrono::DateTime; use chrono::Utc; use num::ToPrimitive; -use oximeter_types::traits::HistogramSupport; use oximeter_types::DatumType; use oximeter_types::Measurement; use oximeter_types::Quantile; +use oximeter_types::traits::HistogramSupport; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -418,11 +418,7 @@ impl Points { let Some(first_type) = types.next() else { unreachable!(); }; - if types.all(|ty| ty == first_type) { - Some(first_type) - } else { - None - } + if types.all(|ty| ty == first_type) { Some(first_type) } else { None } } /// Construct a list of gauge points from a list of gauge measurements. @@ -1980,10 +1976,10 @@ f64_dist_from!(f64); #[cfg(test)] mod tests { use super::{Distribution, MetricType, Points, Values}; - use crate::point::{push_concrete_values, DataType, Datum, ValueArray}; + use crate::point::{DataType, Datum, ValueArray, push_concrete_values}; use chrono::{DateTime, Utc}; use oximeter_types::{ - histogram::Record, types::Cumulative, Measurement, Quantile, + Measurement, Quantile, histogram::Record, types::Cumulative, }; use std::time::Duration; @@ -2369,12 +2365,14 @@ mod tests { ); } assert!(points.cast(&[]).is_err()); - assert!(points - .cast(&[ - DataType::IntegerDistribution, - DataType::IntegerDistribution - ]) - .is_err()); + assert!( + points + .cast(&[ + DataType::IntegerDistribution, + DataType::IntegerDistribution + ]) + .is_err() + ); } #[test] @@ -2416,9 +2414,14 @@ mod tests { ); } assert!(points.cast(&[]).is_err()); - assert!(points - .cast(&[DataType::DoubleDistribution, DataType::DoubleDistribution]) - .is_err()); + assert!( + points + .cast(&[ + DataType::DoubleDistribution, + DataType::DoubleDistribution + ]) + .is_err() + ); } #[test] diff --git a/oximeter/oxql-types/src/table.rs b/oximeter/oxql-types/src/table.rs index f37992942fd..e6b857daa7e 100644 --- a/oximeter/oxql-types/src/table.rs +++ b/oximeter/oxql-types/src/table.rs @@ -6,21 +6,21 @@ // Copyright 2024 Oxide Computer Company +use crate::Alignment; use crate::point::DataType; use crate::point::MetricType; use crate::point::Points; use crate::point::ValueArray; use crate::point::Values; -use crate::Alignment; use anyhow::Error; use highway::HighwayHasher; -use oximeter_types::schema::TimeseriesKey; use oximeter_types::FieldValue; +use oximeter_types::schema::TimeseriesKey; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::hash::Hash; use std::hash::Hasher; diff --git a/oximeter/producer/examples/producer.rs b/oximeter/producer/examples/producer.rs index 3b4e879ca61..15807f75267 100644 --- a/oximeter/producer/examples/producer.rs +++ b/oximeter/producer/examples/producer.rs @@ -14,13 +14,13 @@ use dropshot::ConfigLogging; use dropshot::ConfigLoggingLevel; use omicron_common::api::internal::nexus::ProducerEndpoint; use omicron_common::api::internal::nexus::ProducerKind; -use oximeter::types::Cumulative; -use oximeter::types::ProducerRegistry; -use oximeter::types::Sample; use oximeter::Metric; use oximeter::MetricsError; use oximeter::Producer; use oximeter::Target; +use oximeter::types::Cumulative; +use oximeter::types::ProducerRegistry; +use oximeter::types::Sample; use oximeter_producer::Config; use oximeter_producer::LogConfig; use oximeter_producer::Server; diff --git a/oximeter/producer/src/lib.rs b/oximeter/producer/src/lib.rs index 04768ff42ef..84f214e7397 100644 --- a/oximeter/producer/src/lib.rs +++ b/oximeter/producer/src/lib.rs @@ -6,7 +6,6 @@ // Copyright 2024 Oxide Computer Company -use dropshot::endpoint; use dropshot::ApiDescription; use dropshot::ConfigDropshot; use dropshot::HttpError; @@ -15,26 +14,27 @@ use dropshot::HttpServer; use dropshot::Path; use dropshot::RequestContext; use dropshot::ServerBuilder; +use dropshot::endpoint; use internal_dns_resolver::ResolveError; use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use nexus_client::types::ProducerEndpoint as ApiProducerEndpoint; +use omicron_common::FileKv; use omicron_common::api::internal::nexus::ProducerEndpoint; use omicron_common::backoff; use omicron_common::backoff::BackoffError; -use omicron_common::FileKv; use oximeter::types::ProducerRegistry; use oximeter::types::ProducerResults; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; +use slog::Drain; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; use slog::warn; -use slog::Drain; -use slog::Logger; use std::net::IpAddr; use std::net::SocketAddr; use std::time::Duration; @@ -454,7 +454,6 @@ mod tests { use super::LogConfig; use super::ProducerEndpoint; use super::Server; - use dropshot::endpoint; use dropshot::ApiDescription; use dropshot::ConfigDropshot; use dropshot::HttpError; @@ -462,14 +461,15 @@ mod tests { use dropshot::HttpServer; use dropshot::RequestContext; use dropshot::ServerBuilder; + use dropshot::endpoint; use omicron_common::api::internal::nexus::ProducerKind; use omicron_common::api::internal::nexus::ProducerRegistrationResponse; - use omicron_test_utils::dev::poll::{wait_for_condition, CondCheckError}; + use omicron_test_utils::dev::poll::{CondCheckError, wait_for_condition}; use slog::Drain; use slog::Logger; + use std::sync::Arc; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; - use std::sync::Arc; use std::time::Duration; use uuid::Uuid; diff --git a/oximeter/schema/src/ir.rs b/oximeter/schema/src/ir.rs index 370236000ac..81fa590bfaa 100644 --- a/oximeter/schema/src/ir.rs +++ b/oximeter/schema/src/ir.rs @@ -23,9 +23,9 @@ use oximeter_types::TimeseriesName; use oximeter_types::TimeseriesSchema; use oximeter_types::Units; use serde::Deserialize; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; use std::num::NonZeroU8; mod limits { @@ -450,9 +450,9 @@ impl TimeseriesDefinition { { return Err(MetricsError::SchemaDefinition( format!( - "Timeseries '{}' version {} is duplicated", - old.timeseries_name, old.version, - ), + "Timeseries '{}' version {} is duplicated", + old.timeseries_name, old.version, + ), )); } } @@ -837,13 +837,15 @@ mod tests { let name = String::from("bar"); let target_fields = std::iter::once(name.clone()).collect(); let metric_fields = std::iter::once(name).collect(); - assert!(construct_field_schema( + assert!( + construct_field_schema( &all, "target", &target_fields, "metric", &metric_fields, - ).is_err(), + ) + .is_err(), "Should return an error when the target and metric share a field name" ); } @@ -912,12 +914,14 @@ mod tests { ); for name in ["project_id", "id"] { assert!( - validate_field_name(name, - &FieldMetadata { - type_: FieldType::Uuid, - description: String::new() - } - ).is_ok(), + validate_field_name( + name, + &FieldMetadata { + type_: FieldType::Uuid, + description: String::new() + } + ) + .is_ok(), "A Uuid field should be required to end in '_id' or exactly 'id'", ); } @@ -1055,7 +1059,9 @@ mod tests { "#; let res = load_schema(contents); let Err(MetricsError::SchemaDefinition(msg)) = &res else { - panic!("Should fail when metrics are not added in, but found: {res:#?}"); + panic!( + "Should fail when metrics are not added in, but found: {res:#?}" + ); }; assert!( msg.contains("must be added in at its first"), @@ -1274,8 +1280,8 @@ mod tests { } #[test] - fn load_schema_fills_in_implied_metric_versions_when_last_version_is_removed( - ) { + fn load_schema_fills_in_implied_metric_versions_when_last_version_is_removed() + { let contents = r#" format_version = 1 diff --git a/oximeter/test-utils/src/lib.rs b/oximeter/test-utils/src/lib.rs index 0ceb2129f48..3f6ad2ece81 100644 --- a/oximeter/test-utils/src/lib.rs +++ b/oximeter/test-utils/src/lib.rs @@ -26,7 +26,7 @@ use oximeter_types::types::{ Cumulative, Datum, DatumType, FieldType, FieldValue, Measurement, Sample, }; use oximeter_types::{Metric, Target}; -use slog::{debug, info, Logger}; +use slog::{Logger, debug, info}; use std::time::Duration; use uuid::Uuid; @@ -211,11 +211,11 @@ pub async fn wait_for_ping( mod tests { use chrono::Utc; use oximeter_types::{ + TimeseriesName, schema::{ - default_schema_version, AuthzScope, FieldSchema, FieldSource, - TimeseriesSchema, Units, + AuthzScope, FieldSchema, FieldSource, TimeseriesSchema, Units, + default_schema_version, }, - TimeseriesName, }; use super::*; diff --git a/oximeter/types/benches/quantile.rs b/oximeter/types/benches/quantile.rs index b88cb211e6a..bc092ccfefe 100644 --- a/oximeter/types/benches/quantile.rs +++ b/oximeter/types/benches/quantile.rs @@ -7,7 +7,7 @@ // Copyright 2024 Oxide Computer Company -use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use oximeter_types::Quantile; use rand_distr::{Distribution, Normal}; diff --git a/oximeter/types/src/histogram.rs b/oximeter/types/src/histogram.rs index a1ec458b73a..e70c16029ff 100644 --- a/oximeter/types/src/histogram.rs +++ b/oximeter/types/src/histogram.rs @@ -10,16 +10,16 @@ use super::Quantile; use super::QuantileError; use chrono::DateTime; use chrono::Utc; -use num::traits::Bounded; -use num::traits::FromPrimitive; -use num::traits::Num; -use num::traits::ToPrimitive; -use num::traits::Zero; use num::CheckedAdd; use num::CheckedMul; use num::Float; use num::Integer; use num::NumCast; +use num::traits::Bounded; +use num::traits::FromPrimitive; +use num::traits::Num; +use num::traits::ToPrimitive; +use num::traits::Zero; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -109,9 +109,7 @@ pub enum HistogramError { NonmonotonicBins, /// A non-finite was encountered, either as a bin edge or a sample. - #[error( - "Bin edges and samples must be finite values, not Infinity or NaN" - )] + #[error("Bin edges and samples must be finite values, not Infinity or NaN")] NonFiniteValue, /// Error returned when two neighboring bins are not adjoining (there's space between them) @@ -119,7 +117,9 @@ pub enum HistogramError { NonAdjoiningBins { left: String, right: String }, /// Bin and count arrays are of different sizes. - #[error("Bin and count arrays must have the same size, found {n_bins} and {n_counts}")] + #[error( + "Bin and count arrays must have the same size, found {n_bins} and {n_counts}" + )] ArraySizeMismatch { n_bins: usize, n_counts: usize }, /// Error returned when a quantization error occurs. @@ -593,14 +593,16 @@ where (Bound::Excluded(end), Bound::Included(start)) => { ensure_finite(*end).and(ensure_finite(*start))?; if end != start { - return Err( - HistogramError::NonAdjoiningBins { - left: format!("{:?}", first), - right: format!("{:?}", second), - }); + return Err(HistogramError::NonAdjoiningBins { + left: format!("{:?}", first), + right: format!("{:?}", second), + }); } } - _ => unreachable!("Bin ranges should always be excluded above and included below: {:#?}", (first, second)) + _ => unreachable!( + "Bin ranges should always be excluded above and included below: {:#?}", + (first, second) + ), } } if let Bound::Excluded(end) = bins_.last().unwrap().range.end_bound() { @@ -703,10 +705,12 @@ where BinRange::Range { start, .. } => { bins.push(start); } - BinRange::RangeFrom { start} => { + BinRange::RangeFrom { start } => { bins.push(start); } - _ => unreachable!("No bins in a constructed histogram should be of type RangeTo"), + _ => unreachable!( + "No bins in a constructed histogram should be of type RangeTo" + ), } counts.push(bin.count); } @@ -1237,11 +1241,7 @@ fn ensure_finite(value: T) -> Result<(), HistogramError> where T: HistogramSupport, { - if value.is_finite() { - Ok(()) - } else { - Err(HistogramError::NonFiniteValue) - } + if value.is_finite() { Ok(()) } else { Err(HistogramError::NonFiniteValue) } } #[cfg(test)] @@ -1501,16 +1501,19 @@ mod tests { ); let hist = Histogram::with_bins(&[(..f64::MAX).into()]).unwrap(); assert_eq!( - hist.n_bins(), 2, + hist.n_bins(), + 2, "This histogram should have two bins, since `BinRange`s are always exclusive on the right" ); assert!(Histogram::with_bins(&[(f64::NAN..).into()]).is_err()); assert!(Histogram::with_bins(&[(..f64::NAN).into()]).is_err()); - assert!(Histogram::with_bins(&[ - (0.0..f64::NAN).into(), - (f64::NAN..100.0).into() - ]) - .is_err()); + assert!( + Histogram::with_bins(&[ + (0.0..f64::NAN).into(), + (f64::NAN..100.0).into() + ]) + .is_err() + ); assert!(Histogram::new(&[f64::NAN, 0.0]).is_err()); let hist = Histogram::new(&[i64::MIN]).unwrap(); diff --git a/oximeter/types/src/schema.rs b/oximeter/types/src/schema.rs index 3f0e8beb5c9..c51b4f102af 100644 --- a/oximeter/types/src/schema.rs +++ b/oximeter/types/src/schema.rs @@ -6,12 +6,12 @@ //! Tools for working with schema for fields and timeseries. +use crate::Metric; +use crate::Target; use crate::types::DatumType; use crate::types::FieldType; use crate::types::MetricsError; use crate::types::Sample; -use crate::Metric; -use crate::Target; use chrono::DateTime; use chrono::Utc; use parse_display::Display; diff --git a/oximeter/types/src/traits.rs b/oximeter/types/src/traits.rs index 38088acdb3e..b35c46279bd 100644 --- a/oximeter/types/src/traits.rs +++ b/oximeter/types/src/traits.rs @@ -6,14 +6,14 @@ // Copyright 2024 Oxide Computer Company -use crate::histogram::Histogram; -use crate::types; -use crate::types::{Measurement, Sample}; use crate::DatumType; use crate::Field; use crate::FieldType; use crate::FieldValue; use crate::MetricsError; +use crate::histogram::Histogram; +use crate::types; +use crate::types::{Measurement, Sample}; use bytes::Bytes; use chrono::DateTime; use chrono::Utc; diff --git a/oximeter/types/src/types.rs b/oximeter/types/src/types.rs index 9d9707153cc..515e84ea9bb 100644 --- a/oximeter/types/src/types.rs +++ b/oximeter/types/src/types.rs @@ -6,10 +6,10 @@ // Copyright 2024 Oxide Computer Company -use crate::histogram; -use crate::traits; use crate::Producer; use crate::TimeseriesName; +use crate::histogram; +use crate::traits; use bytes::Bytes; use chrono::DateTime; use chrono::Utc; @@ -1094,7 +1094,6 @@ impl ProducerRegistry { #[cfg(test)] mod tests { - use super::histogram::Histogram; use super::Cumulative; use super::Datum; use super::DatumType; @@ -1105,6 +1104,7 @@ mod tests { use super::Measurement; use super::MetricsError; use super::Sample; + use super::histogram::Histogram; use bytes::Bytes; use std::collections::BTreeMap; use std::net::Ipv4Addr; diff --git a/package/src/bin/omicron-package.rs b/package/src/bin/omicron-package.rs index 2b2d4152847..6bcc520cebc 100644 --- a/package/src/bin/omicron-package.rs +++ b/package/src/bin/omicron-package.rs @@ -4,7 +4,7 @@ //! Utility for bundling target binaries as tarfiles. -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use camino::{Utf8Path, Utf8PathBuf}; use clap::{Parser, Subcommand}; use futures::stream::{self, StreamExt, TryStreamExt}; @@ -24,9 +24,9 @@ use omicron_zone_package::target::TargetMap; use rayon::prelude::*; use ring::digest::{Context as DigestContext, Digest, SHA256}; use sled_hardware::cleanup::cleanup_networking_resources; -use slog::o; use slog::Drain; use slog::Logger; +use slog::o; use slog::{info, warn}; use std::env; use std::fs::create_dir_all; @@ -370,7 +370,9 @@ async fn ensure_package( Ok(()) => break, Err(err) => { attempts_left -= 1; - let msg = format!("Failed to download prebuilt ({attempts_left} attempts remaining)"); + let msg = format!( + "Failed to download prebuilt ({attempts_left} attempts remaining)" + ); progress.set_error_message(msg.into()); if attempts_left == 0 { return Err(err); diff --git a/package/src/cargo_plan.rs b/package/src/cargo_plan.rs index 05ddccdc6a7..cdc5a61f094 100644 --- a/package/src/cargo_plan.rs +++ b/package/src/cargo_plan.rs @@ -7,23 +7,23 @@ use std::collections::BTreeSet; use std::fmt; use std::io::Write; -use anyhow::bail; -use anyhow::ensure; use anyhow::Context; use anyhow::Result; +use anyhow::bail; +use anyhow::ensure; use cargo_metadata::Metadata; use indent_write::io::IndentWriter; use omicron_zone_package::config::PackageMap; use omicron_zone_package::config::PackageName; use omicron_zone_package::package::PackageSource; -use slog::info; use slog::Logger; +use slog::info; use tokio::process::Command; -use crate::config::cargo_features_for_target; use crate::config::BaseConfig; use crate::config::Config; use crate::config::MultiPresetArg; +use crate::config::cargo_features_for_target; /// For a configuration, build a plan: the set of packages, binaries, and /// features to operate on in release and debug modes. @@ -261,11 +261,13 @@ impl fmt::Display for DisplayCargoPlan<'_> { fn command_to_string(command: &Command) -> String { // Use shell-words to join the command and arguments into a single string. - let mut v = vec![command - .as_std() - .get_program() - .to_str() - .expect("program is valid UTF-8")]; + let mut v = vec![ + command + .as_std() + .get_program() + .to_str() + .expect("program is valid UTF-8"), + ]; v.extend( command .as_std() diff --git a/package/src/config.rs b/package/src/config.rs index 9aad0bdef5c..e780dc91b3e 100644 --- a/package/src/config.rs +++ b/package/src/config.rs @@ -2,7 +2,7 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::Utf8Path; use clap::Args; use omicron_zone_package::{ @@ -13,10 +13,10 @@ use omicron_zone_package::{ package::PackageSource, target::TargetMap, }; -use slog::{debug, Logger}; +use slog::{Logger, debug}; use std::{collections::BTreeMap, io::Write, str::FromStr, time::Duration}; -use crate::target::{target_command_help, KnownTarget}; +use crate::target::{KnownTarget, target_command_help}; #[derive(Debug, Args)] pub struct ConfigArgs { diff --git a/package/src/dot.rs b/package/src/dot.rs index 875c6267024..dbc78c8c8ea 100644 --- a/package/src/dot.rs +++ b/package/src/dot.rs @@ -5,10 +5,10 @@ use omicron_zone_package::config::Config; use omicron_zone_package::package::PackageOutput; use omicron_zone_package::package::PackageSource; use omicron_zone_package::target::TargetMap; +use petgraph::Graph; use petgraph::dot::Dot; use petgraph::graph::EdgeReference; use petgraph::graph::NodeIndex; -use petgraph::Graph; use std::collections::BTreeMap; /// A node in our visual representation of the package manifest diff --git a/package/src/target.rs b/package/src/target.rs index 19a5a832a12..ec0b469341e 100644 --- a/package/src/target.rs +++ b/package/src/target.rs @@ -4,7 +4,7 @@ //! Type safety for target parsing -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use clap::ValueEnum; use omicron_zone_package::target::TargetMap; use std::collections::BTreeMap; @@ -175,10 +175,14 @@ impl KnownTarget { ) -> Result { if matches!(image, Image::Trampoline) { if machine.is_some() { - bail!("Trampoline image does not execute the sled agent (do not pass 'machine' flag)"); + bail!( + "Trampoline image does not execute the sled agent (do not pass 'machine' flag)" + ); } if switch.is_some() { - bail!("Trampoline image does not contain switch zone (do not pass 'switch' flag)"); + bail!( + "Trampoline image does not contain switch zone (do not pass 'switch' flag)" + ); } } diff --git a/passwords/benches/argon2.rs b/passwords/benches/argon2.rs index ab57782603e..4c07e9d3773 100644 --- a/passwords/benches/argon2.rs +++ b/passwords/benches/argon2.rs @@ -8,7 +8,7 @@ use argon2::Algorithm; use argon2::Argon2; use argon2::Params; use argon2::Version; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use omicron_passwords::Hasher; use omicron_passwords::Password; diff --git a/passwords/examples/argon2.rs b/passwords/examples/argon2.rs index 3761f33d4f2..936cd7652b4 100644 --- a/passwords/examples/argon2.rs +++ b/passwords/examples/argon2.rs @@ -10,11 +10,11 @@ use argon2::Argon2; use argon2::Params; use argon2::Version; use clap::Parser; -use omicron_passwords::Hasher; -use omicron_passwords::Password; use omicron_passwords::ARGON2_COST_M_KIB; use omicron_passwords::ARGON2_COST_P; use omicron_passwords::ARGON2_COST_T; +use omicron_passwords::Hasher; +use omicron_passwords::Password; /// Quickly check performance of Argon2 hashing with given parameter values /// diff --git a/passwords/src/lib.rs b/passwords/src/lib.rs index 7ab523847a0..1105ff0cd12 100644 --- a/passwords/src/lib.rs +++ b/passwords/src/lib.rs @@ -5,16 +5,16 @@ //! Encapsulates policy, parameters, and low-level implementation of //! password-based authentication for the external API -use argon2::password_hash; use argon2::Argon2; use argon2::PasswordHasher; use argon2::PasswordVerifier; -use password_hash::errors::Error as PasswordHashError; +use argon2::password_hash; pub use password_hash::PasswordHashString; use password_hash::SaltString; -use rand::prelude::ThreadRng; +use password_hash::errors::Error as PasswordHashError; use rand::CryptoRng; use rand::RngCore; +use rand::prelude::ThreadRng; use schemars::JsonSchema; use serde::Deserialize; use serde_with::SerializeDisplay; @@ -310,17 +310,17 @@ fn verify_strength(hash: &PasswordHashString) -> Result<(), String> { #[cfg(test)] mod test { - use super::external_password_argon; - use super::Hasher; - use super::Password; - use super::PasswordTooLongError; use super::ARGON2_COST_M_KIB; use super::ARGON2_COST_P; use super::ARGON2_COST_T; + use super::Hasher; use super::MAX_PASSWORD_LENGTH; + use super::Password; + use super::PasswordTooLongError; + use super::external_password_argon; + use crate::MIN_EXPECTED_PASSWORD_VERIFY_TIME; use crate::parse_phc_hash; use crate::verify_strength; - use crate::MIN_EXPECTED_PASSWORD_VERIFY_TIME; use argon2::password_hash::PasswordHashString; use argon2::password_hash::SaltString; use rand::SeedableRng; @@ -391,18 +391,24 @@ mod test { assert!(hasher.verify_password(&password, &hash_str).unwrap()); assert!(!hasher.verify_password(&bad_password, &hash_str).unwrap()); let time_elapsed = start.elapsed(); - assert!(!hasher - .verify_password(&Password::new("hunter22").unwrap(), &hash_str) - .unwrap()); - assert!(!hasher - .verify_password(&Password::new("").unwrap(), &hash_str) - .unwrap()); - assert!(!hasher - .verify_password( - &Password::new(&"o".repeat(512)).unwrap(), - &hash_str - ) - .unwrap()); + assert!( + !hasher + .verify_password(&Password::new("hunter22").unwrap(), &hash_str) + .unwrap() + ); + assert!( + !hasher + .verify_password(&Password::new("").unwrap(), &hash_str) + .unwrap() + ); + assert!( + !hasher + .verify_password( + &Password::new(&"o".repeat(512)).unwrap(), + &hash_str + ) + .unwrap() + ); // Verifies that password hash verification takes as long as we think it // does. As of this writing, it's calibrated to take at least one @@ -527,11 +533,13 @@ mod test { let password = Password::new(PASSWORD_STR).unwrap(); let password_hash_str = hasher.create_password(&password).unwrap(); verify_strength(&password_hash_str).unwrap(); - assert!(argon2alt::verify_encoded( - password_hash_str.as_ref(), - PASSWORD_STR.as_bytes() - ) - .unwrap()); + assert!( + argon2alt::verify_encoded( + password_hash_str.as_ref(), + PASSWORD_STR.as_bytes() + ) + .unwrap() + ); // Now, verify that a password hashed with the alternate implementation // can be verified with ours. @@ -542,12 +550,14 @@ mod test { &argon2alt::Config::default(), ) .unwrap(); - assert!(hasher - .verify_password( - &Password::new(BAD_PASSWORD_STR).unwrap(), - &PasswordHashString::new(&alt_hashed).unwrap() - ) - .unwrap()); + assert!( + hasher + .verify_password( + &Password::new(BAD_PASSWORD_STR).unwrap(), + &PasswordHashString::new(&alt_hashed).unwrap() + ) + .unwrap() + ); // This isn't really necessary, but again, since this is easy to do: // check that the two implementations produce the exact same result diff --git a/range-requests/src/lib.rs b/range-requests/src/lib.rs index e6e6945e604..44aa999fb31 100644 --- a/range-requests/src/lib.rs +++ b/range-requests/src/lib.rs @@ -6,8 +6,8 @@ use dropshot::Body; use futures::TryStreamExt; use http::HeaderValue; use hyper::{ - header::{ACCEPT_RANGES, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE}, Response, StatusCode, + header::{ACCEPT_RANGES, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE}, }; const ACCEPT_RANGES_BYTES: http::HeaderValue = @@ -458,10 +458,12 @@ mod test { // Validates the data matches an incrementing Vec of u8 values async fn expect_data( - body: &mut (dyn http_body::Body< + body: &mut ( + dyn http_body::Body< Data = Bytes, Error = Box, - > + Unpin), + > + Unpin + ), start: u8, length: u8, ) { diff --git a/rustfmt.toml b/rustfmt.toml index 41d1d58bb70..2a1f85b6402 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -4,3 +4,4 @@ max_width = 80 use_small_heuristics = "max" edition = "2021" +style_edition = "2024" diff --git a/sled-agent/src/artifact_store.rs b/sled-agent/src/artifact_store.rs index 0ec7fb68f11..7e81af1dcc1 100644 --- a/sled-agent/src/artifact_store.rs +++ b/sled-agent/src/artifact_store.rs @@ -35,7 +35,7 @@ use sled_agent_api::ArtifactPutResponse; use sled_storage::dataset::M2_ARTIFACT_DATASET; use sled_storage::error::Error as StorageError; use sled_storage::manager::StorageHandle; -use slog::{error, info, Logger}; +use slog::{Logger, error, info}; use slog_error_chain::{InlineErrorChain, SlogInlineError}; use tokio::fs::{File, OpenOptions}; use tokio::io::AsyncWriteExt; @@ -259,11 +259,7 @@ impl ArtifactStore { } } } - if any_datasets { - Ok(map) - } else { - Err(Error::NoUpdateDataset) - } + if any_datasets { Ok(map) } else { Err(Error::NoUpdateDataset) } } /// Common implementation for all artifact write operations that creates @@ -803,12 +799,9 @@ mod test { .await .unwrap(); // list lists the file - assert!(store - .list() - .await - .unwrap() - .into_iter() - .eq([(TEST_HASH, 2)])); + assert!( + store.list().await.unwrap().into_iter().eq([(TEST_HASH, 2)]) + ); // get succeeds, file reads back OK let mut file = store.get(TEST_HASH).await.unwrap(); let mut vec = Vec::new(); diff --git a/sled-agent/src/bin/sled-agent-sim.rs b/sled-agent/src/bin/sled-agent-sim.rs index b461df9b1d6..164fcac966c 100644 --- a/sled-agent/src/bin/sled-agent-sim.rs +++ b/sled-agent/src/bin/sled-agent-sim.rs @@ -6,19 +6,19 @@ // TODO see the TODO for nexus. -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use camino::Utf8PathBuf; use clap::Parser; use dropshot::ConfigDropshot; use dropshot::ConfigLogging; use dropshot::ConfigLoggingLevel; use omicron_common::api::internal::nexus::Certificate; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use omicron_sled_agent::sim::RssArgs; use omicron_sled_agent::sim::{ - run_standalone_server, Config, ConfigHardware, ConfigStorage, ConfigZpool, - SimMode, ZpoolConfig, + Config, ConfigHardware, ConfigStorage, ConfigZpool, SimMode, ZpoolConfig, + run_standalone_server, }; use omicron_uuid_kinds::SledUuid; use sled_hardware_types::Baseboard; @@ -126,22 +126,23 @@ async fn do_run() -> Result<(), CmdError> { ) }; - let tls_certificate = - match (args.rss_tls_cert, args.rss_tls_key) { - (None, None) => None, - (Some(cert_path), Some(key_path)) => { - let cert_bytes = std::fs::read_to_string(&cert_path) - .with_context(|| format!("read {:?}", &cert_path)) - .map_err(CmdError::Failure)?; - let key_bytes = std::fs::read_to_string(&key_path) - .with_context(|| format!("read {:?}", &key_path)) - .map_err(CmdError::Failure)?; - Some(Certificate { cert: cert_bytes, key: key_bytes }) - } - _ => return Err(CmdError::Usage(String::from( + let tls_certificate = match (args.rss_tls_cert, args.rss_tls_key) { + (None, None) => None, + (Some(cert_path), Some(key_path)) => { + let cert_bytes = std::fs::read_to_string(&cert_path) + .with_context(|| format!("read {:?}", &cert_path)) + .map_err(CmdError::Failure)?; + let key_bytes = std::fs::read_to_string(&key_path) + .with_context(|| format!("read {:?}", &key_path)) + .map_err(CmdError::Failure)?; + Some(Certificate { cert: cert_bytes, key: key_bytes }) + } + _ => { + return Err(CmdError::Usage(String::from( "--rss-tls-key and --rss-tls-cert must be specified together", - ))), - }; + ))); + } + }; let rss_args = RssArgs { nexus_external_addr: args.rss_nexus_external_addr, diff --git a/sled-agent/src/bin/sled-agent.rs b/sled-agent/src/bin/sled-agent.rs index 446103e982b..93a93ac5019 100644 --- a/sled-agent/src/bin/sled-agent.rs +++ b/sled-agent/src/bin/sled-agent.rs @@ -7,10 +7,10 @@ use anyhow::anyhow; use camino::Utf8PathBuf; use clap::Parser; -use omicron_common::cmd::fatal; use omicron_common::cmd::CmdError; -use omicron_sled_agent::bootstrap::server as bootstrap_server; +use omicron_common::cmd::fatal; use omicron_sled_agent::bootstrap::RssAccessError; +use omicron_sled_agent::bootstrap::server as bootstrap_server; use omicron_sled_agent::config::Config as SledConfig; use sled_agent_types::rack_init::RackInitializeRequest; diff --git a/sled-agent/src/bin/zone-bundle.rs b/sled-agent/src/bin/zone-bundle.rs index e420644b524..561dcc18c54 100644 --- a/sled-agent/src/bin/zone-bundle.rs +++ b/sled-agent/src/bin/zone-bundle.rs @@ -4,9 +4,9 @@ //! Small CLI to view and inspect zone bundles from the sled agent. +use anyhow::Context; use anyhow::anyhow; use anyhow::bail; -use anyhow::Context; use bytes::Buf; use bytes::BufMut; use bytes::BytesMut; @@ -17,11 +17,11 @@ use clap::Parser; use clap::Subcommand; use futures::stream::StreamExt; use omicron_common::address::SLED_AGENT_PORT; +use sled_agent_client::Client; use sled_agent_client::types::CleanupContextUpdate; use sled_agent_client::types::Duration; use sled_agent_client::types::PriorityDimension; use sled_agent_client::types::PriorityOrder; -use sled_agent_client::Client; use slog::Drain; use slog::Level; use slog::LevelFilter; @@ -455,7 +455,9 @@ async fn main() -> anyhow::Result<()> { [PriorityDimension; EXPECTED_DIMENSIONS], _, > = pri.try_into() else { - bail!("must provide {EXPECTED_DIMENSIONS} priority dimensions"); + bail!( + "must provide {EXPECTED_DIMENSIONS} priority dimensions" + ); }; Some(PriorityOrder::from(arr)) } diff --git a/sled-agent/src/boot_disk_os_writer.rs b/sled-agent/src/boot_disk_os_writer.rs index e8b89446ae2..4d718ffb908 100644 --- a/sled-agent/src/boot_disk_os_writer.rs +++ b/sled-agent/src/boot_disk_os_writer.rs @@ -19,8 +19,8 @@ use sha3::Sha3_256; use sled_agent_types::boot_disk::BootDiskOsWriteProgress; use sled_agent_types::boot_disk::BootDiskOsWriteStatus; use slog::Logger; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::io; use std::io::Read; use std::path::Path; @@ -59,7 +59,9 @@ pub(crate) enum BootDiskOsWriteError { TaskPanic, #[error("an update is still running ({0})")] UpdateRunning(Uuid), - #[error("a previous update completed ({0}); clear its status before starting a new update")] + #[error( + "a previous update completed ({0}); clear its status before starting a new update" + )] CannotStartWithoutClearingPreviousStatus(Uuid), #[error("failed to create temporary file")] FailedCreatingTempfile(#[source] io::Error), @@ -67,7 +69,9 @@ pub(crate) enum BootDiskOsWriteError { FailedWritingTempfile(#[source] io::Error), #[error("failed downloading image from HTTP client")] FailedDownloadingImage(#[source] HttpError), - #[error("hash mismatch in image from HTTP client: expected {expected} but got {got}")] + #[error( + "hash mismatch in image from HTTP client: expected {expected} but got {got}" + )] UploadedImageHashMismatch { expected: String, got: String }, #[error("failed to open disk for writing {path}")] FailedOpenDiskForWrite { @@ -75,7 +79,9 @@ pub(crate) enum BootDiskOsWriteError { error: io::Error, path: Utf8PathBuf, }, - #[error("image size ({image_size}) is not a multiple of disk block size ({disk_block_size})")] + #[error( + "image size ({image_size}) is not a multiple of disk block size ({disk_block_size})" + )] ImageSizeNotMultipleOfBlockSize { image_size: usize, disk_block_size: usize, @@ -100,7 +106,9 @@ pub(crate) enum BootDiskOsWriteError { error: io::Error, path: Utf8PathBuf, }, - #[error("hash mismatch after writing disk {path}: expected {expected} but got {got}")] + #[error( + "hash mismatch after writing disk {path}: expected {expected} but got {got}" + )] WrittenImageHashMismatch { path: Utf8PathBuf, expected: String, @@ -788,12 +796,12 @@ mod tests { use rand::RngCore; use std::mem; use std::pin::Pin; - use std::task::ready; use std::task::Context; use std::task::Poll; + use std::task::ready; use std::time::Duration; - use tokio::sync::mpsc; use tokio::sync::Semaphore; + use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_util::sync::PollSemaphore; @@ -930,10 +938,11 @@ mod tests { } #[tokio::test] - async fn boot_disk_os_writer_delivers_upload_progress_and_rejects_bad_hashes( - ) { - let logctx = - test_setup_log("boot_disk_os_writer_delivers_upload_progress_and_rejects_bad_hashes"); + async fn boot_disk_os_writer_delivers_upload_progress_and_rejects_bad_hashes() + { + let logctx = test_setup_log( + "boot_disk_os_writer_delivers_upload_progress_and_rejects_bad_hashes", + ); let writer = Arc::new(BootDiskOsWriter::new(&logctx.log)); let boot_disk = M2Slot::A; diff --git a/sled-agent/src/bootstrap/bootstore_setup.rs b/sled-agent/src/bootstrap/bootstore_setup.rs index ee9a3214742..1b148290104 100644 --- a/sled-agent/src/bootstrap/bootstore_setup.rs +++ b/sled-agent/src/bootstrap/bootstore_setup.rs @@ -12,8 +12,8 @@ use super::server::StartError; use bootstore::schemes::v0 as bootstore; use camino::Utf8PathBuf; use omicron_ddm_admin_client::Client as DdmAdminClient; -use sled_hardware_types::underlay::BootstrapInterface; use sled_hardware_types::Baseboard; +use sled_hardware_types::underlay::BootstrapInterface; use sled_storage::dataset::CLUSTER_DATASET; use sled_storage::resources::AllDisks; use slog::Logger; diff --git a/sled-agent/src/bootstrap/client.rs b/sled-agent/src/bootstrap/client.rs index 7c1622903c2..6a14e0dccb0 100644 --- a/sled-agent/src/bootstrap/client.rs +++ b/sled-agent/src/bootstrap/client.rs @@ -4,9 +4,9 @@ //! Interface for making API requests to a Sled Agent's Bootstrap API. -use super::params::version; use super::params::Request; use super::params::RequestEnvelope; +use super::params::version; use super::views::SledAgentResponse; use crate::bootstrap::views::Response; use crate::bootstrap::views::ResponseEnvelope; @@ -56,7 +56,9 @@ pub enum Error { #[error("Request failed: {0}")] ServerFailure(String), - #[error("Bogus response from server (expected {expected} but received {received})")] + #[error( + "Bogus response from server (expected {expected} but received {received})" + )] InvalidResponse { expected: &'static str, received: &'static str }, } diff --git a/sled-agent/src/bootstrap/early_networking.rs b/sled-agent/src/bootstrap/early_networking.rs index 23c6397b0d7..c0ca96cc660 100644 --- a/sled-agent/src/bootstrap/early_networking.rs +++ b/sled-agent/src/bootstrap/early_networking.rs @@ -4,16 +4,17 @@ //! Network setup required to bring up the control plane -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; +use dpd_client::Client as DpdClient; use dpd_client::types::{ LinkCreate, LinkId, LinkSettings, PortId, PortSettings, TxEq, }; -use dpd_client::Client as DpdClient; use futures::future; use gateway_client::Client as MgsClient; use http::StatusCode; use internal_dns_resolver::{ResolveError, Resolver as DnsResolver}; use internal_dns_types::names::ServiceName; +use mg_admin_client::Client as MgdClient; use mg_admin_client::types::BfdPeerConfig as MgBfdPeerConfig; use mg_admin_client::types::BgpPeerConfig as MgBgpPeerConfig; use mg_admin_client::types::ImportExportPolicy as MgImportExportPolicy; @@ -21,7 +22,7 @@ use mg_admin_client::types::{ AddStaticRoute4Request, ApplyRequest, CheckerSource, Prefix, Prefix4, Prefix6, ShaperSource, StaticRoute4, StaticRoute4List, }; -use mg_admin_client::Client as MgdClient; +use omicron_common::OMICRON_DPD_TAG; use omicron_common::address::DENDRITE_PORT; use omicron_common::address::{MGD_PORT, MGS_PORT}; use omicron_common::api::external::{BfdMode, ImportExportPolicy}; @@ -30,10 +31,9 @@ use omicron_common::api::internal::shared::{ SwitchLocation, }; use omicron_common::backoff::{ - retry_notify, retry_policy_local, BackoffError, ExponentialBackoff, - ExponentialBackoffBuilder, + BackoffError, ExponentialBackoff, ExponentialBackoffBuilder, retry_notify, + retry_policy_local, }; -use omicron_common::OMICRON_DPD_TAG; use omicron_ddm_admin_client::DdmError; use oxnet::IpNet; use slog::Logger; diff --git a/sled-agent/src/bootstrap/http_entrypoints.rs b/sled-agent/src/bootstrap/http_entrypoints.rs index 4e87e94e911..44bd09387ff 100644 --- a/sled-agent/src/bootstrap/http_entrypoints.rs +++ b/sled-agent/src/bootstrap/http_entrypoints.rs @@ -7,15 +7,15 @@ //! Note that the bootstrap agent also communicates over Sprockets, //! and has a separate interface for establishing the trust quorum. -use super::rack_ops::RssAccess; use super::BootstrapError; use super::RssAccessError; +use super::rack_ops::RssAccess; use crate::updates::ConfigUpdates; use crate::updates::UpdateManager; use bootstore::schemes::v0 as bootstore; -use bootstrap_agent_api::bootstrap_agent_api_mod; use bootstrap_agent_api::BootstrapAgentApi; use bootstrap_agent_api::Component; +use bootstrap_agent_api::bootstrap_agent_api_mod; use dropshot::{ ApiDescription, HttpError, HttpResponseOk, HttpResponseUpdatedNoContent, RequestContext, TypedBody, diff --git a/sled-agent/src/bootstrap/pre_server.rs b/sled-agent/src/bootstrap/pre_server.rs index ee72101da23..5e31aed1a5c 100644 --- a/sled-agent/src/bootstrap/pre_server.rs +++ b/sled-agent/src/bootstrap/pre_server.rs @@ -16,15 +16,15 @@ use super::server::StartError; use crate::config::Config; use crate::config::SidecarRevision; use crate::long_running_tasks::{ - spawn_all_longrunning_tasks, LongRunningTaskHandles, + LongRunningTaskHandles, spawn_all_longrunning_tasks, }; use crate::services::ServiceManager; use crate::services::TimeSyncConfig; use crate::sled_agent::SledAgent; use camino::Utf8PathBuf; use cancel_safe_futures::TryStreamExt; -use futures::stream; use futures::StreamExt; +use futures::stream; use illumos_utils::addrobj::AddrObject; use illumos_utils::dladm; use illumos_utils::dladm::Dladm; @@ -32,12 +32,12 @@ use illumos_utils::zfs; use illumos_utils::zfs::Zfs; use illumos_utils::zone; use illumos_utils::zone::Zones; -use omicron_common::address::Ipv6Subnet; use omicron_common::FileKv; +use omicron_common::address::Ipv6Subnet; use omicron_ddm_admin_client::Client as DdmAdminClient; -use sled_hardware::underlay; use sled_hardware::DendriteAsic; use sled_hardware::SledMode; +use sled_hardware::underlay; use sled_hardware_types::underlay::BootstrapInterface; use slog::Drain; use slog::Logger; @@ -318,10 +318,12 @@ fn sled_mode_from_config(config: &Config) -> Result { SidecarRevision::SoftPropolis(_) => { DendriteAsic::SoftNpuPropolisDevice } - _ => return Err(StartError::IncorrectBuildPackaging( - "sled-agent configured to run on softnpu zone but dosen't \ + _ => { + return Err(StartError::IncorrectBuildPackaging( + "sled-agent configured to run on softnpu zone but dosen't \ have a softnpu sidecar revision", - )), + )); + } } } else { return Err(StartError::IncorrectBuildPackaging( diff --git a/sled-agent/src/bootstrap/rss_handle.rs b/sled-agent/src/bootstrap/rss_handle.rs index 4a7449eea89..efddfa2aa25 100644 --- a/sled-agent/src/bootstrap/rss_handle.rs +++ b/sled-agent/src/bootstrap/rss_handle.rs @@ -9,11 +9,11 @@ use crate::rack_setup::service::RackSetupService; use crate::rack_setup::service::SetupServiceError; use ::bootstrap_agent_client::Client as BootstrapAgentClient; use bootstore::schemes::v0 as bootstore; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; +use omicron_common::backoff::BackoffError; use omicron_common::backoff::retry_notify; use omicron_common::backoff::retry_policy_local; -use omicron_common::backoff::BackoffError; use sled_agent_types::rack_init::RackInitializeRequest; use sled_agent_types::rack_ops::RssStep; use sled_agent_types::sled::StartSledAgentRequest; diff --git a/sled-agent/src/bootstrap/secret_retriever.rs b/sled-agent/src/bootstrap/secret_retriever.rs index 1d5ac10ac5f..b45d0026b96 100644 --- a/sled-agent/src/bootstrap/secret_retriever.rs +++ b/sled-agent/src/bootstrap/secret_retriever.rs @@ -171,11 +171,7 @@ impl LrtqOrHardcodedSecretRetrieverInner { } pub fn is_hardcoded(&self) -> bool { - if let Self::Hardcoded(_) = self { - true - } else { - false - } + if let Self::Hardcoded(_) = self { true } else { false } } } diff --git a/sled-agent/src/bootstrap/server.rs b/sled-agent/src/bootstrap/server.rs index d9ad4d9ddf1..93138d0e27a 100644 --- a/sled-agent/src/bootstrap/server.rs +++ b/sled-agent/src/bootstrap/server.rs @@ -4,11 +4,11 @@ //! Server API for bootstrap-related functionality. +use super::BootstrapError; +use super::RssAccessError; use super::config::BOOTSTRAP_AGENT_HTTP_PORT; use super::http_entrypoints; use super::views::SledAgentResponse; -use super::BootstrapError; -use super::RssAccessError; use crate::bootstrap::config::BOOTSTRAP_AGENT_RACK_INIT_PORT; use crate::bootstrap::http_entrypoints::BootstrapServerContext; use crate::bootstrap::maghemite; @@ -33,7 +33,7 @@ use illumos_utils::zfs; use illumos_utils::zone; use illumos_utils::zone::Zones; use internal_dns_resolver::Resolver; -use omicron_common::address::{Ipv6Subnet, AZ_PREFIX}; +use omicron_common::address::{AZ_PREFIX, Ipv6Subnet}; use omicron_common::ledger; use omicron_common::ledger::Ledger; use omicron_ddm_admin_client::Client as DdmAdminClient; diff --git a/sled-agent/src/bootstrap/sprockets_server.rs b/sled-agent/src/bootstrap/sprockets_server.rs index bb7f10d7524..17eb51eb48b 100644 --- a/sled-agent/src/bootstrap/sprockets_server.rs +++ b/sled-agent/src/bootstrap/sprockets_server.rs @@ -4,17 +4,17 @@ //! Server for sprockets-secured requests over the bootstrap network. -use crate::bootstrap::params::version; use crate::bootstrap::params::Request; use crate::bootstrap::params::RequestEnvelope; +use crate::bootstrap::params::version; use crate::bootstrap::views::Response; use crate::bootstrap::views::ResponseEnvelope; use crate::bootstrap::views::SledAgentResponse; use sled_agent_types::sled::StartSledAgentRequest; use slog::Logger; +use sprockets_tls::Stream; use sprockets_tls::keys::SprocketsConfig; use sprockets_tls::server::Server; -use sprockets_tls::Stream; use std::io; use std::net::SocketAddrV6; use tokio::io::AsyncReadExt; diff --git a/sled-agent/src/config.rs b/sled-agent/src/config.rs index 60e465745a5..b281ebf358a 100644 --- a/sled-agent/src/config.rs +++ b/sled-agent/src/config.rs @@ -8,14 +8,14 @@ use crate::updates::ConfigUpdates; use camino::{Utf8Path, Utf8PathBuf}; use dropshot::ConfigDropshot; use dropshot::ConfigLogging; +use illumos_utils::dladm::CHELSIO_LINK_PREFIX; use illumos_utils::dladm::Dladm; use illumos_utils::dladm::FindPhysicalLinkError; use illumos_utils::dladm::PhysicalLink; -use illumos_utils::dladm::CHELSIO_LINK_PREFIX; use omicron_common::vlan::VlanID; use serde::Deserialize; -use sled_hardware::is_gimlet; use sled_hardware::UnparsedDisk; +use sled_hardware::is_gimlet; use sprockets_tls::keys::SprocketsConfig; #[derive(Clone, Debug, Deserialize)] diff --git a/sled-agent/src/dump_setup.rs b/sled-agent/src/dump_setup.rs index b05667691eb..0b6b3ddfdfb 100644 --- a/sled-agent/src/dump_setup.rs +++ b/sled-agent/src/dump_setup.rs @@ -85,11 +85,11 @@ use async_trait::async_trait; use camino::Utf8PathBuf; use derive_more::{AsRef, From}; +use illumos_utils::ExecutionError; use illumos_utils::coreadm::{CoreAdm, CoreFileOption}; use illumos_utils::dumpadm::{DumpAdm, DumpContentType}; use illumos_utils::zone::ZONE_PREFIX; use illumos_utils::zpool::{ZpoolHealth, ZpoolName}; -use illumos_utils::ExecutionError; use omicron_common::disk::DiskVariant; use sled_storage::config::MountConfig; use sled_storage::dataset::{CRASH_DATASET, DUMP_DATASET}; @@ -265,7 +265,10 @@ impl DumpSetup { name: name.clone(), }); } else { - warn!(log, "Zpool {name:?} not online, won't attempt to save process core dumps there"); + warn!( + log, + "Zpool {name:?} not online, won't attempt to save process core dumps there" + ); } } } @@ -280,7 +283,10 @@ impl DumpSetup { name: name.clone(), }); } else { - warn!(log, "Zpool {name:?} not online, won't attempt to save kernel core dumps there"); + warn!( + log, + "Zpool {name:?} not online, won't attempt to save kernel core dumps there" + ); } } } @@ -311,7 +317,9 @@ impl DumpSetup { enum ZfsGetError { #[error("Error executing 'zfs get' command: {0}")] IoError(#[from] std::io::Error), - #[error("Output of 'zfs get' was not only not an integer string, it wasn't even UTF-8: {0}")] + #[error( + "Output of 'zfs get' was not only not an integer string, it wasn't even UTF-8: {0}" + )] Utf8(#[from] std::string::FromUtf8Error), #[error("Error parsing output of 'zfs get' command as integer: {0}")] Parse(#[from] std::num::ParseIntError), @@ -639,7 +647,10 @@ impl DumpSetupWorker { if let Some(x) = &self.chosen_debug_dir { if !self.known_debug_dirs.contains(x) { - warn!(self.log, "Previously-chosen debug/dump dir {x:?} no longer exists in our view of reality"); + warn!( + self.log, + "Previously-chosen debug/dump dir {x:?} no longer exists in our view of reality" + ); self.chosen_debug_dir = None; } else { match self @@ -657,19 +668,31 @@ impl DumpSetupWorker { .unwrap_or((false, 0)) .0 }) { - info!(self.log, "Previously-chosen debug/dump dir {x:?} is over usage threshold, choosing a more vacant disk"); + info!( + self.log, + "Previously-chosen debug/dump dir {x:?} is over usage threshold, choosing a more vacant disk" + ); self.chosen_debug_dir = None; } else { - warn!(self.log, "All candidate debug/dump dirs are over usage threshold, removing older archived files"); + warn!( + self.log, + "All candidate debug/dump dirs are over usage threshold, removing older archived files" + ); if let Err(err) = self.cleanup().await { - error!(self.log, "Couldn't clean up any debug/dump dirs, may hit dataset quota in {x:?}: {err:?}"); + error!( + self.log, + "Couldn't clean up any debug/dump dirs, may hit dataset quota in {x:?}: {err:?}" + ); } else { self.chosen_debug_dir = None; } } } Err(err) => { - error!(self.log, "Previously-chosen debug/dump dir {x:?} couldn't be queried for zfs properties! Choosing another. {err:?}"); + error!( + self.log, + "Previously-chosen debug/dump dir {x:?} couldn't be queried for zfs properties! Choosing another. {err:?}" + ); self.chosen_debug_dir = None; } } @@ -677,13 +700,19 @@ impl DumpSetupWorker { } if let Some(x) = &self.chosen_dump_slice { if !self.known_dump_slices.contains(x) { - warn!(self.log, "Previously-chosen dump slice {x:?} no longer exists in our view of reality"); + warn!( + self.log, + "Previously-chosen dump slice {x:?} no longer exists in our view of reality" + ); self.chosen_dump_slice = None; } } if let Some(x) = &self.chosen_core_dir { if !self.known_core_dirs.contains(x) { - warn!(self.log, "Previously-chosen core dir {x:?} no longer exists in our view of reality"); + warn!( + self.log, + "Previously-chosen core dir {x:?} no longer exists in our view of reality" + ); self.chosen_core_dir = None; } } @@ -705,7 +734,10 @@ impl DumpSetupWorker { break; } Err(err) => { - error!(self.log, "Couldn't configure process core dump directory to {core_dir:?}: {err:?}"); + error!( + self.log, + "Couldn't configure process core dump directory to {core_dir:?}: {err:?}" + ); } } } @@ -721,20 +753,32 @@ impl DumpSetupWorker { .await { Ok(true) => { - debug!(self.log, "Dump slice {dump_slice:?} appears to have a valid header; will attempt to savecore"); + debug!( + self.log, + "Dump slice {dump_slice:?} appears to have a valid header; will attempt to savecore" + ); } Ok(false) => { - info!(self.log, "Dump slice {dump_slice:?} appears to have already been saved"); + info!( + self.log, + "Dump slice {dump_slice:?} appears to have already been saved" + ); } Err(err) => { - debug!(self.log, "Dump slice {dump_slice:?} appears to be unused: {err:?}"); + debug!( + self.log, + "Dump slice {dump_slice:?} appears to be unused: {err:?}" + ); } } if let Ok(saved) = self.dumpadm_and_savecore(&dump_slice).await { if let Some(out) = saved { - info!(self.log, "Previous dump on slice {dump_slice:?} saved, configured slice as target for new dumps. {out:?}"); + info!( + self.log, + "Previous dump on slice {dump_slice:?} saved, configured slice as target for new dumps. {out:?}" + ); } self.chosen_dump_slice = Some(dump_slice); break; @@ -759,18 +803,27 @@ impl DumpSetupWorker { .await { Ok(_) => { - info!(self.log, "Using dump device {dump_slice:?} with no savecore destination (no U.2 debug zvol yet)"); + info!( + self.log, + "Using dump device {dump_slice:?} with no savecore destination (no U.2 debug zvol yet)" + ); self.chosen_dump_slice = Some(dump_slice.clone()); break; } Err(err) => { - warn!(self.log, "Could not configure {dump_slice:?} as dump device: {err:?}"); + warn!( + self.log, + "Could not configure {dump_slice:?} as dump device: {err:?}" + ); } } } Ok(true) => { - warn!(self.log, "Not configuring {dump_slice:?} as it appears to contain a dump we cannot yet send to a U.2 debug zvol"); + warn!( + self.log, + "Not configuring {dump_slice:?} as it appears to contain a dump we cannot yet send to a U.2 debug zvol" + ); } Err(err) => { debug!( @@ -805,7 +858,10 @@ impl DumpSetupWorker { } } Err(err) => { - warn!(self.log, "Could not configure {dump_slice:?} as dump device with {debug_dir:?} as savecore destination: {err:?}"); + warn!( + self.log, + "Could not configure {dump_slice:?} as dump device with {debug_dir:?} as savecore destination: {err:?}" + ); } } } @@ -820,7 +876,10 @@ impl DumpSetupWorker { .dumpadm(dump_slice.as_ref(), None) .await { - error!(self.log, "Could not restore dump slice to {dump_slice:?}: {err:?}"); + error!( + self.log, + "Could not restore dump slice to {dump_slice:?}: {err:?}" + ); } } } @@ -853,7 +912,10 @@ impl DumpSetupWorker { ); } } else { - error!(self.log, "Non-UTF8 path found while archiving core dumps: {entry:?}"); + error!( + self.log, + "Non-UTF8 path found while archiving core dumps: {entry:?}" + ); } } } @@ -1010,7 +1072,10 @@ impl DumpSetupWorker { dir_info.push((info, dir)); } Err(err) => { - error!(self.log, "Could not analyze {dir:?} for debug dataset cleanup task: {err:?}"); + error!( + self.log, + "Could not analyze {dir:?} for debug dataset cleanup task: {err:?}" + ); } } } @@ -1030,7 +1095,10 @@ impl DumpSetupWorker { // we continue to the dataset with the next-oldest average age // of files-to-delete in the sorted list. if let Err(err) = tokio::fs::remove_file(&path).await { - error!(self.log, "Couldn't delete {path:?} from debug dataset, skipping {dir:?}. {err:?}"); + error!( + self.log, + "Couldn't delete {path:?} from debug dataset, skipping {dir:?}. {err:?}" + ); continue 'outer; } } @@ -1447,9 +1515,11 @@ mod tests { // but we also have somewhere to unload them, // call dumpadm and savecore. #[tokio::test] - async fn test_savecore_and_dumpadm_invoked_when_slices_occupied_and_dir_is_available( - ) { - let logctx = omicron_test_utils::dev::test_setup_log("test_savecore_and_dumpadm_invoked_when_slices_occupied_and_dir_is_available"); + async fn test_savecore_and_dumpadm_invoked_when_slices_occupied_and_dir_is_available() + { + let logctx = omicron_test_utils::dev::test_setup_log( + "test_savecore_and_dumpadm_invoked_when_slices_occupied_and_dir_is_available", + ); const MOUNTED_EXTERNAL: &str = "oxp_446f6e74-4469-6557-6f6e-646572696e67"; const ZPOOL_MNT: &str = "/path/to/external/zpool"; diff --git a/sled-agent/src/fakes/nexus.rs b/sled-agent/src/fakes/nexus.rs index 1efbf695b36..8a60114acaa 100644 --- a/sled-agent/src/fakes/nexus.rs +++ b/sled-agent/src/fakes/nexus.rs @@ -9,8 +9,8 @@ use dropshot::Body; use dropshot::{ - endpoint, ApiDescription, FreeformBody, HttpError, HttpResponseOk, - HttpResponseUpdatedNoContent, Path, RequestContext, TypedBody, + ApiDescription, FreeformBody, HttpError, HttpResponseOk, + HttpResponseUpdatedNoContent, Path, RequestContext, TypedBody, endpoint, }; use internal_dns_types::config::DnsConfigBuilder; use internal_dns_types::names::ServiceName; diff --git a/sled-agent/src/instance.rs b/sled-agent/src/instance.rs index 39b6ea967e1..1608e45e2dd 100644 --- a/sled-agent/src/instance.rs +++ b/sled-agent/src/instance.rs @@ -25,6 +25,7 @@ use illumos_utils::running_zone::{RunningZone, ZoneBuilderFactory}; use illumos_utils::svc::wait_for_service; use illumos_utils::zone::PROPOLIS_ZONE_PREFIX; use illumos_utils::zpool::ZpoolOrRamdisk; +use omicron_common::NoDebug; use omicron_common::api::internal::nexus::{SledVmmState, VmmRuntimeState}; use omicron_common::api::internal::shared::{ NetworkInterface, ResolvedVpcFirewallRule, SledIdentifiers, SourceNatConfig, @@ -32,14 +33,13 @@ use omicron_common::api::internal::shared::{ use omicron_common::backoff; use omicron_common::backoff::BackoffError; use omicron_common::zpool_name::ZpoolName; -use omicron_common::NoDebug; use omicron_uuid_kinds::{ GenericUuid, InstanceUuid, OmicronZoneUuid, PropolisUuid, }; use propolis_api_types::ErrorCode as PropolisErrorCode; use propolis_client::Client as PropolisClient; -use rand::prelude::IteratorRandom; use rand::SeedableRng; +use rand::prelude::IteratorRandom; use sled_agent_types::instance::*; use sled_agent_types::zone_bundle::{ZoneBundleCause, ZoneBundleMetadata}; use sled_storage::dataset::ZONE_DATASET; @@ -905,6 +905,7 @@ impl InstanceRunner { // platform library in Nexus. use propolis_client::{ + PciPath, SpecKey, types::{ BlobStorageBackend, Board, BootOrderEntry, BootSettings, Chipset, ComponentV0, CrucibleStorageBackend, @@ -912,7 +913,6 @@ impl InstanceRunner { ReplacementComponent, SerialPort, SerialPortNumber, VirtioDisk, VirtioNetworkBackend, VirtioNic, }, - PciPath, SpecKey, }; // Define some local helper structs for unpacking hardware descriptions @@ -2252,20 +2252,20 @@ mod tests { use camino_tempfile::Utf8TempDir; use dns_server::TransientServer; use dropshot::HttpServer; - use illumos_utils::dladm::MockDladm; use illumos_utils::dladm::__mock_MockDladm::__create_vnic::Context as MockDladmCreateVnicContext; use illumos_utils::dladm::__mock_MockDladm::__delete_vnic::Context as MockDladmDeleteVnicContext; + use illumos_utils::dladm::MockDladm; use illumos_utils::svc::__wait_for_service::Context as MockWaitForServiceContext; - use illumos_utils::zone::MockZones; use illumos_utils::zone::__mock_MockZones::__boot::Context as MockZonesBootContext; use illumos_utils::zone::__mock_MockZones::__id::Context as MockZonesIdContext; + use illumos_utils::zone::MockZones; use internal_dns_resolver::Resolver; + use omicron_common::FileKv; use omicron_common::api::external::{ ByteCount, Generation, Hostname, InstanceCpuCount, }; use omicron_common::api::internal::nexus::{InstanceProperties, VmmState}; use omicron_common::api::internal::shared::{DhcpConfig, SledIdentifiers}; - use omicron_common::FileKv; use sled_agent_types::zone_bundle::CleanupContext; use sled_storage::manager_test_harness::StorageManagerTestHarness; use std::net::Ipv6Addr; @@ -2349,8 +2349,8 @@ mod tests { } } - fn mock_vnic_contexts( - ) -> (MockDladmCreateVnicContext, MockDladmDeleteVnicContext) { + fn mock_vnic_contexts() + -> (MockDladmCreateVnicContext, MockDladmDeleteVnicContext) { let create_vnic_ctx = MockDladm::create_vnic_context(); let delete_vnic_ctx = MockDladm::delete_vnic_context(); create_vnic_ctx.expect().return_once( @@ -2369,8 +2369,8 @@ mod tests { // which calls cpapi_instances_put // and calls Instance::setup_propolis_inner, // which creates the zone (which isn't real in these tests, of course) - fn mock_zone_contexts( - ) -> (MockZonesBootContext, MockWaitForServiceContext, MockZonesIdContext) + fn mock_zone_contexts() + -> (MockZonesBootContext, MockWaitForServiceContext, MockZonesIdContext) { let boot_ctx = MockZones::boot_context(); boot_ctx.expect().return_once(|_| Ok(())); @@ -2700,7 +2700,9 @@ mod tests { .. }) = state_rx.borrow().to_owned() { - panic!("Nexus's InstanceState should never have reached running if zone creation timed out"); + panic!( + "Nexus's InstanceState should never have reached running if zone creation timed out" + ); } storage_harness.cleanup().await; @@ -2807,7 +2809,9 @@ mod tests { .. }) = state_rx.borrow().to_owned() { - panic!("Nexus's InstanceState should never have reached running if zone creation timed out"); + panic!( + "Nexus's InstanceState should never have reached running if zone creation timed out" + ); } // Notify the "boot" closure that it can continue, and then wait to diff --git a/sled-agent/src/long_running_tasks.rs b/sled-agent/src/long_running_tasks.rs index 68389ccf433..6475eebad0d 100644 --- a/sled-agent/src/long_running_tasks.rs +++ b/sled-agent/src/long_running_tasks.rs @@ -29,7 +29,7 @@ use sled_hardware::{HardwareManager, SledMode, UnparsedDisk}; use sled_storage::config::MountConfig; use sled_storage::disk::RawSyntheticDisk; use sled_storage::manager::{StorageHandle, StorageManager}; -use slog::{info, Logger}; +use slog::{Logger, info}; use std::net::Ipv6Addr; use tokio::sync::oneshot; diff --git a/sled-agent/src/metrics.rs b/sled-agent/src/metrics.rs index 632e870f6c3..7cc6406ef69 100644 --- a/sled-agent/src/metrics.rs +++ b/sled-agent/src/metrics.rs @@ -8,17 +8,17 @@ use illumos_utils::running_zone::RunningZone; use omicron_common::api::internal::nexus::ProducerEndpoint; use omicron_common::api::internal::nexus::ProducerKind; use omicron_common::api::internal::shared::SledIdentifiers; -use oximeter_instruments::kstat::link::SledDataLink; -use oximeter_instruments::kstat::link::SledDataLinkTarget; use oximeter_instruments::kstat::CollectionDetails; use oximeter_instruments::kstat::Error as KstatError; use oximeter_instruments::kstat::KstatSampler; use oximeter_instruments::kstat::TargetId; +use oximeter_instruments::kstat::link::SledDataLink; +use oximeter_instruments::kstat::link::SledDataLinkTarget; use oximeter_producer::LogConfig; use oximeter_producer::Server as ProducerServer; use slog::Logger; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::net::Ipv6Addr; use std::net::SocketAddr; use std::time::Duration; @@ -196,7 +196,10 @@ async fn metrics_task( .await } Message::TimeSynced { sled_id } => { - assert!(!sled_time_synced, "This message should only be sent once (on first synchronization with NTP)"); + assert!( + !sled_time_synced, + "This message should only be sent once (on first synchronization with NTP)" + ); if sled_id == sled_identifiers.sled_id { sled_time_synced = true; sync_sled_datalinks( diff --git a/sled-agent/src/nexus.rs b/sled-agent/src/nexus.rs index fbacdce1136..3faeed749bb 100644 --- a/sled-agent/src/nexus.rs +++ b/sled-agent/src/nexus.rs @@ -15,8 +15,8 @@ use sled_hardware::HardwareManager; use slog::Logger; use std::net::SocketAddrV6; use std::sync::Arc; -use tokio::sync::{broadcast, mpsc, oneshot, Notify}; -use tokio::time::{interval, Duration, MissedTickBehavior}; +use tokio::sync::{Notify, broadcast, mpsc, oneshot}; +use tokio::time::{Duration, MissedTickBehavior, interval}; // Re-export the nexus_client::Client crate. (Use a type alias to be more // rust-analyzer friendly.) @@ -550,7 +550,7 @@ mod test { use crate::fakes::nexus::FakeNexusServer; use omicron_test_utils::dev::poll::{ - wait_for_condition as wait_for, CondCheckError, + CondCheckError, wait_for_condition as wait_for, }; use omicron_uuid_kinds::GenericUuid; diff --git a/sled-agent/src/probe_manager.rs b/sled-agent/src/probe_manager.rs index 74ca4942ce2..7635e1ca854 100644 --- a/sled-agent/src/probe_manager.rs +++ b/sled-agent/src/probe_manager.rs @@ -1,6 +1,6 @@ use crate::metrics::MetricsRequestQueue; use crate::nexus::NexusClient; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use illumos_utils::dladm::Etherstub; use illumos_utils::link::VnicAllocator; use illumos_utils::opte::{DhcpCfg, PortCreateParams, PortManager}; @@ -18,12 +18,12 @@ use omicron_common::api::internal::shared::{ NetworkInterface, ResolvedVpcFirewallRule, }; use omicron_uuid_kinds::{GenericUuid, OmicronZoneUuid}; -use rand::prelude::IteratorRandom; use rand::SeedableRng; +use rand::prelude::IteratorRandom; use sled_storage::dataset::ZONE_DATASET; use sled_storage::manager::StorageHandle; use sled_storage::resources::AllDisks; -use slog::{error, warn, Logger}; +use slog::{Logger, error, warn}; use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -139,11 +139,7 @@ impl ProbeManager { } }; - if !u2_set.contains(probe_pool) { - Some(*id) - } else { - None - } + if !u2_set.contains(probe_pool) { Some(*id) } else { None } }) .collect::>(); diff --git a/sled-agent/src/rack_setup/plan/service.rs b/sled-agent/src/rack_setup/plan/service.rs index 8d5e3223f7d..68b448878d1 100644 --- a/sled-agent/src/rack_setup/plan/service.rs +++ b/sled-agent/src/rack_setup/plan/service.rs @@ -13,17 +13,17 @@ use nexus_sled_agent_shared::inventory::{ Inventory, OmicronZoneDataset, SledRole, }; use nexus_types::deployment::{ - blueprint_zone_type, BlueprintPhysicalDiskConfig, - BlueprintPhysicalDiskDisposition, BlueprintPhysicalDisksConfig, - BlueprintZoneConfig, BlueprintZoneDisposition, BlueprintZoneType, + BlueprintPhysicalDiskConfig, BlueprintPhysicalDiskDisposition, + BlueprintPhysicalDisksConfig, BlueprintZoneConfig, + BlueprintZoneDisposition, BlueprintZoneType, OmicronZoneExternalFloatingAddr, OmicronZoneExternalFloatingIp, - OmicronZoneExternalSnatIp, + OmicronZoneExternalSnatIp, blueprint_zone_type, }; use omicron_common::address::{ - get_sled_address, get_switch_zone_address, Ipv6Subnet, ReservedRackSubnet, - DENDRITE_PORT, DNS_HTTP_PORT, DNS_PORT, MGD_PORT, MGS_PORT, + DENDRITE_PORT, DNS_HTTP_PORT, DNS_PORT, Ipv6Subnet, MGD_PORT, MGS_PORT, NEXUS_INTERNAL_PORT, NTP_PORT, NUM_SOURCE_NAT_PORTS, - RSS_RESERVED_ADDRESSES, SLED_PREFIX, + RSS_RESERVED_ADDRESSES, ReservedRackSubnet, SLED_PREFIX, get_sled_address, + get_switch_zone_address, }; use omicron_common::api::external::{Generation, MacAddr, Vni}; use omicron_common::api::internal::shared::{ @@ -31,7 +31,7 @@ use omicron_common::api::internal::shared::{ SourceNatConfigError, }; use omicron_common::backoff::{ - retry_notify_ext, retry_policy_internal_service_aggressive, BackoffError, + BackoffError, retry_notify_ext, retry_policy_internal_service_aggressive, }; use omicron_common::disk::{ CompressionAlgorithm, DatasetConfig, DatasetKind, DatasetName, @@ -51,7 +51,7 @@ use rand::prelude::SliceRandom; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use sled_agent_client::{ - types as SledAgentTypes, Client as SledAgentClient, Error as SledAgentError, + Client as SledAgentClient, Error as SledAgentError, types as SledAgentTypes, }; use sled_agent_types::rack_init::RackInitializeRequest as Config; use sled_agent_types::sled::StartSledAgentRequest; @@ -363,7 +363,7 @@ impl Plan { _ => { return Err(PlanError::UnexpectedDataset( name.to_string(), - )) + )); } }; diff --git a/sled-agent/src/rack_setup/service.rs b/sled-agent/src/rack_setup/service.rs index e21d1c8e1ce..b472cad4af0 100644 --- a/sled-agent/src/rack_setup/service.rs +++ b/sled-agent/src/rack_setup/service.rs @@ -77,7 +77,7 @@ use crate::rack_setup::plan::service::{ Plan as ServicePlan, PlanError as ServicePlanError, }; use crate::rack_setup::plan::sled::Plan as SledPlan; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use bootstore::schemes::v0 as bootstore; use camino::Utf8PathBuf; use chrono::Utc; @@ -85,15 +85,15 @@ use dns_service_client::DnsError; use internal_dns_resolver::Resolver as DnsResolver; use internal_dns_types::names::ServiceName; use nexus_client::{ - types as NexusTypes, Client as NexusClient, Error as NexusError, + Client as NexusClient, Error as NexusError, types as NexusTypes, }; use nexus_sled_agent_shared::inventory::{ OmicronZoneConfig, OmicronZoneType, OmicronZonesConfig, }; use nexus_types::deployment::{ - blueprint_zone_type, id_map::IdMap, Blueprint, BlueprintDatasetConfig, - BlueprintDatasetDisposition, BlueprintDatasetsConfig, BlueprintZoneType, - BlueprintZonesConfig, CockroachDbPreserveDowngrade, + Blueprint, BlueprintDatasetConfig, BlueprintDatasetDisposition, + BlueprintDatasetsConfig, BlueprintZoneType, BlueprintZonesConfig, + CockroachDbPreserveDowngrade, blueprint_zone_type, id_map::IdMap, }; use nexus_types::external_api::views::SledState; use omicron_common::address::get_sled_address; @@ -101,7 +101,7 @@ use omicron_common::api::external::Generation; use omicron_common::api::internal::shared::ExternalPortDiscovery; use omicron_common::api::internal::shared::LldpAdminStatus; use omicron_common::backoff::{ - retry_notify, retry_policy_internal_service_aggressive, BackoffError, + BackoffError, retry_notify, retry_policy_internal_service_aggressive, }; use omicron_common::disk::{ DatasetKind, DatasetsConfig, OmicronPhysicalDisksConfig, @@ -114,7 +114,7 @@ use omicron_uuid_kinds::SledUuid; use omicron_uuid_kinds::ZpoolUuid; use serde::{Deserialize, Serialize}; use sled_agent_client::{ - types as SledAgentTypes, Client as SledAgentClient, Error as SledAgentError, + Client as SledAgentClient, Error as SledAgentError, types as SledAgentTypes, }; use sled_agent_types::early_networking::{ EarlyNetworkConfig, EarlyNetworkConfigBody, @@ -129,7 +129,7 @@ use sled_hardware_types::underlay::BootstrapInterface; use sled_storage::dataset::CONFIG_DATASET; use sled_storage::manager::StorageHandle; use slog::Logger; -use std::collections::{btree_map, BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, btree_map}; use std::collections::{HashMap, HashSet}; use std::iter; use std::net::SocketAddrV6; @@ -1722,7 +1722,7 @@ mod test { OmicronZonesConfig, SledRole, }; use omicron_common::{ - address::{get_sled_address, Ipv6Subnet, SLED_PREFIX}, + address::{Ipv6Subnet, SLED_PREFIX, get_sled_address}, api::external::{ByteCount, Generation}, disk::{DiskIdentity, DiskVariant}, }; diff --git a/sled-agent/src/services.rs b/sled-agent/src/services.rs index f1033aa8a15..1296ffffdfd 100644 --- a/sled-agent/src/services.rs +++ b/sled-agent/src/services.rs @@ -25,10 +25,10 @@ //! - [ServiceManager::activate_switch] exposes an API to specifically enable //! or disable (via [ServiceManager::deactivate_switch]) the switch zone. +use crate::bootstrap::BootstrapNetworking; use crate::bootstrap::early_networking::{ EarlyNetworkSetup, EarlyNetworkSetupError, }; -use crate::bootstrap::BootstrapNetworking; use crate::config::SidecarRevision; use crate::metrics::MetricsRequestQueue; use crate::params::{DendriteAsic, OmicronZoneConfigExt, OmicronZoneTypeExt}; @@ -41,7 +41,7 @@ use clickhouse_admin_types::CLICKHOUSE_KEEPER_CONFIG_DIR; use clickhouse_admin_types::CLICKHOUSE_KEEPER_CONFIG_FILE; use clickhouse_admin_types::CLICKHOUSE_SERVER_CONFIG_DIR; use clickhouse_admin_types::CLICKHOUSE_SERVER_CONFIG_FILE; -use dpd_client::{types as DpdTypes, Client as DpdClient, Error as DpdError}; +use dpd_client::{Client as DpdClient, Error as DpdError, types as DpdTypes}; use dropshot::HandlerTaskMode; use illumos_utils::addrobj::AddrObject; use illumos_utils::addrobj::IPV6_LINK_LOCAL_ADDROBJ_NAME; @@ -60,7 +60,7 @@ use illumos_utils::smf_helper::SmfHelper; use illumos_utils::zfs::ZONE_ZFS_RAMDISK_DATASET_MOUNTPOINT; use illumos_utils::zone::AddressRequest; use illumos_utils::zpool::{PathInPool, ZpoolName, ZpoolOrRamdisk}; -use illumos_utils::{execute, PFEXEC}; +use illumos_utils::{PFEXEC, execute}; use internal_dns_resolver::Resolver; use internal_dns_types::names::BOUNDARY_NTP_DNS_NAME; use internal_dns_types::names::DNS_ZONE; @@ -79,18 +79,18 @@ use omicron_common::address::SLED_PREFIX; use omicron_common::address::TFPORTD_PORT; use omicron_common::address::WICKETD_NEXUS_PROXY_PORT; use omicron_common::address::WICKETD_PORT; +use omicron_common::address::{BOOTSTRAP_ARTIFACT_PORT, COCKROACH_ADMIN_PORT}; use omicron_common::address::{ - get_internal_dns_server_addresses, CLICKHOUSE_ADMIN_PORT, - CLICKHOUSE_TCP_PORT, + CLICKHOUSE_ADMIN_PORT, CLICKHOUSE_TCP_PORT, + get_internal_dns_server_addresses, }; use omicron_common::address::{Ipv6Subnet, NEXUS_TECHPORT_EXTERNAL_PORT}; -use omicron_common::address::{BOOTSTRAP_ARTIFACT_PORT, COCKROACH_ADMIN_PORT}; use omicron_common::api::external::Generation; use omicron_common::api::internal::shared::{ HostPortConfig, RackNetworkConfig, SledIdentifiers, }; use omicron_common::backoff::{ - retry_notify, retry_policy_internal_service_aggressive, BackoffError, + BackoffError, retry_notify, retry_policy_internal_service_aggressive, }; use omicron_common::disk::{DatasetKind, DatasetName}; use omicron_common::ledger::{self, Ledger, Ledgerable}; @@ -101,9 +101,9 @@ use sled_agent_types::{ time_sync::TimeSync, zone_bundle::{ZoneBundleCause, ZoneBundleMetadata}, }; +use sled_hardware::SledMode; use sled_hardware::is_gimlet; use sled_hardware::underlay; -use sled_hardware::SledMode; use sled_hardware_types::Baseboard; use sled_storage::config::MountConfig; use sled_storage::dataset::{CONFIG_DATASET, INSTALL_DATASET, ZONE_DATASET}; @@ -117,7 +117,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use tokio::io::AsyncWriteExt; use tokio::sync::Mutex; -use tokio::sync::{oneshot, MutexGuard}; +use tokio::sync::{MutexGuard, oneshot}; use tokio::task::JoinHandle; use uuid::Uuid; @@ -246,7 +246,9 @@ pub enum Error { source: illumos_utils::zfs::GetValueError, }, - #[error("Cannot launch {zone} with {dataset} (saw {prop_name} = {prop_value}, expected {prop_value_expected})")] + #[error( + "Cannot launch {zone} with {dataset} (saw {prop_name} = {prop_value}, expected {prop_value_expected})" + )] DatasetNotReady { zone: String, dataset: String, @@ -2827,12 +2829,14 @@ impl ServiceManager { ref s, ) => s, _ => { - return Err(Error::SidecarRevision( - anyhow::anyhow!( - "expected soft sidecar \ - revision" + return Err( + Error::SidecarRevision( + anyhow::anyhow!( + "expected soft \ + sidecar revision" + ), ), - )) + ); } }; @@ -4025,7 +4029,7 @@ impl ServiceManager { SledMode::Gimlet => { return Err(Error::SwitchZone(anyhow::anyhow!( "attempted to activate switch zone on non-scrimlet sled" - ))) + ))); } // Sled is a scrimlet and the real tofino driver has been loaded. @@ -4490,7 +4494,10 @@ impl ServiceManager { } } smfh.refresh()?; - info!(self.inner.log, "refreshed dendrite service with new configuration") + info!( + self.inner.log, + "refreshed dendrite service with new configuration" + ) } SwitchService::Wicketd { .. } => { if let Some(&address) = first_address { @@ -4508,7 +4515,10 @@ impl ServiceManager { )?; smfh.refresh()?; - info!(self.inner.log, "refreshed wicketd service with new configuration") + info!( + self.inner.log, + "refreshed wicketd service with new configuration" + ) } else { error!( self.inner.log, @@ -4530,7 +4540,10 @@ impl ServiceManager { )?; } smfh.refresh()?; - info!(self.inner.log, "refreshed lldpd service with new configuration") + info!( + self.inner.log, + "refreshed lldpd service with new configuration" + ) } SwitchService::Tfport { pkt_source, asic } => { info!(self.inner.log, "configuring tfport service"); @@ -4566,7 +4579,10 @@ impl ServiceManager { } smfh.refresh()?; - info!(self.inner.log, "refreshed tfport service with new configuration") + info!( + self.inner.log, + "refreshed tfport service with new configuration" + ) } SwitchService::Pumpkind { .. } => { // Unless we want to plumb through the "only log @@ -4660,7 +4676,10 @@ impl ServiceManager { } } smfh.refresh()?; - info!(self.inner.log, "refreshed mg-ddm service with new configuration") + info!( + self.inner.log, + "refreshed mg-ddm service with new configuration" + ) } } } @@ -4932,7 +4951,7 @@ mod illumos_tests { use super::*; use illumos_utils::{ dladm::{ - Etherstub, MockDladm, BOOTSTRAP_ETHERSTUB_NAME, + BOOTSTRAP_ETHERSTUB_NAME, Etherstub, MockDladm, UNDERLAY_ETHERSTUB_NAME, UNDERLAY_ETHERSTUB_VNIC_NAME, }, svc, diff --git a/sled-agent/src/sim/collection.rs b/sled-agent/src/sim/collection.rs index d75081f1e4c..bf3c08f1e91 100644 --- a/sled-agent/src/sim/collection.rs +++ b/sled-agent/src/sim/collection.rs @@ -594,10 +594,9 @@ mod test { info!(logctx.log, "new instance"; "state" => ?r1); assert_eq!(r1.vmm_state.state, VmmState::Starting); assert_eq!(r1.vmm_state.gen, Generation::new()); - assert!(instance - .transition(VmmStateRequested::Running) - .unwrap() - .is_none()); + assert!( + instance.transition(VmmStateRequested::Running).unwrap().is_none() + ); instance.transition_finish(); let (rprev, rnext) = (r1, instance.object.current()); @@ -610,10 +609,9 @@ mod test { // Now reboot the instance. This is dispatched to Propolis, which will // move to the Rebooting state and then back to Running. - assert!(instance - .transition(VmmStateRequested::Reboot) - .unwrap() - .is_none()); + assert!( + instance.transition(VmmStateRequested::Reboot).unwrap().is_none() + ); let (rprev, rnext) = (rnext, instance.object.current()); assert!(rnext.vmm_state.gen > rprev.vmm_state.gen); assert!(rnext.vmm_state.time_updated > rprev.vmm_state.time_updated); @@ -693,10 +691,11 @@ mod test { let id = uuid::Uuid::new_v4(); let rprev = r1; assert!(!rprev.disk_state.is_attached()); - assert!(disk - .transition(DiskStateRequested::Attached(id)) - .unwrap() - .is_none()); + assert!( + disk.transition(DiskStateRequested::Attached(id)) + .unwrap() + .is_none() + ); let rnext = disk.object.current(); assert!(rnext.gen > rprev.gen); assert!(rnext.time_updated >= rprev.time_updated); @@ -720,10 +719,11 @@ mod test { let rprev = rnext; // If we go straight to "Attached" again, there's nothing to do. - assert!(disk - .transition(DiskStateRequested::Attached(id)) - .unwrap() - .is_none()); + assert!( + disk.transition(DiskStateRequested::Attached(id)) + .unwrap() + .is_none() + ); let rnext = disk.object.current(); assert_eq!(rnext.gen, rprev.gen); let rprev = rnext; diff --git a/sled-agent/src/sim/disk.rs b/sled-agent/src/sim/disk.rs index 3c87dfb10d5..18d63cfb1ca 100644 --- a/sled-agent/src/sim/disk.rs +++ b/sled-agent/src/sim/disk.rs @@ -32,8 +32,8 @@ use crate::common::disk::{Action as DiskAction, DiskStates}; mod producers { use super::*; use oximeter::{ - types::{Cumulative, Sample}, Metric, Target, + types::{Cumulative, Sample}, }; #[derive(Debug, Clone, Target)] diff --git a/sled-agent/src/sim/http_entrypoints.rs b/sled-agent/src/sim/http_entrypoints.rs index a65d2114f4e..d5dddea7d78 100644 --- a/sled-agent/src/sim/http_entrypoints.rs +++ b/sled-agent/src/sim/http_entrypoints.rs @@ -7,7 +7,6 @@ use super::collection::PokeMode; use crate::support_bundle::storage::SupportBundleQueryType; use camino::Utf8PathBuf; -use dropshot::endpoint; use dropshot::ApiDescription; use dropshot::ErrorStatusCode; use dropshot::FreeformBody; @@ -23,6 +22,7 @@ use dropshot::Query; use dropshot::RequestContext; use dropshot::StreamingBody; use dropshot::TypedBody; +use dropshot::endpoint; use nexus_sled_agent_shared::inventory::SledRole; use nexus_sled_agent_shared::inventory::{Inventory, OmicronZonesConfig}; use omicron_common::api::internal::nexus::DiskRuntimeState; diff --git a/sled-agent/src/sim/http_entrypoints_pantry.rs b/sled-agent/src/sim/http_entrypoints_pantry.rs index 5c8dc9c9361..672f36d1207 100644 --- a/sled-agent/src/sim/http_entrypoints_pantry.rs +++ b/sled-agent/src/sim/http_entrypoints_pantry.rs @@ -5,9 +5,9 @@ //! HTTP entrypoint functions for simulating the crucible pantry API. use dropshot::{ - endpoint, ApiDescription, ApiDescriptionRegisterError, HttpError, + ApiDescription, ApiDescriptionRegisterError, HttpError, HttpResponseDeleted, HttpResponseOk, HttpResponseUpdatedNoContent, - Path as TypedPath, RequestContext, TypedBody, + Path as TypedPath, RequestContext, TypedBody, endpoint, }; use propolis_client::VolumeConstructionRequest; use schemars::JsonSchema; @@ -365,10 +365,10 @@ async fn detach( #[cfg(test)] mod tests { + use guppy::MetadataCommand; use guppy::graph::ExternalSource; use guppy::graph::GitReq; use guppy::graph::PackageGraph; - use guppy::MetadataCommand; use serde_json::Value; use std::path::Path; diff --git a/sled-agent/src/sim/http_entrypoints_storage.rs b/sled-agent/src/sim/http_entrypoints_storage.rs index cb53d96fd11..24a38af7e7d 100644 --- a/sled-agent/src/sim/http_entrypoints_storage.rs +++ b/sled-agent/src/sim/http_entrypoints_storage.rs @@ -9,9 +9,9 @@ use crucible_agent_client::types::{ Snapshot, }; use dropshot::{ - endpoint, ApiDescription, ApiDescriptionRegisterError, HttpError, + ApiDescription, ApiDescriptionRegisterError, HttpError, HttpResponseDeleted, HttpResponseOk, Path as TypedPath, RequestContext, - TypedBody, + TypedBody, endpoint, }; use schemars::JsonSchema; use serde::Deserialize; diff --git a/sled-agent/src/sim/instance.rs b/sled-agent/src/sim/instance.rs index eb7ea0ca794..a739bcb0b25 100644 --- a/sled-agent/src/sim/instance.rs +++ b/sled-agent/src/sim/instance.rs @@ -231,7 +231,7 @@ impl SimInstanceInner { state {:?} (current state: {:?})", self.next_resting_state(), self - ))) + ))); } } } @@ -253,7 +253,7 @@ impl SimInstanceInner { state {:?} (current state: {:?})", self.next_resting_state(), self - ))) + ))); } } } @@ -282,7 +282,7 @@ impl SimInstanceInner { (current state: {:?})", self.next_resting_state(), self - ))) + ))); } }, } @@ -440,9 +440,11 @@ impl Simulatable for SimInstance { type Action = InstanceAction; fn new(current: SledVmmState) -> Self { - assert!(matches!( - current.vmm_state.state, - VmmState::Starting | VmmState::Migrating), + assert!( + matches!( + current.vmm_state.state, + VmmState::Starting | VmmState::Migrating + ), "new VMMs should always be registered in the Starting or Migrating \ state (supplied state: {:?})", current.vmm_state.state diff --git a/sled-agent/src/sim/mod.rs b/sled-agent/src/sim/mod.rs index 5cb7e64461f..ef7915293e8 100644 --- a/sled-agent/src/sim/mod.rs +++ b/sled-agent/src/sim/mod.rs @@ -21,9 +21,9 @@ mod upstairs; pub use crate::updates::ConfigUpdates; pub use config::{ Baseboard, Config, ConfigHardware, ConfigStorage, ConfigZpool, SimMode, - ZpoolConfig, TEST_HARDWARE_THREADS, TEST_RESERVOIR_RAM, + TEST_HARDWARE_THREADS, TEST_RESERVOIR_RAM, ZpoolConfig, }; -pub use server::{run_standalone_server, RssArgs, Server}; +pub use server::{RssArgs, Server, run_standalone_server}; pub use sled_agent::SledAgent; pub use storage::PantryServer; pub(crate) use storage::Storage; diff --git a/sled-agent/src/sim/server.rs b/sled-agent/src/sim/server.rs index f1c7f7e209c..8e1aa9e0a52 100644 --- a/sled-agent/src/sim/server.rs +++ b/sled-agent/src/sim/server.rs @@ -9,31 +9,32 @@ use super::http_entrypoints::api as http_api; use super::sled_agent::SledAgent; use super::storage::PantryServer; use crate::nexus::NexusClient; -use crate::rack_setup::service::build_initial_blueprint_from_sled_configs; use crate::rack_setup::SledConfig; +use crate::rack_setup::service::build_initial_blueprint_from_sled_configs; use crate::rack_setup::{ from_ipaddr_to_external_floating_ip, from_sockaddr_to_external_floating_addr, }; use crate::sim::SimulatedUpstairs; -use anyhow::{anyhow, Context as _}; +use anyhow::{Context as _, anyhow}; use crucible_agent_client::types::State as RegionState; use illumos_utils::zpool::ZpoolName; use internal_dns_types::config::DnsConfigBuilder; -use internal_dns_types::names::ServiceName; use internal_dns_types::names::DNS_ZONE_EXTERNAL_TESTING; +use internal_dns_types::names::ServiceName; use nexus_client::types as NexusTypes; use nexus_client::types::{IpRange, Ipv4Range, Ipv6Range}; use nexus_config::NUM_INITIAL_RESERVED_IP_ADDRESSES; use nexus_sled_agent_shared::inventory::OmicronZoneDataset; use nexus_types::deployment::{ - blueprint_zone_type, BlueprintPhysicalDiskConfig, - BlueprintPhysicalDiskDisposition, BlueprintPhysicalDisksConfig, + BlueprintPhysicalDiskConfig, BlueprintPhysicalDiskDisposition, + BlueprintPhysicalDisksConfig, blueprint_zone_type, }; use nexus_types::deployment::{ BlueprintZoneConfig, BlueprintZoneDisposition, BlueprintZoneType, }; use nexus_types::inventory::NetworkInterfaceKind; +use omicron_common::FileKv; use omicron_common::address::DNS_OPTE_IPV4_SUBNET; use omicron_common::address::NEXUS_OPTE_IPV4_SUBNET; use omicron_common::api::external::Generation; @@ -41,10 +42,9 @@ use omicron_common::api::external::MacAddr; use omicron_common::api::external::Vni; use omicron_common::api::internal::nexus::Certificate; use omicron_common::backoff::{ - retry_notify, retry_policy_internal_service_aggressive, BackoffError, + BackoffError, retry_notify, retry_policy_internal_service_aggressive, }; use omicron_common::disk::DiskIdentity; -use omicron_common::FileKv; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::GenericUuid; use omicron_uuid_kinds::OmicronZoneUuid; @@ -52,7 +52,7 @@ use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::ZpoolUuid; use oxnet::Ipv6Net; use sled_agent_types::rack_init::RecoverySiloConfig; -use slog::{info, Drain, Logger}; +use slog::{Drain, Logger, info}; use std::collections::BTreeMap; use std::collections::HashMap; use std::net::IpAddr; diff --git a/sled-agent/src/sim/sled_agent.rs b/sled-agent/src/sim/sled_agent.rs index bd07db7d5c7..cff6e308d73 100644 --- a/sled-agent/src/sim/sled_agent.rs +++ b/sled-agent/src/sim/sled_agent.rs @@ -13,12 +13,12 @@ use super::storage::CrucibleData; use super::storage::Storage; use crate::artifact_store::ArtifactStore; use crate::nexus::NexusClient; -use crate::sim::simulatable::Simulatable; use crate::sim::SimulatedUpstairs; +use crate::sim::simulatable::Simulatable; use crate::support_bundle::storage::SupportBundleQueryType; use crate::updates::UpdateManager; -use anyhow::bail; use anyhow::Context; +use anyhow::bail; use bytes::Bytes; use dropshot::Body; use dropshot::HttpError; @@ -49,11 +49,11 @@ use omicron_uuid_kinds::{ }; use oxnet::Ipv6Net; use propolis_client::{ + Client as PropolisClient, types::{ Board, Chipset, ComponentV0, InstanceInitializationMethod, InstanceSpecV0, SerialPort, SerialPortNumber, }, - Client as PropolisClient, }; use range_requests::PotentialRange; use sled_agent_api::SupportBundleMetadata; @@ -370,7 +370,7 @@ impl SledAgent { { Ok(instance) => instance, Err(Error::ObjectNotFound { .. }) => { - return Ok(VmmUnregisterResponse { updated_runtime: None }) + return Ok(VmmUnregisterResponse { updated_runtime: None }); } Err(e) => return Err(e), }; @@ -658,7 +658,9 @@ impl SledAgent { false } }) { - return Err(Error::invalid_request("cannot replace existing ephemeral IP without explicit removal")); + return Err(Error::invalid_request( + "cannot replace existing ephemeral IP without explicit removal", + )); } } diff --git a/sled-agent/src/sim/storage.rs b/sled-agent/src/sim/storage.rs index 49dd4def7b5..1ffde9cf36b 100644 --- a/sled-agent/src/sim/storage.rs +++ b/sled-agent/src/sim/storage.rs @@ -8,12 +8,12 @@ //! than the representation of "virtual disks" which would be presented //! through Nexus' external API. +use crate::sim::SimulatedUpstairs; use crate::sim::http_entrypoints_pantry::ExpectedDigest; use crate::sim::http_entrypoints_pantry::PantryStatus; use crate::sim::http_entrypoints_pantry::VolumeStatus; -use crate::sim::SimulatedUpstairs; use crate::support_bundle::storage::SupportBundleManager; -use anyhow::{self, bail, Result}; +use anyhow::{self, Result, bail}; use camino::Utf8Path; use camino_tempfile::Utf8TempDir; use chrono::prelude::*; @@ -436,10 +436,9 @@ mod test { let first_region_port = region.port_number; - assert!(agent - .delete(RegionId(region_id.to_string())) - .unwrap() - .is_some()); + assert!( + agent.delete(RegionId(region_id.to_string())).unwrap().is_some() + ); // Create another region, make sure it gets the same port number, but // don't delete it. @@ -480,10 +479,12 @@ mod test { let third_region_port = third_region.port_number; - assert!(agent - .delete(RegionId(third_region.id.to_string())) - .unwrap() - .is_some()); + assert!( + agent + .delete(RegionId(third_region.id.to_string())) + .unwrap() + .is_some() + ); // Create a running snapshot, make sure it gets the same port number // as the third region did. This ensures that the Crucible agent shares @@ -1383,7 +1384,7 @@ impl StorageInner { return Err(HttpError::for_not_found( None, "Dataset not found".to_string(), - )) + )); } }; } @@ -1450,7 +1451,7 @@ impl StorageInner { return Err(HttpError::for_not_found( None, "Dataset not found".to_string(), - )) + )); } }; } @@ -1494,7 +1495,7 @@ impl StorageInner { return Err(HttpError::for_not_found( None, "Dataset not found".to_string(), - )) + )); } }; } diff --git a/sled-agent/src/sled_agent.rs b/sled-agent/src/sled_agent.rs index 5c00a590844..f4a2da5c4ef 100644 --- a/sled-agent/src/sled_agent.rs +++ b/sled-agent/src/sled_agent.rs @@ -27,8 +27,8 @@ use bootstore::schemes::v0 as bootstore; use camino::Utf8PathBuf; use derive_more::From; use dropshot::HttpError; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; use illumos_utils::opte::PortManager; use illumos_utils::zone::PROPOLIS_ZONE_PREFIX; use illumos_utils::zone::ZONE_PREFIX; @@ -37,7 +37,7 @@ use nexus_sled_agent_shared::inventory::{ OmicronZonesConfig, SledRole, }; use omicron_common::address::{ - get_sled_address, get_switch_zone_address, Ipv6Subnet, SLED_PREFIX, + Ipv6Subnet, SLED_PREFIX, get_sled_address, get_switch_zone_address, }; use omicron_common::api::external::{ByteCount, ByteCountRangeError, Vni}; use omicron_common::api::internal::nexus::{DiskRuntimeState, SledVmmState}; @@ -47,7 +47,7 @@ use omicron_common::api::internal::shared::{ SledIdentifiers, VirtualNetworkInterfaceHost, }; use omicron_common::backoff::{ - retry_notify, retry_policy_internal_service_aggressive, BackoffError, + BackoffError, retry_notify, retry_policy_internal_service_aggressive, }; use omicron_common::disk::{ DatasetsConfig, DatasetsManagementResult, DisksManagementResult, @@ -69,9 +69,9 @@ use sled_agent_types::zone_bundle::{ PriorityOrder, StorageLimit, ZoneBundleMetadata, }; use sled_diagnostics::{SledDiagnosticsCmdError, SledDiagnosticsCmdOutput}; -use sled_hardware::{underlay, HardwareManager}; -use sled_hardware_types::underlay::BootstrapInterface; +use sled_hardware::{HardwareManager, underlay}; use sled_hardware_types::Baseboard; +use sled_hardware_types::underlay::BootstrapInterface; use sled_storage::manager::StorageHandle; use slog::Logger; use sprockets_tls::keys::SprocketsConfig; diff --git a/sled-agent/src/support_bundle/storage.rs b/sled-agent/src/support_bundle/storage.rs index c1b0cfe42f6..765ac5abd09 100644 --- a/sled-agent/src/support_bundle/storage.rs +++ b/sled-agent/src/support_bundle/storage.rs @@ -21,7 +21,7 @@ use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::SupportBundleUuid; use omicron_uuid_kinds::ZpoolUuid; use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; +use rand::{Rng, thread_rng}; use range_requests::PotentialRange; use range_requests::SingleRange; use sha2::{Digest, Sha256}; @@ -64,10 +64,14 @@ pub enum Error { #[error("Dataset not found")] DatasetNotFound, - #[error("Dataset exists, but has an invalid configuration: (wanted {wanted}, saw {actual})")] + #[error( + "Dataset exists, but has an invalid configuration: (wanted {wanted}, saw {actual})" + )] DatasetExistsBadConfig { wanted: DatasetUuid, actual: DatasetUuid }, - #[error("Dataset exists, but appears on the wrong zpool (wanted {wanted}, saw {actual})")] + #[error( + "Dataset exists, but appears on the wrong zpool (wanted {wanted}, saw {actual})" + )] DatasetExistsOnWrongZpool { wanted: ZpoolUuid, actual: ZpoolUuid }, #[error(transparent)] @@ -805,7 +809,7 @@ impl<'a> SupportBundleManager<'a> { // The entry exists, but the requested range is invalid -- // send it back as an http body. ZipStreamOutput::RangeResponse(response) => { - return Ok(response) + return Ok(response); } }; @@ -845,8 +849,8 @@ mod tests { use omicron_test_utils::dev::test_setup_log; use sled_storage::manager_test_harness::StorageManagerTestHarness; use std::collections::BTreeMap; - use zip::write::SimpleFileOptions; use zip::ZipWriter; + use zip::write::SimpleFileOptions; struct SingleU2StorageHarness { storage_test_harness: StorageManagerTestHarness, diff --git a/sled-agent/src/swap_device.rs b/sled-agent/src/swap_device.rs index 7dadf62434e..467d2a0af66 100644 --- a/sled-agent/src/swap_device.rs +++ b/sled-agent/src/swap_device.rs @@ -15,7 +15,9 @@ pub enum SwapDeviceError { #[error("Error listing swap devices: {0}")] ListDevices(String), - #[error("Error adding swap device: {msg} (path=\"{path}\", start={start}, length={length})")] + #[error( + "Error adding swap device: {msg} (path=\"{path}\", start={start}, length={length})" + )] AddDevice { msg: String, path: String, start: u64, length: u64 }, #[error("{msg}: {error}")] @@ -122,7 +124,7 @@ fn zvol_exists(name: &str) -> Result { error: format!( "found dataset \"{}\" for swap device, but it is not a volume", name - ), + ), }); } else { return Ok(true); @@ -225,9 +227,11 @@ fn create_encrypted_swap_zvol( use std::io::Write; let res = stdin.write_all(&secret); if res.is_err() { - error!(child_log, + error!( + child_log, "could not write key to stdin of `zfs create` for swap zvol: {:?}", - res); + res + ); } secret.zeroize(); }); diff --git a/sled-agent/src/vmm_reservoir.rs b/sled-agent/src/vmm_reservoir.rs index 0fa7bc14af3..d1f8a892063 100644 --- a/sled-agent/src/vmm_reservoir.rs +++ b/sled-agent/src/vmm_reservoir.rs @@ -7,8 +7,8 @@ use illumos_utils::vmm_reservoir; use omicron_common::api::external::ByteCount; use slog::Logger; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use std::thread; use tokio::sync::{broadcast, oneshot}; @@ -28,9 +28,7 @@ pub enum Error { #[error("VmmReservoirManager has shutdown")] Shutdown, - #[error( - "Communication error with VmmReservoirManager: ReplySenderDropped" - )] + #[error("Communication error with VmmReservoirManager: ReplySenderDropped")] ReplySenderDropped, } diff --git a/sled-agent/src/zone_bundle.rs b/sled-agent/src/zone_bundle.rs index 853f341c402..2b6bafa8085 100644 --- a/sled-agent/src/zone_bundle.rs +++ b/sled-agent/src/zone_bundle.rs @@ -6,15 +6,15 @@ //! Tools for collecting and inspecting service bundles for zones. -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use camino::FromPathBufError; use camino::Utf8Path; use camino::Utf8PathBuf; use flate2::bufread::GzDecoder; -use illumos_utils::running_zone::is_oxide_smf_log_file; use illumos_utils::running_zone::RunningZone; use illumos_utils::running_zone::ServiceProcess; +use illumos_utils::running_zone::is_oxide_smf_log_file; use illumos_utils::zfs::CreateSnapshotError; use illumos_utils::zfs::DestroyDatasetError; use illumos_utils::zfs::DestroySnapshotError; @@ -24,8 +24,8 @@ use illumos_utils::zfs::ListDatasetsError; use illumos_utils::zfs::ListSnapshotsError; use illumos_utils::zfs::SetValueError; use illumos_utils::zfs::Snapshot; -use illumos_utils::zfs::Zfs; use illumos_utils::zfs::ZFS; +use illumos_utils::zfs::Zfs; use illumos_utils::zone::AdmError; use sled_agent_types::zone_bundle::*; use sled_storage::dataset::U2_DEBUG_DATASET; @@ -43,8 +43,8 @@ use tar::Header; use tokio::process::Command; use tokio::sync::Mutex; use tokio::sync::Notify; -use tokio::time::sleep; use tokio::time::Instant; +use tokio::time::sleep; use uuid::Uuid; // The name of the snapshot created from the zone root filesystem. @@ -698,9 +698,11 @@ fn create_zfs_snapshots( unwind any previously created snapshots"; "error" => ?e, ); - assert!(maybe_err - .replace(BundleError::from(e)) - .is_none()); + assert!( + maybe_err + .replace(BundleError::from(e)) + .is_none() + ); break; } }; @@ -1715,8 +1717,6 @@ mod tests { #[cfg(all(target_os = "illumos", test))] mod illumos_tests { - use super::find_archived_log_files; - use super::zfs_quota; use super::CleanupContext; use super::CleanupPeriod; use super::PriorityOrder; @@ -1728,6 +1728,8 @@ mod illumos_tests { use super::ZoneBundleInfo; use super::ZoneBundleMetadata; use super::ZoneBundler; + use super::find_archived_log_files; + use super::zfs_quota; use anyhow::Context; use chrono::DateTime; use chrono::TimeZone; @@ -2301,10 +2303,12 @@ mod illumos_tests { should_match.sort(); files.sort(); assert_eq!(files.len(), should_match.len()); - assert!(files - .iter() - .zip(should_match.iter()) - .all(|(file, name)| { file.file_name().unwrap() == *name })); + assert!( + files + .iter() + .zip(should_match.iter()) + .all(|(file, name)| { file.file_name().unwrap() == *name }) + ); } } diff --git a/sled-agent/tests/integration_tests/commands.rs b/sled-agent/tests/integration_tests/commands.rs index 8a5b3557705..fec2a5008c5 100644 --- a/sled-agent/tests/integration_tests/commands.rs +++ b/sled-agent/tests/integration_tests/commands.rs @@ -10,10 +10,10 @@ use camino::Utf8PathBuf; use expectorate::assert_contents; +use omicron_test_utils::dev::test_cmds::EXIT_USAGE; use omicron_test_utils::dev::test_cmds::assert_exit_code; use omicron_test_utils::dev::test_cmds::path_to_executable; use omicron_test_utils::dev::test_cmds::run_command; -use omicron_test_utils::dev::test_cmds::EXIT_USAGE; use subprocess::Exec; /// name of the "sled-agent-sim" executable diff --git a/sled-agent/types/src/early_networking.rs b/sled-agent/types/src/early_networking.rs index cef692769cb..73767ecf18c 100644 --- a/sled-agent/types/src/early_networking.rs +++ b/sled-agent/types/src/early_networking.rs @@ -10,7 +10,7 @@ use bootstore::schemes::v0 as bootstore; use omicron_common::api::internal::shared::RackNetworkConfig; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use slog::{warn, Logger}; +use slog::{Logger, warn}; /// Network configuration required to bring up the control plane /// @@ -50,7 +50,7 @@ impl FromStr for EarlyNetworkConfig { generation: cfg.generation, schema_version: cfg.schema_version, body: cfg.body, - }) + }); } Err(e) => format!("unable to parse EarlyNetworkConfig: {e:?}"), }; diff --git a/sled-agent/types/src/instance.rs b/sled-agent/types/src/instance.rs index 3ff73925e46..f4dd1f9bc93 100644 --- a/sled-agent/types/src/instance.rs +++ b/sled-agent/types/src/instance.rs @@ -9,13 +9,13 @@ use std::{ net::{IpAddr, SocketAddr}, }; +use omicron_common::NoDebug; use omicron_common::api::internal::{ nexus::{InstanceProperties, SledVmmState, VmmRuntimeState}, shared::{ DhcpConfig, NetworkInterface, ResolvedVpcFirewallRule, SourceNatConfig, }, }; -use omicron_common::NoDebug; use omicron_uuid_kinds::InstanceUuid; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/sled-agent/types/src/rack_init.rs b/sled-agent/types/src/rack_init.rs index 64ad63e9dff..be8e83d7b86 100644 --- a/sled-agent/types/src/rack_init.rs +++ b/sled-agent/types/src/rack_init.rs @@ -9,12 +9,12 @@ use std::{ net::{IpAddr, Ipv6Addr}, }; -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use camino::{Utf8Path, Utf8PathBuf}; pub use nexus_sled_agent_shared::recovery_silo::RecoverySiloConfig; use omicron_common::{ address::{ - get_64_subnet, IpRange, Ipv6Subnet, AZ_PREFIX, RACK_PREFIX, SLED_PREFIX, + AZ_PREFIX, IpRange, Ipv6Subnet, RACK_PREFIX, SLED_PREFIX, get_64_subnet, }, api::{ external::AllowedSourceIps, diff --git a/sled-agent/types/src/zone_bundle.rs b/sled-agent/types/src/zone_bundle.rs index f7a388771df..6a95eab97a4 100644 --- a/sled-agent/types/src/zone_bundle.rs +++ b/sled-agent/types/src/zone_bundle.rs @@ -415,23 +415,29 @@ mod tests { fn test_priority_dimension() { assert!(PriorityOrder::new(&[]).is_err()); assert!(PriorityOrder::new(&[PriorityDimension::Cause]).is_err()); - assert!(PriorityOrder::new(&[ - PriorityDimension::Cause, - PriorityDimension::Cause - ]) - .is_err()); - assert!(PriorityOrder::new(&[ - PriorityDimension::Cause, - PriorityDimension::Cause, - PriorityDimension::Time - ]) - .is_err()); - - assert!(PriorityOrder::new(&[ - PriorityDimension::Cause, - PriorityDimension::Time - ]) - .is_ok()); + assert!( + PriorityOrder::new(&[ + PriorityDimension::Cause, + PriorityDimension::Cause + ]) + .is_err() + ); + assert!( + PriorityOrder::new(&[ + PriorityDimension::Cause, + PriorityDimension::Cause, + PriorityDimension::Time + ]) + .is_err() + ); + + assert!( + PriorityOrder::new(&[ + PriorityDimension::Cause, + PriorityDimension::Time + ]) + .is_ok() + ); assert_eq!( PriorityOrder::new(PriorityOrder::default().as_slice()).unwrap(), PriorityOrder::default() diff --git a/sled-diagnostics/src/contract.rs b/sled-diagnostics/src/contract.rs index f6bca904f9e..0f23c5926b3 100644 --- a/sled-diagnostics/src/contract.rs +++ b/sled-diagnostics/src/contract.rs @@ -6,7 +6,7 @@ use fs_err as fs; use libc::{c_char, c_int, c_void, pid_t}; -use slog::{warn, Logger}; +use slog::{Logger, warn}; use thiserror::Error; use std::{ @@ -58,7 +58,9 @@ pub enum ContractError { "Failed to call ct_pr_status_get_members for contract {ctid}: {error}" )] Members { ctid: i32, error: std::io::Error }, - #[error("ct_status_read returned successfully but handed back a null ptr for {0}")] + #[error( + "ct_status_read returned successfully but handed back a null ptr for {0}" + )] Null(std::path::PathBuf), #[error("Failed to call ct_status_read on {path}: {error}")] StatusRead { path: std::path::PathBuf, error: std::io::Error }, diff --git a/sled-diagnostics/src/contract_stub.rs b/sled-diagnostics/src/contract_stub.rs index 9637c3486de..40424d1cbfa 100644 --- a/sled-diagnostics/src/contract_stub.rs +++ b/sled-diagnostics/src/contract_stub.rs @@ -2,7 +2,7 @@ use std::collections::BTreeSet; -use slog::{warn, Logger}; +use slog::{Logger, warn}; use thiserror::Error; #[derive(Error, Debug)] diff --git a/sled-diagnostics/src/lib.rs b/sled-diagnostics/src/lib.rs index dba055b85f5..050dc91a212 100644 --- a/sled-diagnostics/src/lib.rs +++ b/sled-diagnostics/src/lib.rs @@ -4,7 +4,7 @@ //! Diagnostics for an Oxide sled that exposes common support commands. -use futures::{stream::FuturesUnordered, StreamExt}; +use futures::{StreamExt, stream::FuturesUnordered}; use slog::Logger; cfg_if::cfg_if! { @@ -24,14 +24,14 @@ pub use crate::queries::{ use queries::*; /// List all zones on a sled. -pub async fn zoneadm_info( -) -> Result { +pub async fn zoneadm_info() +-> Result { execute_command_with_timeout(zoneadm_list(), DEFAULT_TIMEOUT).await } /// Retrieve various `ipadm` command output for the system. -pub async fn ipadm_info( -) -> Vec> { +pub async fn ipadm_info() +-> Vec> { [ipadm_show_interface(), ipadm_show_addr(), ipadm_show_prop()] .into_iter() .map(|c| async move { @@ -43,8 +43,8 @@ pub async fn ipadm_info( } /// Retrieve various `dladm` command output for the system. -pub async fn dladm_info( -) -> Vec> { +pub async fn dladm_info() +-> Vec> { [ dladm_show_phys(), dladm_show_ether(), diff --git a/sled-hardware/src/cleanup.rs b/sled-hardware/src/cleanup.rs index f438098792d..e0780ddf5a4 100644 --- a/sled-hardware/src/cleanup.rs +++ b/sled-hardware/src/cleanup.rs @@ -6,18 +6,18 @@ use anyhow::Error; use futures::stream::{self, StreamExt, TryStreamExt}; -use illumos_utils::dladm::Dladm; +use illumos_utils::ExecutionError; use illumos_utils::dladm::BOOTSTRAP_ETHERSTUB_NAME; use illumos_utils::dladm::BOOTSTRAP_ETHERSTUB_VNIC_NAME; +use illumos_utils::dladm::Dladm; use illumos_utils::dladm::UNDERLAY_ETHERSTUB_NAME; use illumos_utils::dladm::UNDERLAY_ETHERSTUB_VNIC_NAME; use illumos_utils::link::LinkKind; use illumos_utils::opte; use illumos_utils::zone::IPADM; -use illumos_utils::ExecutionError; -use illumos_utils::{execute, PFEXEC}; -use slog::warn; +use illumos_utils::{PFEXEC, execute}; use slog::Logger; +use slog::warn; use slog_error_chain::InlineErrorChain; use std::process::Command; diff --git a/sled-hardware/src/disk.rs b/sled-hardware/src/disk.rs index a07ddea8cfd..ec54ac99a45 100644 --- a/sled-hardware/src/disk.rs +++ b/sled-hardware/src/disk.rs @@ -32,7 +32,9 @@ pub enum PooledDiskError { NotFound { path: Utf8PathBuf, partition: Partition }, #[error("Zpool UUID required to format this disk")] MissingZpoolUuid, - #[error("Observed Zpool with unexpected UUID (saw: {observed}, expected: {expected})")] + #[error( + "Observed Zpool with unexpected UUID (saw: {observed}, expected: {expected})" + )] UnexpectedUuid { expected: ZpoolUuid, observed: ZpoolUuid }, #[error("Unexpected disk variant")] UnexpectedVariant, diff --git a/sled-hardware/src/illumos/mod.rs b/sled-hardware/src/illumos/mod.rs index 3664a7cf06f..06163c3f64b 100644 --- a/sled-hardware/src/illumos/mod.rs +++ b/sled-hardware/src/illumos/mod.rs @@ -7,15 +7,15 @@ use crate::{DendriteAsic, HardwareUpdate, SledMode, UnparsedDisk}; use camino::Utf8PathBuf; use gethostname::gethostname; use illumos_devinfo::{DevInfo, DevLinkType, DevLinks, Node, Property}; -use libnvme::{controller::Controller, Nvme}; +use libnvme::{Nvme, controller::Controller}; use omicron_common::disk::{DiskIdentity, DiskVariant}; use sled_hardware_types::Baseboard; +use slog::Logger; use slog::debug; use slog::error; use slog::info; use slog::o; use slog::warn; -use slog::Logger; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::sync::Mutex; @@ -26,7 +26,7 @@ mod gpt; mod partitions; mod sysconf; -pub use partitions::{ensure_partition_layout, NvmeFormattingError}; +pub use partitions::{NvmeFormattingError, ensure_partition_layout}; #[derive(thiserror::Error, Debug)] enum Error { @@ -568,7 +568,7 @@ fn poll_blkdev_node( return Err(Error::NvmeControllerLocked); } libnvme::controller::TryLockResult::Err(err) => { - return Err(Error::from(err)) + return Err(Error::from(err)); } }; let firmware_log_page = controller_lock.get_firmware_log_page()?; @@ -763,10 +763,13 @@ impl HardwareManager { // Allow non-gimlet devices to proceed with a "null" view of // hardware, otherwise they won't be able to start. Err(Error::NotAGimlet(root)) => { - warn!(log, "Device is not a Gimlet ({root}), proceeding with null hardware view"); + warn!( + log, + "Device is not a Gimlet ({root}), proceeding with null hardware view" + ); } Err(err) => { - return Err(format!("Failed to poll device tree: {err}")) + return Err(format!("Failed to poll device tree: {err}")); } }; diff --git a/sled-hardware/src/illumos/partitions.rs b/sled-hardware/src/illumos/partitions.rs index 7b8f88a1f1c..651ca5fdc47 100644 --- a/sled-hardware/src/illumos/partitions.rs +++ b/sled-hardware/src/illumos/partitions.rs @@ -13,8 +13,8 @@ use camino::Utf8Path; use illumos_utils::zpool::ZpoolName; use omicron_common::disk::{DiskIdentity, DiskVariant}; use omicron_uuid_kinds::ZpoolUuid; -use slog::info; use slog::Logger; +use slog::info; #[cfg(test)] use illumos_utils::zpool::MockZpool as Zpool; @@ -41,8 +41,8 @@ static PREFERRED_NVME_DEVICE_SETTINGS: OnceLock< HashMap<&'static str, NvmeDeviceSettings>, > = OnceLock::new(); -fn preferred_nvme_device_settings( -) -> &'static HashMap<&'static str, NvmeDeviceSettings> { +fn preferred_nvme_device_settings() +-> &'static HashMap<&'static str, NvmeDeviceSettings> { PREFERRED_NVME_DEVICE_SETTINGS.get_or_init(|| { HashMap::from([ ( @@ -248,8 +248,8 @@ fn ensure_size_and_formatting( log: &Logger, identity: &DiskIdentity, ) -> Result<(), NvmeFormattingError> { - use libnvme::namespace::NamespaceDiscoveryLevel; use libnvme::Nvme; + use libnvme::namespace::NamespaceDiscoveryLevel; let mut controller_found = false; @@ -451,17 +451,19 @@ mod test { let devfs_path = Utf8PathBuf::from("/devfs/path"); const DEV_PATH: &'static str = "/dev/path"; - assert!(internal_ensure_partition_layout::( - &log, - &DiskPaths { - devfs_path, - dev_path: Some(Utf8PathBuf::from(DEV_PATH)) - }, - DiskVariant::M2, - &mock_disk_identity(), - None, - ) - .is_err()); + assert!( + internal_ensure_partition_layout::( + &log, + &DiskPaths { + devfs_path, + dev_path: Some(Utf8PathBuf::from(DEV_PATH)) + }, + DiskVariant::M2, + &mock_disk_identity(), + None, + ) + .is_err() + ); logctx.cleanup_successful(); } diff --git a/sled-hardware/src/non_illumos/mod.rs b/sled-hardware/src/non_illumos/mod.rs index a61bbc495fc..707ccd8d45f 100644 --- a/sled-hardware/src/non_illumos/mod.rs +++ b/sled-hardware/src/non_illumos/mod.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::disk::{DiskPaths, Partition, PooledDiskError, UnparsedDisk}; use crate::SledMode; +use crate::disk::{DiskPaths, Partition, PooledDiskError, UnparsedDisk}; use omicron_common::disk::{DiskIdentity, DiskVariant}; use omicron_uuid_kinds::ZpoolUuid; use sled_hardware_types::Baseboard; diff --git a/sled-hardware/src/underlay.rs b/sled-hardware/src/underlay.rs index e0b40f443b6..dbc0d57022a 100644 --- a/sled-hardware/src/underlay.rs +++ b/sled-hardware/src/underlay.rs @@ -7,12 +7,12 @@ use crate::is_gimlet; use illumos_utils::addrobj; use illumos_utils::addrobj::AddrObject; +use illumos_utils::dladm::CHELSIO_LINK_PREFIX; use illumos_utils::dladm::Dladm; use illumos_utils::dladm::FindPhysicalLinkError; use illumos_utils::dladm::GetLinkpropError; use illumos_utils::dladm::PhysicalLink; use illumos_utils::dladm::SetLinkpropError; -use illumos_utils::dladm::CHELSIO_LINK_PREFIX; use illumos_utils::zone::Zones; #[derive(thiserror::Error, Debug)] diff --git a/sled-storage/src/dataset.rs b/sled-storage/src/dataset.rs index 42c1d324cab..123a9a8653e 100644 --- a/sled-storage/src/dataset.rs +++ b/sled-storage/src/dataset.rs @@ -19,7 +19,7 @@ use omicron_common::disk::{ CompressionAlgorithm, DatasetName, DiskIdentity, DiskVariant, GzipLevel, }; use rand::distributions::{Alphanumeric, DistString}; -use slog::{debug, info, Logger}; +use slog::{Logger, debug, info}; use std::process::Stdio; use std::str::FromStr; use std::sync::OnceLock; @@ -165,7 +165,9 @@ pub enum DatasetError { MissingStorageKeyRequester, #[error("Encrypted filesystem '{0}' missing 'oxide:epoch' property")] CannotParseEpochProperty(String), - #[error("Encrypted dataset '{dataset}' cannot set 'oxide:agent' property: {err}")] + #[error( + "Encrypted dataset '{dataset}' cannot set 'oxide:agent' property: {err}" + )] CannotSetAgentProperty { dataset: String, #[source] diff --git a/sled-storage/src/disk.rs b/sled-storage/src/disk.rs index ae0f5d25dce..0de4ef116c6 100644 --- a/sled-storage/src/disk.rs +++ b/sled-storage/src/disk.rs @@ -14,7 +14,7 @@ use omicron_uuid_kinds::ZpoolUuid; use sled_hardware::{ DiskFirmware, Partition, PooledDisk, PooledDiskError, UnparsedDisk, }; -use slog::{info, Logger}; +use slog::{Logger, info}; use crate::config::MountConfig; use crate::dataset; diff --git a/sled-storage/src/error.rs b/sled-storage/src/error.rs index 1e496161622..e103f7d6bcc 100644 --- a/sled-storage/src/error.rs +++ b/sled-storage/src/error.rs @@ -57,7 +57,9 @@ pub enum Error { err: uuid::Error, }, - #[error("Dataset {name} exists with a different uuid (has {old}, requested {new})")] + #[error( + "Dataset {name} exists with a different uuid (has {old}, requested {new})" + )] UuidMismatch { name: String, old: Uuid, new: Uuid }, #[error("Error parsing pool {name}'s size: {err}")] @@ -77,10 +79,14 @@ pub enum Error { #[error("Not ready to manage U.2s (key manager is not ready)")] KeyManagerNotReady, - #[error("Physical disk configuration changed for the same generation number: {generation}")] + #[error( + "Physical disk configuration changed for the same generation number: {generation}" + )] PhysicalDiskConfigurationChanged { generation: Generation }, - #[error("Physical disk configuration out-of-date (asked for {requested}, but latest is {current})")] + #[error( + "Physical disk configuration out-of-date (asked for {requested}, but latest is {current})" + )] PhysicalDiskConfigurationOutdated { requested: Generation, current: Generation, @@ -89,10 +95,14 @@ pub enum Error { #[error("Invalid configuration (UUID mismatch in arguments)")] ConfigUuidMismatch, - #[error("Dataset configuration out-of-date (asked for {requested}, but latest is {current})")] + #[error( + "Dataset configuration out-of-date (asked for {requested}, but latest is {current})" + )] DatasetConfigurationOutdated { requested: Generation, current: Generation }, - #[error("Dataset configuration changed for the same generation number: {generation}")] + #[error( + "Dataset configuration changed for the same generation number: {generation}" + )] DatasetConfigurationChanged { generation: Generation }, #[error("Failed to update ledger in internal storage")] diff --git a/sled-storage/src/keyfile.rs b/sled-storage/src/keyfile.rs index 190dfb9c260..b0e859da485 100644 --- a/sled-storage/src/keyfile.rs +++ b/sled-storage/src/keyfile.rs @@ -5,8 +5,8 @@ //! Key file support for ZFS dataset encryption use illumos_utils::zfs::Keypath; -use slog::{error, info, Logger}; -use tokio::fs::{remove_file, File}; +use slog::{Logger, error, info}; +use tokio::fs::{File, remove_file}; use tokio::io::{AsyncSeekExt, AsyncWriteExt, SeekFrom}; /// A file that wraps a zfs encryption key. diff --git a/sled-storage/src/manager.rs b/sled-storage/src/manager.rs index f1739fe5f47..59de4a22f20 100644 --- a/sled-storage/src/manager.rs +++ b/sled-storage/src/manager.rs @@ -13,13 +13,13 @@ use anyhow::anyhow; use camino::Utf8Path; use camino::Utf8PathBuf; use debug_ignore::DebugIgnore; -use futures::future::FutureExt; use futures::Stream; use futures::StreamExt; +use futures::future::FutureExt; use illumos_utils::zfs::{ DatasetEnsureArgs, DatasetProperties, Mountpoint, WhichDatasets, Zfs, }; -use illumos_utils::zpool::{ZpoolName, ZPOOL_MOUNTPOINT_ROOT}; +use illumos_utils::zpool::{ZPOOL_MOUNTPOINT_ROOT, ZpoolName}; use key_manager::StorageKeyRequester; use omicron_common::disk::{ DatasetConfig, DatasetManagementStatus, DatasetName, DatasetsConfig, @@ -29,12 +29,12 @@ use omicron_common::disk::{ use omicron_common::ledger::Ledger; use omicron_uuid_kinds::DatasetUuid; use omicron_uuid_kinds::GenericUuid; -use slog::{error, info, o, warn, Logger}; +use slog::{Logger, error, info, o, warn}; use std::collections::BTreeMap; use std::collections::HashSet; use std::future::Future; use tokio::sync::{mpsc, oneshot, watch}; -use tokio::time::{interval, Duration, MissedTickBehavior}; +use tokio::time::{Duration, MissedTickBehavior, interval}; // The size of the mpsc bounded channel used to communicate // between the `StorageHandle` and `StorageManager`. @@ -906,7 +906,10 @@ impl StorageManager { ledger } None => { - info!(log, "No previously-stored 'requested datasets', creating new ledger"); + info!( + log, + "No previously-stored 'requested datasets', creating new ledger" + ); Ledger::::new_with( &log, ledger_paths.clone(), @@ -1295,7 +1298,10 @@ impl StorageManager { ledger } None => { - info!(log, "No previously-stored 'requested disks', creating new ledger"); + info!( + log, + "No previously-stored 'requested disks', creating new ledger" + ); Ledger::::new_with( &log, ledger_paths.clone(), @@ -1394,11 +1400,7 @@ impl StorageManager { .disks() .iter_all() .filter_map(|(id, _variant, _slot, _firmware)| { - if !all_ids.contains(id) { - Some(id.clone()) - } else { - None - } + if !all_ids.contains(id) { Some(id.clone()) } else { None } }) .collect(); @@ -1694,11 +1696,7 @@ mod tests { let firmware = all_disks_gen2 .iter_all() .find_map(|(identity, _, _, fw)| { - if identity == rd.identity() { - Some(fw) - } else { - None - } + if identity == rd.identity() { Some(fw) } else { None } }) .expect("disk exists"); assert_eq!(firmware, rd.firmware(), "didn't see firmware update"); @@ -1722,12 +1720,14 @@ mod tests { assert!(all_disks.boot_disk().is_none()); // Waiting for the boot disk should time out. - assert!(tokio::time::timeout( - tokio::time::Duration::from_millis(10), - harness.handle_mut().wait_for_boot_disk(), - ) - .await - .is_err()); + assert!( + tokio::time::timeout( + tokio::time::Duration::from_millis(10), + harness.handle_mut().wait_for_boot_disk(), + ) + .await + .is_err() + ); // Now we add a boot disk. let boot_disk = harness.add_vdevs(&["m2_under_test.vdev"]).await; diff --git a/sled-storage/src/manager_test_harness.rs b/sled-storage/src/manager_test_harness.rs index 33705dd0b8b..334af3b2c79 100644 --- a/sled-storage/src/manager_test_harness.rs +++ b/sled-storage/src/manager_test_harness.rs @@ -14,10 +14,10 @@ use omicron_common::disk::{ }; use omicron_uuid_kinds::PhysicalDiskUuid; use omicron_uuid_kinds::ZpoolUuid; -use slog::{info, Logger}; +use slog::{Logger, info}; use std::sync::{ - atomic::{AtomicBool, Ordering}, Arc, + atomic::{AtomicBool, Ordering}, }; /// A [`key-manager::SecretRetriever`] that only returns hardcoded IKM for diff --git a/sled-storage/src/resources.rs b/sled-storage/src/resources.rs index 2af9d006fca..d6320e28abb 100644 --- a/sled-storage/src/resources.rs +++ b/sled-storage/src/resources.rs @@ -19,7 +19,7 @@ use omicron_common::disk::{ OmicronPhysicalDisksConfig, }; use sled_hardware::DiskFirmware; -use slog::{info, o, warn, Logger}; +use slog::{Logger, info, o, warn}; use std::collections::BTreeMap; use std::sync::Arc; use tokio::sync::watch; diff --git a/sp-sim/src/bin/sp-sim.rs b/sp-sim/src/bin/sp-sim.rs index ee0dd3b70c1..3409041b8eb 100644 --- a/sp-sim/src/bin/sp-sim.rs +++ b/sp-sim/src/bin/sp-sim.rs @@ -2,11 +2,11 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use clap::Parser; -use omicron_common::cmd::{fatal, CmdError}; -use sp_sim::config::Config; +use omicron_common::cmd::{CmdError, fatal}; use sp_sim::SimRack; +use sp_sim::config::Config; use std::path::PathBuf; use std::time::Duration; diff --git a/sp-sim/src/gimlet.rs b/sp-sim/src/gimlet.rs index 4245e360eb0..ce1bd77268e 100644 --- a/sp-sim/src/gimlet.rs +++ b/sp-sim/src/gimlet.rs @@ -2,6 +2,9 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::Responsiveness; +use crate::SIM_ROT_BOARD; +use crate::SimulatedSp; use crate::config::GimletConfig; use crate::config::SpComponentConfig; use crate::helpers::rot_slot_id_from_u16; @@ -12,17 +15,10 @@ use crate::server; use crate::server::SimSpHandler; use crate::server::UdpServer; use crate::update::SimSpUpdate; -use crate::Responsiveness; -use crate::SimulatedSp; -use crate::SIM_ROT_BOARD; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use async_trait::async_trait; -use futures::future; use futures::Future; -use gateway_messages::ignition::{self, LinkEvents}; -use gateway_messages::sp_impl::Sender; -use gateway_messages::sp_impl::SpHandler; -use gateway_messages::sp_impl::{BoundsChecked, DeviceDescription}; +use futures::future; use gateway_messages::CfpaPage; use gateway_messages::ComponentAction; use gateway_messages::ComponentActionResponse; @@ -38,11 +34,15 @@ use gateway_messages::SpError; use gateway_messages::SpPort; use gateway_messages::SpRequest; use gateway_messages::SpStateV2; -use gateway_messages::{version, MessageKind}; +use gateway_messages::ignition::{self, LinkEvents}; +use gateway_messages::sp_impl::Sender; +use gateway_messages::sp_impl::SpHandler; +use gateway_messages::sp_impl::{BoundsChecked, DeviceDescription}; use gateway_messages::{ComponentDetails, Message, MgsError, StartupOptions}; use gateway_messages::{DiscoverResponse, IgnitionState, PowerState}; +use gateway_messages::{MessageKind, version}; use gateway_types::component::SpState; -use slog::{debug, error, info, warn, Logger}; +use slog::{Logger, debug, error, info, warn}; use std::cell::Cell; use std::collections::HashMap; use std::iter; @@ -52,10 +52,10 @@ use std::sync::{Arc, Mutex}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio::select; +use tokio::sync::Mutex as TokioMutex; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tokio::sync::oneshot; use tokio::sync::watch; -use tokio::sync::Mutex as TokioMutex; use tokio::task::{self, JoinHandle}; pub const SIM_GIMLET_BOARD: &str = "SimGimletSp"; @@ -242,9 +242,9 @@ impl Gimlet { .to_string(), listener .local_addr() - .with_context(|| { - "failed to get local address of bound socket" - }) + .with_context( + || "failed to get local address of bound socket", + ) .and_then(|addr| match addr { SocketAddr::V4(addr) => { bail!("bound IPv4 address {}", addr) diff --git a/sp-sim/src/lib.rs b/sp-sim/src/lib.rs index 15f2034aa8b..1f1721747a1 100644 --- a/sp-sim/src/lib.rs +++ b/sp-sim/src/lib.rs @@ -16,11 +16,11 @@ pub use config::Config; use gateway_messages::SpPort; use gateway_types::component::SpState; pub use gimlet::Gimlet; -pub use gimlet::SimSpHandledRequest; pub use gimlet::SIM_GIMLET_BOARD; +pub use gimlet::SimSpHandledRequest; pub use server::logger; -pub use sidecar::Sidecar; pub use sidecar::SIM_SIDECAR_BOARD; +pub use sidecar::Sidecar; pub use slog::Logger; use std::net::SocketAddrV6; use tokio::sync::mpsc; diff --git a/sp-sim/src/sensors.rs b/sp-sim/src/sensors.rs index fc684af01b9..1db3f4a2661 100644 --- a/sp-sim/src/sensors.rs +++ b/sp-sim/src/sensors.rs @@ -3,9 +3,6 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::config::SpComponentConfig; -use gateway_messages::measurement::MeasurementError; -use gateway_messages::measurement::MeasurementKind; -use gateway_messages::sp_impl::BoundsChecked; use gateway_messages::ComponentDetails; use gateway_messages::DeviceCapabilities; use gateway_messages::Measurement; @@ -16,6 +13,9 @@ use gateway_messages::SensorRequest; use gateway_messages::SensorRequestKind; use gateway_messages::SensorResponse; use gateway_messages::SpComponent; +use gateway_messages::measurement::MeasurementError; +use gateway_messages::measurement::MeasurementKind; +use gateway_messages::sp_impl::BoundsChecked; use std::collections::HashMap; diff --git a/sp-sim/src/server.rs b/sp-sim/src/server.rs index d1324b605b8..5f3052cbe5f 100644 --- a/sp-sim/src/server.rs +++ b/sp-sim/src/server.rs @@ -2,25 +2,25 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::Responsiveness; use crate::config::Config; use crate::config::NetworkConfig; -use crate::Responsiveness; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::bail; use gateway_messages::sp_impl; use gateway_messages::sp_impl::Sender; use gateway_messages::sp_impl::SpHandler; use nix::net::if_::if_nametoindex; +use slog::Logger; use slog::debug; use slog::error; use slog::info; -use slog::Logger; use std::net::SocketAddr; use std::net::SocketAddrV6; +use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; -use std::sync::Arc; use tokio::net::UdpSocket; /// Thin wrapper pairing a [`UdpSocket`] with a buffer sized for gateway @@ -180,11 +180,7 @@ where let response = sp_impl::handle_message(sender, data, handler, out) .map(|n| (&out[..n], addr)); - if should_respond.load(Ordering::SeqCst) { - Ok(response) - } else { - Ok(None) - } + if should_respond.load(Ordering::SeqCst) { Ok(response) } else { Ok(None) } } pub(crate) trait SimSpHandler: SpHandler { diff --git a/sp-sim/src/sidecar.rs b/sp-sim/src/sidecar.rs index 309d4b4489f..c5b0c317350 100644 --- a/sp-sim/src/sidecar.rs +++ b/sp-sim/src/sidecar.rs @@ -2,6 +2,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::Responsiveness; +use crate::SIM_ROT_BOARD; +use crate::SIM_ROT_STAGE0_BOARD; +use crate::SimulatedSp; use crate::config::Config; use crate::config::SidecarConfig; use crate::config::SimulatedSpsConfig; @@ -14,21 +18,10 @@ use crate::server; use crate::server::SimSpHandler; use crate::server::UdpServer; use crate::update::SimSpUpdate; -use crate::Responsiveness; -use crate::SimulatedSp; -use crate::SIM_ROT_BOARD; -use crate::SIM_ROT_STAGE0_BOARD; use anyhow::Result; use async_trait::async_trait; -use futures::future; use futures::Future; -use gateway_messages::ignition; -use gateway_messages::ignition::IgnitionError; -use gateway_messages::ignition::LinkEvents; -use gateway_messages::sp_impl::BoundsChecked; -use gateway_messages::sp_impl::DeviceDescription; -use gateway_messages::sp_impl::Sender; -use gateway_messages::sp_impl::SpHandler; +use futures::future; use gateway_messages::CfpaPage; use gateway_messages::ComponentAction; use gateway_messages::ComponentActionResponse; @@ -49,20 +42,27 @@ use gateway_messages::SpError; use gateway_messages::SpPort; use gateway_messages::SpStateV2; use gateway_messages::StartupOptions; +use gateway_messages::ignition; +use gateway_messages::ignition::IgnitionError; +use gateway_messages::ignition::LinkEvents; +use gateway_messages::sp_impl::BoundsChecked; +use gateway_messages::sp_impl::DeviceDescription; +use gateway_messages::sp_impl::Sender; +use gateway_messages::sp_impl::SpHandler; use gateway_types::component::SpState; +use slog::Logger; use slog::debug; use slog::info; use slog::warn; -use slog::Logger; use std::iter; use std::net::SocketAddrV6; use std::pin::Pin; use std::sync::Arc; use tokio::select; +use tokio::sync::Mutex as TokioMutex; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::sync::watch; -use tokio::sync::Mutex as TokioMutex; use tokio::task; use tokio::task::JoinHandle; diff --git a/test-utils/src/bin/falcon_runner.rs b/test-utils/src/bin/falcon_runner.rs index d7ffd1d8236..c95b4261888 100644 --- a/test-utils/src/bin/falcon_runner.rs +++ b/test-utils/src/bin/falcon_runner.rs @@ -8,7 +8,7 @@ mod illumos { pub use anyhow::anyhow; pub use camino_tempfile::tempdir; - pub use libfalcon::{unit::gb, Runner}; + pub use libfalcon::{Runner, unit::gb}; pub use omicron_test_utils::dev::test_setup_log; pub use slog::info; pub use std::env; diff --git a/test-utils/src/bin/falcon_runner_cli.rs b/test-utils/src/bin/falcon_runner_cli.rs index 9a4f6c1bf62..0e6a127674e 100644 --- a/test-utils/src/bin/falcon_runner_cli.rs +++ b/test-utils/src/bin/falcon_runner_cli.rs @@ -6,7 +6,7 @@ #[cfg(target_os = "illumos")] mod illumos { - pub use libfalcon::{cli::run, error::Error, unit::gb, Runner}; + pub use libfalcon::{Runner, cli::run, error::Error, unit::gb}; } #[cfg(target_os = "illumos")] diff --git a/test-utils/src/dev/clickhouse.rs b/test-utils/src/dev/clickhouse.rs index 8956bb88a72..e4bd93ae169 100644 --- a/test-utils/src/dev/clickhouse.rs +++ b/test-utils/src/dev/clickhouse.rs @@ -10,19 +10,19 @@ use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::Duration; -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use camino::{Utf8Path, Utf8PathBuf}; use camino_tempfile::{Builder, Utf8TempDir}; -use dropshot::test_util::{log_prefix_for_test, LogContext}; -use futures::stream::FuturesUnordered; +use dropshot::test_util::{LogContext, log_prefix_for_test}; use futures::StreamExt as _; +use futures::stream::FuturesUnordered; use omicron_common::address::{CLICKHOUSE_HTTP_PORT, CLICKHOUSE_TCP_PORT}; use std::net::{Ipv6Addr, SocketAddrV6}; use thiserror::Error; use tokio::{ fs::File, io::{AsyncBufReadExt, BufReader}, - time::{sleep, Instant}, + time::{Instant, sleep}, }; use crate::dev::poll; @@ -1320,9 +1320,9 @@ async fn clickhouse_ready_from_log( #[cfg(test)] mod tests { use super::{ - discover_ready, wait_for_ports, ClickHouseDeployment, ClickHouseError, - ClickHousePorts, CLICKHOUSE_HTTP_PORT_NEEDLE, CLICKHOUSE_READY, - CLICKHOUSE_TCP_PORT_NEEDLE, CLICKHOUSE_TIMEOUT, + CLICKHOUSE_HTTP_PORT_NEEDLE, CLICKHOUSE_READY, + CLICKHOUSE_TCP_PORT_NEEDLE, CLICKHOUSE_TIMEOUT, ClickHouseDeployment, + ClickHouseError, ClickHousePorts, discover_ready, wait_for_ports, }; use crate::dev::test_setup_log; use camino_tempfile::NamedUtf8TempFile; diff --git a/test-utils/src/dev/db.rs b/test-utils/src/dev/db.rs index 1a8c08b4bc4..6249570c630 100644 --- a/test-utils/src/dev/db.rs +++ b/test-utils/src/dev/db.rs @@ -5,9 +5,9 @@ //! Facilities for managing a local database for development use crate::dev::poll; +use anyhow::Context; use anyhow::anyhow; use anyhow::bail; -use anyhow::Context; use nexus_config::PostgresConfigWithUrl; use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; @@ -18,8 +18,8 @@ use std::path::Path; use std::path::PathBuf; use std::process::Stdio; use std::time::Duration; -use tempfile::tempdir; use tempfile::TempDir; +use tempfile::tempdir; use thiserror::Error; use tokio::io::AsyncWriteExt; use tokio_postgres::config::Host; @@ -691,7 +691,7 @@ impl Drop for CockroachInstance { \tcargo xtask db-dev run --no-populate --store-dir {data_path:?}\n\ \t# Access the database. Note the port may change if you run multiple databases.\n\ \tcockroach sql --host=localhost:32221 --insecure", - data_path = path.join("data"), + data_path = path.join("data"), ); } } @@ -1072,11 +1072,11 @@ impl Client { // These are more integration tests than unit tests. #[cfg(test)] mod test { - use super::has_omicron_schema; - use super::make_pg_config; use super::CockroachStartError; use super::CockroachStarter; use super::CockroachStarterBuilder; + use super::has_omicron_schema; + use super::make_pg_config; use crate::dev::db::process_exited; use crate::dev::poll; use crate::dev::process_running; @@ -1104,10 +1104,12 @@ mod test { let builder = new_builder(); let starter = builder.build().unwrap(); let directory = starter.temp_dir().to_owned(); - assert!(fs::metadata(&directory) - .await - .expect("temporary directory is missing") - .is_dir()); + assert!( + fs::metadata(&directory) + .await + .expect("temporary directory is missing") + .is_dir() + ); drop(starter); assert_eq!( libc::ENOENT, @@ -1203,10 +1205,12 @@ mod test { // The child process should still be running. assert!(process_running(pid)); // The temporary directory should still exist. - assert!(fs::metadata(&directory) - .await - .expect("temporary directory is missing") - .is_dir()); + assert!( + fs::metadata(&directory) + .await + .expect("temporary directory is missing") + .is_dir() + ); // Kill the child process (to clean up after ourselves). assert_eq!(0, unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }); @@ -1345,10 +1349,12 @@ mod test { // At this point, our extra temporary directory should still exist. // This is important -- the library should not clean up a data directory // that was specified by the user. - assert!(fs::metadata(&data_dir) - .await - .expect("CockroachDB data directory is missing") - .is_dir()); + assert!( + fs::metadata(&data_dir) + .await + .expect("CockroachDB data directory is missing") + .is_dir() + ); // Clean it up. let extra_temp_dir_path = extra_temp_dir.path().to_owned(); extra_temp_dir @@ -1412,10 +1418,12 @@ mod test { // The database process should be running and the database's store // directory should exist. assert!(process_running(pid)); - assert!(fs::metadata(data_dir.as_ref()) - .await - .expect("CockroachDB data directory is missing") - .is_dir()); + assert!( + fs::metadata(data_dir.as_ref()) + .await + .expect("CockroachDB data directory is missing") + .is_dir() + ); // Check the environment variables. Doing this is platform-specific and // we only bother implementing it for illumos. diff --git a/test-utils/src/dev/dendrite.rs b/test-utils/src/dev/dendrite.rs index 22f3f696011..6840480cfc3 100644 --- a/test-utils/src/dev/dendrite.rs +++ b/test-utils/src/dev/dendrite.rs @@ -13,7 +13,7 @@ use tempfile::TempDir; use tokio::{ fs::File, io::{AsyncBufReadExt, BufReader}, - time::{sleep, Instant}, + time::{Instant, sleep}, }; /// Specifies the amount of time we will wait for `dpd` to launch, diff --git a/test-utils/src/dev/maghemite.rs b/test-utils/src/dev/maghemite.rs index 7e2d8953299..a633751bca8 100644 --- a/test-utils/src/dev/maghemite.rs +++ b/test-utils/src/dev/maghemite.rs @@ -13,7 +13,7 @@ use tempfile::TempDir; use tokio::{ fs::File, io::{AsyncBufReadExt, BufReader}, - time::{sleep, Instant}, + time::{Instant, sleep}, }; /// Specifies the amount of time we will wait for `mgd` to launch, diff --git a/test-utils/src/dev/mod.rs b/test-utils/src/dev/mod.rs index 31a448c9880..daaaf6506ee 100644 --- a/test-utils/src/dev/mod.rs +++ b/test-utils/src/dev/mod.rs @@ -17,10 +17,10 @@ pub mod test_cmds; use anyhow::{Context, Result}; use camino::Utf8PathBuf; -pub use dropshot::test_util::LogContext; use dropshot::ConfigLogging; use dropshot::ConfigLoggingIfExists; use dropshot::ConfigLoggingLevel; +pub use dropshot::test_util::LogContext; use omicron_common::disk::DiskIdentity; use slog::Logger; use std::io::BufReader; @@ -92,9 +92,11 @@ async fn setup_database( StorageSource::DoNotPopulate | StorageSource::PopulateLatest { .. } => { } StorageSource::CopyFromSeed { input_tar } => { - info!(&log, + info!( + &log, "cockroach: copying from seed tarball ({}) to storage directory ({})", - input_tar, starter.store_dir().to_string_lossy(), + input_tar, + starter.store_dir().to_string_lossy(), ); let reader = std::fs::File::open(input_tar).with_context(|| { format!("cannot open input tar {}", input_tar) diff --git a/test-utils/src/dev/seed.rs b/test-utils/src/dev/seed.rs index 46be1e327b6..5d5ea5beb44 100644 --- a/test-utils/src/dev/seed.rs +++ b/test-utils/src/dev/seed.rs @@ -4,7 +4,7 @@ use std::io::{BufWriter, Write}; -use anyhow::{ensure, Context, Result}; +use anyhow::{Context, Result, ensure}; use camino::{Utf8Path, Utf8PathBuf}; use filetime::FileTime; use slog::Logger; diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index c46fad4130a..f035b8132b7 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -8,8 +8,8 @@ // it's expected that we'll have links to private items in the docs. #![allow(rustdoc::private_intra_doc_links)] -use anyhow::anyhow; use anyhow::Context; +use anyhow::anyhow; use headers::authorization::Credentials; pub mod certificates; diff --git a/tufaceous-lib/src/archive.rs b/tufaceous-lib/src/archive.rs index 60be5799b2d..30f93b2dfb1 100644 --- a/tufaceous-lib/src/archive.rs +++ b/tufaceous-lib/src/archive.rs @@ -4,7 +4,7 @@ //! Support for reading and writing zip archives. -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use buf_list::BufList; use bytes::Bytes; use camino::{Utf8Component, Utf8Path, Utf8PathBuf}; @@ -15,8 +15,8 @@ use std::{ io::{BufReader, BufWriter, Cursor, Read, Seek}, }; use zip::{ - write::{FileOptions, SimpleFileOptions}, CompressionMethod, ZipArchive, ZipWriter, + write::{FileOptions, SimpleFileOptions}, }; /// A builder for TUF repo archives. @@ -223,7 +223,10 @@ impl fmt::Display for InvalidPath<'_> { write!(f, "path is absolute -- expected relative paths") } InvalidPath::ExactlyBaseDir => { - write!(f, "path is exactly `{ZIP_BASE_DIR}` -- expected `{ZIP_BASE_DIR}/`") + write!( + f, + "path is exactly `{ZIP_BASE_DIR}` -- expected `{ZIP_BASE_DIR}/`" + ) } InvalidPath::IncorrectBaseDir => { write!(f, "invalid base directory -- must be `{ZIP_BASE_DIR}`") diff --git a/tufaceous-lib/src/artifact.rs b/tufaceous-lib/src/artifact.rs index 486744e3ceb..625c9734667 100644 --- a/tufaceous-lib/src/artifact.rs +++ b/tufaceous-lib/src/artifact.rs @@ -7,7 +7,7 @@ use std::{ path::Path, }; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use buf_list::BufList; use bytes::Bytes; use camino::Utf8PathBuf; diff --git a/tufaceous-lib/src/artifact/composite.rs b/tufaceous-lib/src/artifact/composite.rs index 50574d704f3..b851740ddc6 100644 --- a/tufaceous-lib/src/artifact/composite.rs +++ b/tufaceous-lib/src/artifact/composite.rs @@ -7,13 +7,13 @@ use super::HOST_PHASE_1_FILE_NAME; use super::HOST_PHASE_2_FILE_NAME; use super::ROT_ARCHIVE_A_FILE_NAME; use super::ROT_ARCHIVE_B_FILE_NAME; -use anyhow::anyhow; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::anyhow; +use anyhow::bail; use camino::Utf8Path; -use flate2::write::GzEncoder; use flate2::Compression; +use flate2::write::GzEncoder; use omicron_brand_metadata::{ArchiveType, Metadata}; use sha2::Digest; use sha2::Sha256; diff --git a/tufaceous-lib/src/assemble/manifest.rs b/tufaceous-lib/src/assemble/manifest.rs index 3203cdfc825..e78b586f18e 100644 --- a/tufaceous-lib/src/assemble/manifest.rs +++ b/tufaceous-lib/src/assemble/manifest.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use anyhow::{bail, ensure, Context, Result}; +use anyhow::{Context, Result, bail, ensure}; use camino::{Utf8Path, Utf8PathBuf}; use omicron_common::api::{ external::SemverVersion, internal::nexus::KnownArtifactKind, @@ -13,9 +13,9 @@ use parse_size::parse_size; use serde::{Deserialize, Serialize}; use crate::{ - make_filler_text, ArtifactSource, CompositeControlPlaneArchiveBuilder, - CompositeEntry, CompositeHostArchiveBuilder, CompositeRotArchiveBuilder, - MtimeSource, + ArtifactSource, CompositeControlPlaneArchiveBuilder, CompositeEntry, + CompositeHostArchiveBuilder, CompositeRotArchiveBuilder, MtimeSource, + make_filler_text, }; static FAKE_MANIFEST_TOML: &str = @@ -545,7 +545,7 @@ impl DeserializedControlPlaneZoneSource { (name.to_owned(), data, MtimeSource::Now) } DeserializedControlPlaneZoneSource::Fake { name, size } => { - use flate2::{write::GzEncoder, Compression}; + use flate2::{Compression, write::GzEncoder}; use omicron_brand_metadata::{ ArchiveType, LayerInfo, Metadata, }; diff --git a/tufaceous-lib/src/key.rs b/tufaceous-lib/src/key.rs index b5aa558df6b..d435c78bbcc 100644 --- a/tufaceous-lib/src/key.rs +++ b/tufaceous-lib/src/key.rs @@ -1,7 +1,7 @@ -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use aws_lc_rs::rand::SystemRandom; use aws_lc_rs::signature::Ed25519KeyPair; -use base64::{engine::general_purpose::URL_SAFE, Engine}; +use base64::{Engine, engine::general_purpose::URL_SAFE}; use std::fmt::Display; use std::str::FromStr; use tough::async_trait; diff --git a/tufaceous-lib/src/repository.rs b/tufaceous-lib/src/repository.rs index 7fef2565a86..0d521965e0d 100644 --- a/tufaceous-lib/src/repository.rs +++ b/tufaceous-lib/src/repository.rs @@ -2,8 +2,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::{key::Key, target::TargetWriter, AddArtifact, ArchiveBuilder}; -use anyhow::{anyhow, bail, Context, Result}; +use crate::{AddArtifact, ArchiveBuilder, key::Key, target::TargetWriter}; +use anyhow::{Context, Result, anyhow, bail}; use buf_list::BufList; use camino::{Utf8Path, Utf8PathBuf}; use chrono::{DateTime, Utc}; @@ -15,9 +15,9 @@ use omicron_common::{ }; use std::{collections::BTreeSet, num::NonZeroU64}; use tough::{ - editor::{signed::SignedRole, RepositoryEditor}, - schema::{Root, Target}, ExpirationEnforcement, Repository, RepositoryLoader, TargetName, + editor::{RepositoryEditor, signed::SignedRole}, + schema::{Root, Target}, }; use url::Url; diff --git a/tufaceous/src/dispatch.rs b/tufaceous/src/dispatch.rs index ed0c63f7879..f5162870f6e 100644 --- a/tufaceous/src/dispatch.rs +++ b/tufaceous/src/dispatch.rs @@ -2,14 +2,14 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::Utf8PathBuf; use chrono::{DateTime, Utc}; use clap::{CommandFactory, Parser}; use omicron_common::{api::external::SemverVersion, update::ArtifactKind}; use tufaceous_lib::{ - assemble::{ArtifactManifest, OmicronRepoAssembler}, AddArtifact, ArchiveExtractor, Key, OmicronRepo, + assemble::{ArtifactManifest, OmicronRepoAssembler}, }; #[derive(Debug, Parser)] diff --git a/update-common/src/artifacts/artifacts_with_plan.rs b/update-common/src/artifacts/artifacts_with_plan.rs index 2a7a27a9f66..42747db3c1c 100644 --- a/update-common/src/artifacts/artifacts_with_plan.rs +++ b/update-common/src/artifacts/artifacts_with_plan.rs @@ -20,8 +20,8 @@ use omicron_common::update::ArtifactHash; use omicron_common::update::ArtifactHashId; use omicron_common::update::ArtifactId; use sha2::{Digest, Sha256}; -use slog::info; use slog::Logger; +use slog::info; use std::collections::BTreeMap; use std::collections::HashMap; use std::io; diff --git a/update-common/src/artifacts/extracted_artifacts.rs b/update-common/src/artifacts/extracted_artifacts.rs index dd5b1edc8ba..75c5a7ebe43 100644 --- a/update-common/src/artifacts/extracted_artifacts.rs +++ b/update-common/src/artifacts/extracted_artifacts.rs @@ -14,8 +14,8 @@ use omicron_common::update::ArtifactHashId; use omicron_common::update::ArtifactKind; use sha2::Digest; use sha2::Sha256; -use slog::info; use slog::Logger; +use slog::info; use std::io; use std::io::Write; use std::sync::Arc; diff --git a/update-common/src/artifacts/update_plan.rs b/update-common/src/artifacts/update_plan.rs index 297d66f9868..0ec5adfdc27 100644 --- a/update-common/src/artifacts/update_plan.rs +++ b/update-common/src/artifacts/update_plan.rs @@ -28,12 +28,12 @@ use omicron_common::update::ArtifactHash; use omicron_common::update::ArtifactHashId; use omicron_common::update::ArtifactId; use omicron_common::update::ArtifactKind; -use slog::info; use slog::Logger; -use std::collections::btree_map; -use std::collections::hash_map; +use slog::info; use std::collections::BTreeMap; use std::collections::HashMap; +use std::collections::btree_map; +use std::collections::hash_map; use std::io; use tokio::io::AsyncReadExt; use tokio::runtime::Handle; @@ -1063,7 +1063,7 @@ impl<'a> UpdatePlanBuilder<'a> { kind, v1: version.clone(), v2: v.id.version.clone(), - }) + }); } } } @@ -1277,11 +1277,11 @@ mod tests { use super::*; use bytes::Bytes; - use flate2::{write::GzEncoder, Compression}; + use flate2::{Compression, write::GzEncoder}; use futures::StreamExt; use omicron_brand_metadata::{ArchiveType, LayerInfo, Metadata}; use omicron_test_utils::dev::test_setup_log; - use rand::{distributions::Standard, thread_rng, Rng}; + use rand::{Rng, distributions::Standard, thread_rng}; use sha2::{Digest, Sha256}; use tufaceous_lib::{ CompositeControlPlaneArchiveBuilder, CompositeEntry, MtimeSource, diff --git a/update-common/src/errors.rs b/update-common/src/errors.rs index d4dc9c6bfc4..e3d7d3fd02b 100644 --- a/update-common/src/errors.rs +++ b/update-common/src/errors.rs @@ -130,9 +130,7 @@ pub enum RepositoryError { error: hubtools::CabooseError, }, - #[error( - "error reading board from hubris caboose of {0:?}: non-utf8 value" - )] + #[error("error reading board from hubris caboose of {0:?}: non-utf8 value")] ReadHubrisCabooseBoardUtf8(ArtifactId), #[error("error reading name from hubris caboose of {0:?}: non-utf8 value")] diff --git a/update-engine/examples/update-engine-basic/display.rs b/update-engine/examples/update-engine-basic/display.rs index 891bdce6d38..c88c33db985 100644 --- a/update-engine/examples/update-engine-basic/display.rs +++ b/update-engine/examples/update-engine-basic/display.rs @@ -6,9 +6,9 @@ use std::{borrow::Cow, time::Duration}; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use debug_ignore::DebugIgnore; -use indexmap::{map::Entry, IndexMap}; +use indexmap::{IndexMap, map::Entry}; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use owo_colors::OwoColorize; use tokio::{sync::mpsc, task::JoinHandle}; @@ -18,12 +18,12 @@ use update_engine::{ }; use crate::{ + DisplayStyle, spec::{ Event, EventBuffer, ExampleComponent, ExampleStepId, ExampleStepMetadata, ProgressEvent, ProgressEventKind, StepEventKind, StepInfoWithMetadata, StepOutcome, }, - DisplayStyle, }; /// An example that displays an event stream on the command line. diff --git a/update-engine/examples/update-engine-basic/main.rs b/update-engine/examples/update-engine-basic/main.rs index 95fe3c54dc3..70f31e0f59a 100644 --- a/update-engine/examples/update-engine-basic/main.rs +++ b/update-engine/examples/update-engine-basic/main.rs @@ -6,7 +6,7 @@ use std::{io::IsTerminal, time::Duration}; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use buf_list::BufList; use bytes::Buf; use camino::Utf8PathBuf; @@ -22,8 +22,8 @@ use spec::{ }; use tokio::{io::AsyncWriteExt, sync::mpsc}; use update_engine::{ - events::{Event, ProgressUnits}, StepContext, StepSuccess, + events::{Event, ProgressUnits}, }; mod display; diff --git a/update-engine/examples/update-engine-basic/spec.rs b/update-engine/examples/update-engine-basic/spec.rs index 35e469463b7..e454c8f6c46 100644 --- a/update-engine/examples/update-engine-basic/spec.rs +++ b/update-engine/examples/update-engine-basic/spec.rs @@ -8,9 +8,9 @@ use std::fmt; use camino::Utf8PathBuf; use schemars::{ + JsonSchema, gen::SchemaGenerator, schema::{Schema, SchemaObject}, - JsonSchema, }; use serde::{Deserialize, Serialize}; use update_engine::StepSpec; diff --git a/update-engine/src/buffer.rs b/update-engine/src/buffer.rs index e3ac02458ad..aeacdfc97b5 100644 --- a/update-engine/src/buffer.rs +++ b/update-engine/src/buffer.rs @@ -17,12 +17,12 @@ use indexmap::IndexMap; use petgraph::{prelude::*, visit::Walker}; use crate::{ + ExecutionId, NestedSpec, StepSpec, display::AbortMessageDisplay, events::{ Event, EventReport, ProgressEvent, ProgressEventKind, StepEvent, StepEventKind, StepEventPriority, StepInfo, StepOutcome, }, - ExecutionId, NestedSpec, StepSpec, }; /// A receiver for events that provides a pull-based model with periodic @@ -1749,14 +1749,14 @@ impl fmt::Display for RootEventIndex { mod tests { use std::collections::HashSet; - use anyhow::{bail, ensure, Context}; + use anyhow::{Context, bail, ensure}; use indexmap::IndexSet; use omicron_test_utils::dev::test_setup_log; - use serde::{de::IntoDeserializer, Deserialize}; + use serde::{Deserialize, de::IntoDeserializer}; use crate::{ events::ProgressCounter, - test_utils::{generate_test_events, GenerateTestEventsKind, TestSpec}, + test_utils::{GenerateTestEventsKind, TestSpec, generate_test_events}, }; use super::*; @@ -2026,7 +2026,8 @@ mod tests { data2.sort_key() ); ensure!( - data1.parent_key_and_child_index() == data2.parent_key_and_child_index(), + data1.parent_key_and_child_index() + == data2.parent_key_and_child_index(), "buffers have same parent key and child index at index {} ({:?} vs {:?})", ix, data1.parent_key_and_child_index(), diff --git a/update-engine/src/context.rs b/update-engine/src/context.rs index b0666858bc3..b9acef9b5ab 100644 --- a/update-engine/src/context.rs +++ b/update-engine/src/context.rs @@ -14,12 +14,12 @@ use tokio::sync::{mpsc, oneshot}; use tokio::time::Instant; use crate::errors::NestedEngineError; +use crate::{EventBuffer, ExecutionId}; use crate::{ + NestedError, NestedSpec, StepSpec, UpdateEngine, errors::ExecutionError, events::{Event, EventReport, StepEventKind, StepProgress}, - NestedError, NestedSpec, StepSpec, UpdateEngine, }; -use crate::{EventBuffer, ExecutionId}; /// Context for a step's execution function. /// diff --git a/update-engine/src/display/group_display.rs b/update-engine/src/display/group_display.rs index 7d99150a9fb..f48426fc920 100644 --- a/update-engine/src/display/group_display.rs +++ b/update-engine/src/display/group_display.rs @@ -8,18 +8,18 @@ use std::{borrow::Borrow, collections::BTreeMap, fmt, time::Duration}; use libsw::TokioSw; use owo_colors::OwoColorize; -use swrite::{swrite, SWrite}; +use swrite::{SWrite, swrite}; use unicode_width::UnicodeWidthStr; use crate::{ - display::ProgressRatioDisplay, errors::UnknownReportKey, - events::EventReport, EventBuffer, ExecutionStatus, ExecutionTerminalInfo, - StepSpec, TerminalKind, + EventBuffer, ExecutionStatus, ExecutionTerminalInfo, StepSpec, + TerminalKind, display::ProgressRatioDisplay, errors::UnknownReportKey, + events::EventReport, }; use super::{ + HEADER_WIDTH, LineDisplayShared, LineDisplayStyles, line_display_shared::{LineDisplayFormatter, LineDisplayOutput}, - LineDisplayShared, LineDisplayStyles, HEADER_WIDTH, }; /// A displayer that simultaneously manages and shows line-based output for @@ -428,7 +428,9 @@ impl SingleState { // non-empty event report has been received, the // event buffer never goes back to the NotStarted // state. - unreachable!("illegal state transition from Running to NotStarted") + unreachable!( + "illegal state transition from Running to NotStarted" + ) } ApplyReportResult::Running(root_total_elapsed) => { (SingleStateTag::Running, Some(root_total_elapsed)) @@ -624,7 +626,7 @@ mod tests { use super::*; - use crate::test_utils::{generate_test_events, GenerateTestEventsKind}; + use crate::test_utils::{GenerateTestEventsKind, generate_test_events}; #[tokio::test] async fn test_stats() { diff --git a/update-engine/src/display/line_display.rs b/update-engine/src/display/line_display.rs index f6005a9f9e1..e18d25c39f8 100644 --- a/update-engine/src/display/line_display.rs +++ b/update-engine/src/display/line_display.rs @@ -13,8 +13,8 @@ use std::time::Duration; use crate::{EventBuffer, ExecutionTerminalInfo, StepSpec}; use super::{ - line_display_shared::LineDisplayOutput, LineDisplayFormatter, - LineDisplayShared, + LineDisplayFormatter, LineDisplayShared, + line_display_shared::LineDisplayOutput, }; /// A line-oriented display. diff --git a/update-engine/src/display/line_display_shared.rs b/update-engine/src/display/line_display_shared.rs index c11aadf3e52..71245e0ee09 100644 --- a/update-engine/src/display/line_display_shared.rs +++ b/update-engine/src/display/line_display_shared.rs @@ -15,16 +15,16 @@ use std::{ use chrono::{DateTime, Utc}; use owo_colors::OwoColorize; -use swrite::{swrite, SWrite as _}; +use swrite::{SWrite as _, swrite}; use crate::{ + EventBuffer, ExecutionId, ExecutionTerminalInfo, StepKey, StepSpec, + TerminalKind, display::ProgressRatioDisplay, events::{ ProgressCounter, ProgressEvent, ProgressEventKind, StepEvent, StepEventKind, StepInfo, StepOutcome, }, - EventBuffer, ExecutionId, ExecutionTerminalInfo, StepKey, StepSpec, - TerminalKind, }; use super::LineDisplayStyles; diff --git a/update-engine/src/engine.rs b/update-engine/src/engine.rs index 35c4f1cab15..09e254807bb 100644 --- a/update-engine/src/engine.rs +++ b/update-engine/src/engine.rs @@ -27,14 +27,14 @@ use tokio::{ use uuid::Uuid; use crate::{ + AsError, CompletionContext, MetadataContext, NestedSpec, StepContext, + StepContextPayload, StepHandle, StepSpec, errors::ExecutionError, events::{ Event, ProgressEvent, ProgressEventKind, StepComponentSummary, StepEvent, StepEventKind, StepInfo, StepInfoWithMetadata, StepOutcome, StepProgress, }, - AsError, CompletionContext, MetadataContext, NestedSpec, StepContext, - StepContextPayload, StepHandle, StepSpec, }; /// Makes an MPSC channel suitable for the update engine. @@ -43,8 +43,8 @@ use crate::{ /// [`tokio::sync::mpsc::channel`] that creates a channel of the appropriate /// size, and may aid in type inference. #[inline] -pub fn channel( -) -> (mpsc::Sender>, mpsc::Receiver>) { +pub fn channel() +-> (mpsc::Sender>, mpsc::Receiver>) { // This is a large enough channel to handle incoming messages without // stalling. const CHANNEL_SIZE: usize = 256; diff --git a/update-engine/src/errors.rs b/update-engine/src/errors.rs index 0607ad6e271..5346d15d8af 100644 --- a/update-engine/src/errors.rs +++ b/update-engine/src/errors.rs @@ -11,7 +11,7 @@ use std::{borrow::Cow, collections::VecDeque, error, fmt}; use derive_where::derive_where; use tokio::sync::mpsc; -use crate::{events::Event, AsError, StepSpec}; +use crate::{AsError, StepSpec, events::Event}; // NOTE: have to hand write `ExecutionError` and `NestedEngineError` impls // because #[source] doesn't work for AsError. diff --git a/update-engine/src/events.rs b/update-engine/src/events.rs index 900a9776f5c..c9cbc827520 100644 --- a/update-engine/src/events.rs +++ b/update-engine/src/events.rs @@ -17,8 +17,8 @@ use serde::{Deserialize, Serialize}; use serde_with::rust::deserialize_ignore_any; use crate::{ - errors::ConvertGenericError, AsError, ExecutionId, GenericSpec, NestedSpec, - StepSpec, + AsError, ExecutionId, GenericSpec, NestedSpec, StepSpec, + errors::ConvertGenericError, }; #[derive_where(Clone, Debug, PartialEq, Eq)] diff --git a/update-engine/src/spec.rs b/update-engine/src/spec.rs index bb017be3f61..59afee0640e 100644 --- a/update-engine/src/spec.rs +++ b/update-engine/src/spec.rs @@ -9,7 +9,7 @@ use std::{fmt, fmt::Write, marker::PhantomData}; use anyhow::anyhow; use indent_write::fmt::IndentWriter; use schemars::JsonSchema; -use serde::{de::DeserializeOwned, Serialize}; +use serde::{Serialize, de::DeserializeOwned}; /// A specification for an [`UpdateEngine`](crate::UpdateEngine). /// diff --git a/update-engine/src/test_utils.rs b/update-engine/src/test_utils.rs index 02b267f6d23..bc21dd07400 100644 --- a/update-engine/src/test_utils.rs +++ b/update-engine/src/test_utils.rs @@ -11,8 +11,8 @@ use tokio::sync::oneshot; use tokio_stream::wrappers::ReceiverStream; use crate::{ - events::{Event, ProgressUnits, StepProgress}, EventBuffer, ExecutionId, StepContext, StepSpec, StepSuccess, UpdateEngine, + events::{Event, ProgressUnits, StepProgress}, }; #[derive(JsonSchema)] diff --git a/wicket-common/src/preflight_check.rs b/wicket-common/src/preflight_check.rs index e13be0a9d75..01b0854c7ee 100644 --- a/wicket-common/src/preflight_check.rs +++ b/wicket-common/src/preflight_check.rs @@ -25,9 +25,7 @@ pub enum UplinkPreflightTerminalError { err: DpdError, port_id: PortId, }, - #[error( - "failed to remove host OS route {destination} -> {nexthop}: {err}" - )] + #[error("failed to remove host OS route {destination} -> {nexthop}: {err}")] RemoveHostRoute { err: String, destination: IpNet, nexthop: IpAddr }, #[error("failed to remove uplink SMF property {property:?}: {err}")] RemoveSmfProperty { property: String, err: String }, diff --git a/wicket-common/src/update_events.rs b/wicket-common/src/update_events.rs index 630ad2d905c..eb360e306ed 100644 --- a/wicket-common/src/update_events.rs +++ b/wicket-common/src/update_events.rs @@ -12,8 +12,8 @@ use serde::Serialize; use std::fmt; use std::sync::Arc; use thiserror::Error; -use update_engine::errors::NestedEngineError; use update_engine::StepSpec; +use update_engine::errors::NestedEngineError; #[derive(JsonSchema)] pub enum WicketdEngineSpec {} @@ -205,7 +205,9 @@ pub enum UpdateTerminalError { #[source] error: Arc, }, - #[error("uploading trampoline phase 2 to MGS cancelled (was a new TUF repo uploaded?)")] + #[error( + "uploading trampoline phase 2 to MGS cancelled (was a new TUF repo uploaded?)" + )] TrampolinePhase2UploadCancelled, #[error("downloading installinator failed")] DownloadingInstallinatorFailed { diff --git a/wicket-dbg/src/bin/wicket-dbg-server.rs b/wicket-dbg/src/bin/wicket-dbg-server.rs index 531cba30d4e..dfe63d71735 100644 --- a/wicket-dbg/src/bin/wicket-dbg-server.rs +++ b/wicket-dbg/src/bin/wicket-dbg-server.rs @@ -2,11 +2,11 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use bytes::BytesMut; use camino::Utf8PathBuf; -use slog::info; use slog::Drain; +use slog::info; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use wicket_dbg::{Cmd, Runner, RunnerHandle}; diff --git a/wicket-dbg/src/lib.rs b/wicket-dbg/src/lib.rs index 5fc900a5e82..e9a54a97218 100644 --- a/wicket-dbg/src/lib.rs +++ b/wicket-dbg/src/lib.rs @@ -87,10 +87,6 @@ pub struct DebugState { impl Rpy { fn is_err(&self) -> bool { - if let Rpy::Err(_) = self { - true - } else { - false - } + if let Rpy::Err(_) = self { true } else { false } } } diff --git a/wicket-dbg/src/runner.rs b/wicket-dbg/src/runner.rs index 2e696c3ced6..c9167d581fb 100644 --- a/wicket-dbg/src/runner.rs +++ b/wicket-dbg/src/runner.rs @@ -8,8 +8,8 @@ use crate::{Cmd, DebugState, Rpy}; use camino::Utf8PathBuf; use crossterm::execute; use crossterm::terminal::{ - disable_raw_mode, enable_raw_mode, EnterAlternateScreen, - LeaveAlternateScreen, + EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, + enable_raw_mode, }; use slog::Logger; use std::collections::BTreeSet; diff --git a/wicket/src/cli/preflight.rs b/wicket/src/cli/preflight.rs index 3e8d5027ba8..0d6cf26f944 100644 --- a/wicket/src/cli/preflight.rs +++ b/wicket/src/cli/preflight.rs @@ -5,9 +5,9 @@ //! Support for preflight checks via wicketd. use crate::wicketd::create_wicketd_client; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::bail; use clap::Subcommand; use indicatif::ProgressBar; use indicatif::ProgressStyle; @@ -22,8 +22,8 @@ use wicket_common::preflight_check::StepEventKind; use wicket_common::preflight_check::StepInfo; use wicket_common::preflight_check::StepInfoWithMetadata; use wicket_common::preflight_check::StepOutcome; -use wicketd_client::types::PreflightUplinkCheckOptions; use wicketd_client::Client; +use wicketd_client::types::PreflightUplinkCheckOptions; const WICKETD_TIMEOUT: Duration = Duration::from_secs(5); diff --git a/wicket/src/cli/rack_setup.rs b/wicket/src/cli/rack_setup.rs index 84e82bf173c..965d06796bd 100644 --- a/wicket/src/cli/rack_setup.rs +++ b/wicket/src/cli/rack_setup.rs @@ -8,9 +8,9 @@ use crate::ui::defaults::style::BULLET_ICON; use crate::ui::defaults::style::CHECK_ICON; use crate::ui::defaults::style::WARN_ICON; use crate::wicketd::create_wicketd_client; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::bail; use clap::Args; use clap::Subcommand; use clap::ValueEnum; diff --git a/wicket/src/cli/rack_update.rs b/wicket/src/cli/rack_update.rs index 44a2076b227..a4ad982324a 100644 --- a/wicket/src/cli/rack_update.rs +++ b/wicket/src/cli/rack_update.rs @@ -13,19 +13,19 @@ use std::{ time::Duration, }; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use camino::Utf8PathBuf; use clap::{Args, Subcommand, ValueEnum}; use slog::Logger; use tokio::{sync::watch, task::JoinHandle}; use update_engine::{ - display::{GroupDisplay, LineDisplayStyles}, EventBuffer, NestedError, + display::{GroupDisplay, LineDisplayStyles}, }; use wicket_common::{ + WICKETD_TIMEOUT, rack_update::ClearUpdateStateResponse, update_events::{EventReport, WicketdEngineSpec}, - WICKETD_TIMEOUT, }; use wicketd_client::types::{ ClearUpdateStateParams, GetArtifactsAndEventReportsResponse, @@ -35,8 +35,8 @@ use wicketd_client::types::{ use crate::{ cli::GlobalOpts, state::{ - parse_event_report_map, ComponentId, CreateClearUpdateStateOptions, - CreateStartUpdateOptions, + ComponentId, CreateClearUpdateStateOptions, CreateStartUpdateOptions, + parse_event_report_map, }, wicketd::create_wicketd_client, }; @@ -597,7 +597,9 @@ impl ComponentIdSelector { component_ids.insert(ComponentId::new_psc(*psc)?); } if component_ids.is_empty() { - bail!("at least one component ID must be selected via --sled, --switch or --psc"); + bail!( + "at least one component ID must be selected via --sled, --switch or --psc" + ); } Ok(component_ids) diff --git a/wicket/src/dispatch.rs b/wicket/src/dispatch.rs index fd6f7cd2900..994c85eb288 100644 --- a/wicket/src/dispatch.rs +++ b/wicket/src/dispatch.rs @@ -6,15 +6,15 @@ use std::net::{Ipv6Addr, SocketAddrV6}; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use camino::{Utf8Path, Utf8PathBuf}; use clap::Parser; -use omicron_common::{address::WICKETD_PORT, FileKv}; +use omicron_common::{FileKv, address::WICKETD_PORT}; use slog::Drain; use crate::{ - cli::{CommandOutput, ShellApp}, Runner, + cli::{CommandOutput, ShellApp}, }; pub fn exec() -> Result<()> { diff --git a/wicket/src/events.rs b/wicket/src/events.rs index 55f28f5acb9..c4ba1f36d75 100644 --- a/wicket/src/events.rs +++ b/wicket/src/events.rs @@ -1,7 +1,7 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use crate::{keymap::Cmd, state::ComponentId, State}; +use crate::{State, keymap::Cmd, state::ComponentId}; use camino::Utf8PathBuf; use humantime::format_rfc3339; use serde::{Deserialize, Serialize}; @@ -67,11 +67,7 @@ pub enum Event { impl Event { pub fn is_tick(&self) -> bool { - if let Event::Tick = self { - true - } else { - false - } + if let Event::Tick = self { true } else { false } } } diff --git a/wicket/src/helpers.rs b/wicket/src/helpers.rs index bb4155231c0..a1abba34912 100644 --- a/wicket/src/helpers.rs +++ b/wicket/src/helpers.rs @@ -6,7 +6,7 @@ use std::env::VarError; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use wicket_common::rack_update::{UpdateSimulatedResult, UpdateTestError}; pub(crate) fn get_update_test_error( diff --git a/wicket/src/runner.rs b/wicket/src/runner.rs index 0e201478a8e..6287dfcfb91 100644 --- a/wicket/src/runner.rs +++ b/wicket/src/runner.rs @@ -7,21 +7,21 @@ use crossterm::event::EventStream; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::execute; use crossterm::terminal::{ - disable_raw_mode, enable_raw_mode, EnterAlternateScreen, - LeaveAlternateScreen, + EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, + enable_raw_mode, }; use futures::StreamExt; -use ratatui::backend::CrosstermBackend; use ratatui::Terminal; +use ratatui::backend::CrosstermBackend; use slog::Logger; use slog::{debug, error, info}; -use std::io::{stdout, Stdout}; +use std::io::{Stdout, stdout}; use std::net::SocketAddrV6; use std::time::Instant; use tokio::sync::mpsc::{ - unbounded_channel, UnboundedReceiver, UnboundedSender, + UnboundedReceiver, UnboundedSender, unbounded_channel, }; -use tokio::time::{interval, Duration}; +use tokio::time::{Duration, interval}; use wicket_common::rack_update::AbortUpdateOptions; use crate::events::EventReportMap; diff --git a/wicket/src/state/inventory.rs b/wicket/src/state/inventory.rs index 858562c675d..f88ceea4842 100644 --- a/wicket/src/state/inventory.rs +++ b/wicket/src/state/inventory.rs @@ -4,7 +4,7 @@ //! Information about all top-level Oxide components (sleds, switches, PSCs) -use anyhow::{bail, Result}; +use anyhow::{Result, bail}; use omicron_common::api::internal::nexus::KnownArtifactKind; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; diff --git a/wicket/src/state/mod.rs b/wicket/src/state/mod.rs index 9e6da97d4fc..8cfc422bb02 100644 --- a/wicket/src/state/mod.rs +++ b/wicket/src/state/mod.rs @@ -12,14 +12,14 @@ mod update; pub use force_update::ForceUpdateState; pub use inventory::{ - Component, ComponentId, Inventory, ParsableComponentId, ALL_COMPONENT_IDS, + ALL_COMPONENT_IDS, Component, ComponentId, Inventory, ParsableComponentId, }; pub use rack::{KnightRiderMode, RackState}; pub use status::ServiceStatus; pub use update::{ - parse_event_report_map, update_component_title, ArtifactVersions, - CreateClearUpdateStateOptions, CreateStartUpdateOptions, RackUpdateState, - UpdateItemState, + ArtifactVersions, CreateClearUpdateStateOptions, CreateStartUpdateOptions, + RackUpdateState, UpdateItemState, parse_event_report_map, + update_component_title, }; use serde::{Deserialize, Serialize}; diff --git a/wicket/src/state/update.rs b/wicket/src/state/update.rs index f143ac36452..1b93c76ef4a 100644 --- a/wicket/src/state/update.rs +++ b/wicket/src/state/update.rs @@ -16,7 +16,7 @@ use crate::{ ui::defaults::style, }; -use super::{ComponentId, ParsableComponentId, ALL_COMPONENT_IDS}; +use super::{ALL_COMPONENT_IDS, ComponentId, ParsableComponentId}; use omicron_common::api::internal::nexus::KnownArtifactKind; use serde::{Deserialize, Serialize}; use slog::Logger; diff --git a/wicket/src/ui/controls/mod.rs b/wicket/src/ui/controls/mod.rs index a2682b8052b..a4cabf3afcc 100644 --- a/wicket/src/ui/controls/mod.rs +++ b/wicket/src/ui/controls/mod.rs @@ -3,7 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::{Action, Cmd, State}; -use ratatui::{layout::Rect, Frame}; +use ratatui::{Frame, layout::Rect}; /// A [`Control`] is the an item on a screen that can be selected and interacted with. /// Control's render [`ratatui::widgets::Widget`]s when drawn. diff --git a/wicket/src/ui/defaults/style.rs b/wicket/src/ui/defaults/style.rs index 2ede7d1bb25..7e0eb0d98b8 100644 --- a/wicket/src/ui/defaults/style.rs +++ b/wicket/src/ui/defaults/style.rs @@ -90,11 +90,7 @@ pub fn warning_update_bold() -> Style { } pub fn line(active: bool) -> Style { - if active { - selected_line() - } else { - deselected() - } + if active { selected_line() } else { deselected() } } pub fn warning() -> Style { @@ -102,11 +98,7 @@ pub fn warning() -> Style { } pub fn header(active: bool) -> Style { - if active { - selected() - } else { - deselected() - } + if active { selected() } else { deselected() } } pub fn popup_highlight() -> Style { diff --git a/wicket/src/ui/main.rs b/wicket/src/ui/main.rs index ae6924071a3..e6603b8df4f 100644 --- a/wicket/src/ui/main.rs +++ b/wicket/src/ui/main.rs @@ -9,12 +9,12 @@ use crate::ui::defaults::colors::*; use crate::ui::defaults::style; use crate::ui::widgets::Fade; use crate::{Action, Cmd, State, Term}; +use ratatui::Frame; use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect}; use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, BorderType, Borders, List, ListItem, Paragraph}; -use ratatui::Frame; -use slog::{o, Logger}; +use slog::{Logger, o}; use wicketd_client::types::GetLocationResponse; /// The [`MainScreen`] is the primary UI element of the terminal, covers the diff --git a/wicket/src/ui/mod.rs b/wicket/src/ui/mod.rs index 1430a676592..d91c20a095f 100644 --- a/wicket/src/ui/mod.rs +++ b/wicket/src/ui/mod.rs @@ -12,7 +12,7 @@ mod wrap; use crate::{Action, Cmd, State, Term}; use ratatui::widgets::ListState; -use slog::{o, Logger}; +use slog::{Logger, o}; use main::MainScreen; use splash::SplashScreen; diff --git a/wicket/src/ui/panes/mod.rs b/wicket/src/ui/panes/mod.rs index 42cb205d501..86695e7f04b 100644 --- a/wicket/src/ui/panes/mod.rs +++ b/wicket/src/ui/panes/mod.rs @@ -7,8 +7,8 @@ mod rack_setup; mod update; pub use super::Control; -use crate::ui::defaults::style; use crate::Cmd; +use crate::ui::defaults::style; pub use overview::OverviewPane; pub use rack_setup::RackSetupPane; use ratatui::layout::{Constraint, Direction, Layout, Rect}; diff --git a/wicket/src/ui/panes/overview.rs b/wicket/src/ui/panes/overview.rs index b807a13a973..15cc9c6b4ea 100644 --- a/wicket/src/ui/panes/overview.rs +++ b/wicket/src/ui/panes/overview.rs @@ -5,23 +5,23 @@ use std::borrow::Cow; use std::collections::BTreeMap; -use super::help_text; use super::ComputedScrollOffset; use super::Control; use super::PendingScroll; +use super::help_text; use crate::state::Component; -use crate::state::{ComponentId, ALL_COMPONENT_IDS}; +use crate::state::{ALL_COMPONENT_IDS, ComponentId}; use crate::ui::defaults::colors::*; use crate::ui::defaults::style; use crate::ui::widgets::IgnitionPopup; use crate::ui::widgets::{BoxConnector, BoxConnectorKind, Rack}; use crate::ui::wrap::wrap_text; use crate::{Action, Cmd, State}; +use ratatui::Frame; use ratatui::layout::{Constraint, Direction, Layout, Rect}; use ratatui::style::Style; use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{Block, BorderType, Borders, Paragraph}; -use ratatui::Frame; use wicket_common::inventory::RotState; use wicket_common::inventory::SpComponentCaboose; use wicket_common::inventory::SpComponentInfo; diff --git a/wicket/src/ui/panes/rack_setup.rs b/wicket/src/ui/panes/rack_setup.rs index 422c47b2bdd..fcc4acf5609 100644 --- a/wicket/src/ui/panes/rack_setup.rs +++ b/wicket/src/ui/panes/rack_setup.rs @@ -2,10 +2,14 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -use super::help_text; -use super::push_text_lines; use super::ComputedScrollOffset; use super::PendingScroll; +use super::help_text; +use super::push_text_lines; +use crate::Action; +use crate::Cmd; +use crate::Control; +use crate::State; use crate::keymap::ShowPopupCmd; use crate::ui::defaults::style; use crate::ui::widgets::BoxConnector; @@ -13,16 +17,13 @@ use crate::ui::widgets::BoxConnectorKind; use crate::ui::widgets::ButtonText; use crate::ui::widgets::PopupBuilder; use crate::ui::widgets::PopupScrollOffset; -use crate::Action; -use crate::Cmd; -use crate::Control; -use crate::State; use itertools::Itertools; use omicron_common::address::IpRange; use omicron_common::api::internal::shared::AllowedSourceIps; use omicron_common::api::internal::shared::BgpConfig; use omicron_common::api::internal::shared::LldpPortConfig; use omicron_common::api::internal::shared::RouteConfig; +use ratatui::Frame; use ratatui::layout::Constraint; use ratatui::layout::Direction; use ratatui::layout::Layout; @@ -34,7 +35,6 @@ use ratatui::widgets::Block; use ratatui::widgets::BorderType; use ratatui::widgets::Borders; use ratatui::widgets::Paragraph; -use ratatui::Frame; use sled_hardware_types::Baseboard; use std::borrow::Cow; use wicket_common::rack_setup::BgpAuthKeyInfo; diff --git a/wicket/src/ui/panes/update.rs b/wicket/src/ui/panes/update.rs index 1b2a1ed295d..50d3fda99d9 100644 --- a/wicket/src/ui/panes/update.rs +++ b/wicket/src/ui/panes/update.rs @@ -5,11 +5,11 @@ use std::borrow::Cow; use std::collections::BTreeMap; -use super::{align_by, help_text, push_text_lines, Control, PendingScroll}; +use super::{Control, PendingScroll, align_by, help_text, push_text_lines}; use crate::keymap::ShowPopupCmd; use crate::state::{ - update_component_title, ArtifactVersions, ComponentId, Inventory, - UpdateItemState, ALL_COMPONENT_IDS, + ALL_COMPONENT_IDS, ArtifactVersions, ComponentId, Inventory, + UpdateItemState, update_component_title, }; use crate::ui::defaults::style; use crate::ui::widgets::{ @@ -20,14 +20,14 @@ use crate::ui::wrap::wrap_text; use crate::{Action, Cmd, State}; use indexmap::IndexMap; use omicron_common::api::internal::nexus::KnownArtifactKind; +use ratatui::Frame; use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect}; use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{ Block, BorderType, Borders, Cell, List, ListItem, ListState, Paragraph, Row, Table, }; -use ratatui::Frame; -use slog::{info, o, Logger}; +use slog::{Logger, info, o}; use tui_tree_widget::{Tree, TreeItem, TreeState}; use update_engine::display::ProgressRatioDisplay; use update_engine::{ @@ -1306,11 +1306,11 @@ impl UpdatePane { // state.rack_state.selected be changed in the // meantime) so log this. slog::warn!( - self.log, - "currently waiting on start update response \ + self.log, + "currently waiting on start update response \ for {} but received response for {component_id}", - state.rack_state.selected - ); + state.rack_state.selected + ); None } } @@ -2435,7 +2435,7 @@ fn artifact_version( // Switches and PSCs do not have a host. (ComponentId::Switch(_), UpdateComponent::Host) | (ComponentId::Psc(_), UpdateComponent::Host) => { - return "N/A".to_string() + return "N/A".to_string(); } }; match versions.get(&artifact) { diff --git a/wicket/src/ui/splash.rs b/wicket/src/ui/splash.rs index 18d7b37f082..ce5ce2fa58d 100644 --- a/wicket/src/ui/splash.rs +++ b/wicket/src/ui/splash.rs @@ -9,11 +9,11 @@ use super::defaults::colors::*; use super::defaults::dimensions::RectExt; use super::defaults::style; -use super::widgets::{Logo, LogoState, LOGO_HEIGHT, LOGO_WIDTH}; +use super::widgets::{LOGO_HEIGHT, LOGO_WIDTH, Logo, LogoState}; use crate::{Cmd, Term}; +use ratatui::Frame; use ratatui::style::Style; use ratatui::widgets::Block; -use ratatui::Frame; const TOTAL_FRAMES: usize = 100; diff --git a/wicket/src/ui/widgets/mod.rs b/wicket/src/ui/widgets/mod.rs index fd5ed18e3a9..99d55ce691d 100644 --- a/wicket/src/ui/widgets/mod.rs +++ b/wicket/src/ui/widgets/mod.rs @@ -12,7 +12,7 @@ mod popup; mod rack; mod status_view; -pub use animated_logo::{Logo, LogoState, LOGO_HEIGHT, LOGO_WIDTH}; +pub use animated_logo::{LOGO_HEIGHT, LOGO_WIDTH, Logo, LogoState}; pub use box_connector::{BoxConnector, BoxConnectorKind}; pub use fade::Fade; pub use ignition::IgnitionPopup; diff --git a/wicket/src/ui/widgets/rack.rs b/wicket/src/ui/widgets/rack.rs index 19c93951ae2..bc6a43476fa 100644 --- a/wicket/src/ui/widgets/rack.rs +++ b/wicket/src/ui/widgets/rack.rs @@ -413,9 +413,5 @@ type ComponentRectsMap = BTreeMap; /// Ensure that a u16 is an even number by adding 1 if necessary. pub fn make_even(val: u16) -> u16 { - if val % 2 == 0 { - val - } else { - val + 1 - } + if val % 2 == 0 { val } else { val + 1 } } diff --git a/wicket/src/ui/widgets/status_view.rs b/wicket/src/ui/widgets/status_view.rs index b9e981c9bc8..df107d6b24d 100644 --- a/wicket/src/ui/widgets/status_view.rs +++ b/wicket/src/ui/widgets/status_view.rs @@ -3,10 +3,10 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use ratatui::{ + Frame, layout::{Alignment, Rect}, text::Text, widgets::{Block, Borders, List, Paragraph, StatefulWidget, Widget}, - Frame, }; use super::{BoxConnector, BoxConnectorKind}; diff --git a/wicket/src/ui/wrap.rs b/wicket/src/ui/wrap.rs index 07fbc68acaf..33acd53e1b7 100644 --- a/wicket/src/ui/wrap.rs +++ b/wicket/src/ui/wrap.rs @@ -18,8 +18,8 @@ use itertools::{Itertools, Position}; use ratatui::text::{Line, Span, Text}; use textwrap::{ - core::{display_width, Fragment}, - wrap_algorithms::{wrap_optimal_fit, Penalties}, + core::{Fragment, display_width}, + wrap_algorithms::{Penalties, wrap_optimal_fit}, }; pub struct Options<'a> { diff --git a/wicket/src/wicketd.rs b/wicket/src/wicketd.rs index 635878e080b..5408fa893cd 100644 --- a/wicket/src/wicketd.rs +++ b/wicket/src/wicketd.rs @@ -4,16 +4,16 @@ //! Code for talking to wicketd -use slog::{o, warn, Logger}; +use slog::{Logger, o, warn}; use std::convert::From; use std::net::SocketAddrV6; use tokio::sync::mpsc::{self, Sender, UnboundedSender}; -use tokio::time::{interval, Duration, MissedTickBehavior}; +use tokio::time::{Duration, MissedTickBehavior, interval}; +use wicket_common::WICKETD_TIMEOUT; use wicket_common::inventory::{SpIdentifier, SpType}; use wicket_common::rack_update::{ AbortUpdateOptions, ClearUpdateStateOptions, StartUpdateOptions, }; -use wicket_common::WICKETD_TIMEOUT; use wicketd_client::types::{ ClearUpdateStateParams, GetInventoryParams, GetInventoryResponse, GetLocationResponse, IgnitionCommand, StartUpdateParams, diff --git a/wicketd/src/artifacts/server.rs b/wicketd/src/artifacts/server.rs index 4b3241762a9..850406c8dfa 100644 --- a/wicketd/src/artifacts/server.rs +++ b/wicketd/src/artifacts/server.rs @@ -13,13 +13,13 @@ use dropshot::Path; use dropshot::RequestContext; use dropshot::TypedBody; use futures::TryStreamExt; -use installinator_api::body_to_artifact_response; use installinator_api::InstallinatorApi; use installinator_api::ReportQuery; +use installinator_api::body_to_artifact_response; use installinator_common::EventReport; use omicron_common::update::ArtifactHashId; -use slog::error; use slog::Logger; +use slog::error; use super::WicketdArtifactStore; diff --git a/wicketd/src/bin/wicketd.rs b/wicketd/src/bin/wicketd.rs index bc23362daf4..67e9cfc1bff 100644 --- a/wicketd/src/bin/wicketd.rs +++ b/wicketd/src/bin/wicketd.rs @@ -4,12 +4,12 @@ //! Executable for wicketd: technician port based management service -use anyhow::{anyhow, Context}; +use anyhow::{Context, anyhow}; use camino::Utf8PathBuf; use clap::Parser; use omicron_common::{ address::Ipv6Subnet, - cmd::{fatal, CmdError}, + cmd::{CmdError, fatal}, }; use sled_hardware_types::Baseboard; use std::net::{Ipv6Addr, SocketAddrV6}; diff --git a/wicketd/src/bootstrap_addrs.rs b/wicketd/src/bootstrap_addrs.rs index dd13fe0f445..27efc892463 100644 --- a/wicketd/src/bootstrap_addrs.rs +++ b/wicketd/src/bootstrap_addrs.rs @@ -4,10 +4,10 @@ use futures::stream::FuturesUnordered; use omicron_ddm_admin_client::Client as DdmAdminClient; -use sled_hardware_types::underlay::BootstrapInterface; use sled_hardware_types::Baseboard; -use slog::warn; +use sled_hardware_types::underlay::BootstrapInterface; use slog::Logger; +use slog::warn; use std::collections::BTreeMap; use std::net::Ipv6Addr; use std::sync::Arc; diff --git a/wicketd/src/context.rs b/wicketd/src/context.rs index 307898200be..bbd3fc16fb2 100644 --- a/wicketd/src/context.rs +++ b/wicketd/src/context.rs @@ -4,14 +4,14 @@ //! User provided dropshot server context +use crate::MgsHandle; use crate::bootstrap_addrs::BootstrapPeers; use crate::preflight_check::PreflightCheckerHandler; use crate::rss_config::CurrentRssConfig; use crate::update_tracker::UpdateTracker; -use crate::MgsHandle; +use anyhow::Result; use anyhow::anyhow; use anyhow::bail; -use anyhow::Result; use internal_dns_resolver::Resolver; use sled_hardware_types::Baseboard; use slog::info; diff --git a/wicketd/src/http_entrypoints.rs b/wicketd/src/http_entrypoints.rs index 6cd8ee813a4..27a33db1a8d 100644 --- a/wicketd/src/http_entrypoints.rs +++ b/wicketd/src/http_entrypoints.rs @@ -4,12 +4,12 @@ //! HTTP entrypoint functions for wicketd -use crate::helpers::sps_to_string; +use crate::SmfConfigValues; use crate::helpers::SpIdentifierDisplay; +use crate::helpers::sps_to_string; use crate::mgs::GetInventoryError; use crate::mgs::MgsHandle; use crate::mgs::ShutdownInProgress; -use crate::SmfConfigValues; use bootstrap_agent_client::types::RackOperationStatus; use dropshot::ApiDescription; use dropshot::HttpError; @@ -27,6 +27,7 @@ use sled_hardware_types::Baseboard; use slog::o; use std::collections::BTreeMap; use std::collections::BTreeSet; +use wicket_common::WICKETD_TIMEOUT; use wicket_common::inventory::RackV1Inventory; use wicket_common::inventory::SpIdentifier; use wicket_common::inventory::SpType; @@ -35,7 +36,6 @@ use wicket_common::rack_setup::PutRssUserConfigInsensitive; use wicket_common::rack_update::AbortUpdateOptions; use wicket_common::rack_update::ClearUpdateStateResponse; use wicket_common::update_events::EventReport; -use wicket_common::WICKETD_TIMEOUT; use wicketd_api::*; use crate::ServerContext; diff --git a/wicketd/src/lib.rs b/wicketd/src/lib.rs index 1fbf278ead3..8041f5be0a9 100644 --- a/wicketd/src/lib.rs +++ b/wicketd/src/lib.rs @@ -15,7 +15,7 @@ mod preflight_check; mod rss_config; mod update_tracker; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{Context, Result, anyhow, bail}; use artifacts::{ WicketdArtifactStore, WicketdInstallinatorApiImpl, WicketdInstallinatorContext, @@ -30,11 +30,11 @@ use internal_dns_resolver::Resolver; use mgs::make_mgs_client; pub(crate) use mgs::{MgsHandle, MgsManager}; use nexus_proxy::NexusTcpProxy; -use omicron_common::address::{Ipv6Subnet, AZ_PREFIX}; use omicron_common::FileKv; +use omicron_common::address::{AZ_PREFIX, Ipv6Subnet}; use preflight_check::PreflightCheckerHandler; use sled_hardware_types::Baseboard; -use slog::{debug, error, o, Drain}; +use slog::{Drain, debug, error, o}; use std::sync::{Mutex, OnceLock}; use std::time::Duration; use std::{ diff --git a/wicketd/src/mgs.rs b/wicketd/src/mgs.rs index da09ac5802d..8eaf2d6765e 100644 --- a/wicketd/src/mgs.rs +++ b/wicketd/src/mgs.rs @@ -7,7 +7,7 @@ use futures::StreamExt; use gateway_client::types::SpIgnition; -use slog::{info, o, warn, Logger}; +use slog::{Logger, info, o, warn}; use std::collections::{BTreeMap, BTreeSet}; use std::net::SocketAddrV6; use tokio::sync::{mpsc, oneshot}; diff --git a/wicketd/src/mgs/inventory.rs b/wicketd/src/mgs/inventory.rs index 7d9aa586ad2..e56c5bb60af 100644 --- a/wicketd/src/mgs/inventory.rs +++ b/wicketd/src/mgs/inventory.rs @@ -10,15 +10,15 @@ use gateway_client::types::SpComponentInfo; use gateway_client::types::SpIgnition; use gateway_client::types::SpState; use gateway_messages::SpComponent; -use slog::warn; use slog::Logger; +use slog::warn; use std::collections::BTreeMap; use tokio::sync::mpsc; use tokio::sync::watch; use tokio::task; -use tokio::time::interval; use tokio::time::Duration; use tokio::time::Instant; +use tokio::time::interval; use tokio_stream::wrappers::ReceiverStream; use wicket_common::inventory::RotInventory; use wicket_common::inventory::SpIdentifier; diff --git a/wicketd/src/nexus_proxy.rs b/wicketd/src/nexus_proxy.rs index b55a4498536..934e2920889 100644 --- a/wicketd/src/nexus_proxy.rs +++ b/wicketd/src/nexus_proxy.rs @@ -7,10 +7,10 @@ use internal_dns_resolver::Resolver; use internal_dns_types::names::ServiceName; use omicron_common::address::NEXUS_TECHPORT_EXTERNAL_PORT; +use slog::Logger; use slog::info; use slog::o; use slog::warn; -use slog::Logger; use std::io; use std::net::SocketAddr; use std::net::SocketAddrV6; diff --git a/wicketd/src/preflight_check.rs b/wicketd/src/preflight_check.rs index 6863e41a84e..7789c0b5197 100644 --- a/wicketd/src/preflight_check.rs +++ b/wicketd/src/preflight_check.rs @@ -3,8 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use omicron_common::api::internal::shared::SwitchLocation; -use slog::o; use slog::Logger; +use slog::o; use std::net::IpAddr; use std::sync::Arc; use std::sync::Mutex; diff --git a/wicketd/src/preflight_check/uplink.rs b/wicketd/src/preflight_check/uplink.rs index 42210d77190..6dc9470891c 100644 --- a/wicketd/src/preflight_check/uplink.rs +++ b/wicketd/src/preflight_check/uplink.rs @@ -3,6 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use display_error_chain::DisplayErrorChain; +use dpd_client::Client as DpdClient; +use dpd_client::ClientState as DpdClientState; use dpd_client::types::LinkCreate; use dpd_client::types::LinkId; use dpd_client::types::LinkSettings; @@ -11,25 +13,23 @@ use dpd_client::types::PortFec as DpdPortFec; use dpd_client::types::PortId; use dpd_client::types::PortSettings; use dpd_client::types::PortSpeed as DpdPortSpeed; -use dpd_client::Client as DpdClient; -use dpd_client::ClientState as DpdClientState; use either::Either; +use hickory_resolver::TokioAsyncResolver; use hickory_resolver::config::NameServerConfigGroup; use hickory_resolver::config::ResolverConfig; use hickory_resolver::config::ResolverOpts; use hickory_resolver::error::ResolveErrorKind; -use hickory_resolver::TokioAsyncResolver; -use illumos_utils::zone::SVCCFG; use illumos_utils::PFEXEC; +use illumos_utils::zone::SVCCFG; +use omicron_common::OMICRON_DPD_TAG; use omicron_common::address::DENDRITE_PORT; use omicron_common::api::internal::shared::PortFec as OmicronPortFec; use omicron_common::api::internal::shared::PortSpeed as OmicronPortSpeed; use omicron_common::api::internal::shared::SwitchLocation; -use omicron_common::OMICRON_DPD_TAG; use oxnet::IpNet; +use slog::Logger; use slog::error; use slog::o; -use slog::Logger; use std::collections::BTreeSet; use std::collections::HashMap; use std::net::IpAddr; @@ -294,7 +294,7 @@ fn add_steps_for_single_local_uplink_preflight_check<'a>( Err(L2Failure::L1(failure)), "link not up due to earlier failure", ) - .into() + .into(); } }; diff --git a/wicketd/src/rss_config.rs b/wicketd/src/rss_config.rs index 5f4a62d537e..ef3ca98d1f3 100644 --- a/wicketd/src/rss_config.rs +++ b/wicketd/src/rss_config.rs @@ -5,10 +5,10 @@ //! Support for user-provided RSS configuration options. use crate::bootstrap_addrs::BootstrapPeers; -use anyhow::anyhow; -use anyhow::bail; use anyhow::Context; use anyhow::Result; +use anyhow::anyhow; +use anyhow::bail; use bootstrap_agent_client::types::BootstrapAddressDiscovery; use bootstrap_agent_client::types::Certificate; use bootstrap_agent_client::types::Name; @@ -27,9 +27,9 @@ use omicron_common::api::external::SwitchLocation; use sled_hardware_types::Baseboard; use slog::debug; use slog::warn; -use std::collections::btree_map; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map; use std::mem; use std::net::IpAddr; use std::net::Ipv6Addr; @@ -645,9 +645,9 @@ fn validate_rack_network_config( || addr.addr() > infra_ip_range.last { bail!( - "`uplink_cidr`'s IP address must be in the range defined by \ + "`uplink_cidr`'s IP address must be in the range defined by \ `infra_ip_first` and `infra_ip_last`" - ); + ); } } } diff --git a/wicketd/src/update_tracker.rs b/wicketd/src/update_tracker.rs index 43b550a2d8b..34f9f324db2 100644 --- a/wicketd/src/update_tracker.rs +++ b/wicketd/src/update_tracker.rs @@ -9,10 +9,10 @@ use crate::helpers::sps_to_string; use crate::installinator_progress::IprStartReceiver; use crate::installinator_progress::IprUpdateTracker; use crate::mgs::make_mgs_client; +use anyhow::Context; use anyhow::anyhow; use anyhow::bail; use anyhow::ensure; -use anyhow::Context; use base64::Engine; use bytes::Bytes; use display_error_chain::DisplayErrorChain; @@ -30,8 +30,8 @@ use gateway_client::types::RotImageError; use gateway_client::types::RotState; use gateway_client::types::SpComponentFirmwareSlot; use gateway_client::types::SpUpdateStatus; -use gateway_messages::SpComponent; use gateway_messages::ROT_PAGE_SIZE; +use gateway_messages::SpComponent; use hubtools::RawHubrisArchive; use installinator_common::InstallinatorCompletionMetadata; use installinator_common::InstallinatorSpec; @@ -39,34 +39,34 @@ use installinator_common::WriteOutput; use omicron_common::api::external::SemverVersion; use omicron_common::disk::M2Slot; use omicron_common::update::ArtifactHash; +use slog::Logger; use slog::error; use slog::info; use slog::o; use slog::warn; -use slog::Logger; -use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::collections::btree_map::Entry; use std::net::SocketAddrV6; -use std::sync::atomic::AtomicBool; use std::sync::Arc; use std::sync::Mutex as StdMutex; +use std::sync::atomic::AtomicBool; use std::time::Duration; use std::time::Instant; use thiserror::Error; use tokio::io::AsyncReadExt; +use tokio::sync::Mutex; use tokio::sync::oneshot; use tokio::sync::watch; -use tokio::sync::Mutex; use tokio::task::JoinHandle; use tokio_util::io::StreamReader; use update_common::artifacts::ArtifactIdData; use update_common::artifacts::ArtifactsWithPlan; use update_common::artifacts::ControlPlaneZonesMode; use update_common::artifacts::UpdatePlan; -use update_engine::events::ProgressUnits; use update_engine::AbortHandle; use update_engine::StepSpec; +use update_engine::events::ProgressUnits; use uuid::Uuid; use wicket_common::inventory::SpComponentCaboose; use wicket_common::inventory::SpIdentifier; @@ -1976,7 +1976,7 @@ impl UpdateContext { error: anyhow!( "unexpected RoT active slot {rot_active_slot}" ), - }) + }); } }; @@ -2255,7 +2255,7 @@ impl UpdateContext { // the minimum we will ever return is 3 RotState::V2 { .. } => unreachable!(), RotState::V3 { stage0_error, stage0next_error, .. } => { - return Ok((stage0_error, stage0next_error)) + return Ok((stage0_error, stage0next_error)); } // ugh RotState::CommunicationFailed { message } => { diff --git a/zone-setup/src/bin/zone-setup.rs b/zone-setup/src/bin/zone-setup.rs index 4441431605c..63c0b0cfc28 100644 --- a/zone-setup/src/bin/zone-setup.rs +++ b/zone-setup/src/bin/zone-setup.rs @@ -4,26 +4,26 @@ //! CLI to set up zone configuration -use anyhow::{anyhow, bail, Context}; +use anyhow::{Context, anyhow, bail}; use clap::builder::{ NonEmptyStringValueParser, StringValueParser, TypedValueParser, }; use clap::{ArgAction, Args, Parser, Subcommand}; +use illumos_utils::ExecutionError; use illumos_utils::addrobj::{AddrObject, IPV6_LINK_LOCAL_ADDROBJ_NAME}; use illumos_utils::ipadm::Ipadm; use illumos_utils::route::{Gateway, Route}; use illumos_utils::svcadm::Svcadm; use illumos_utils::zone::{AddressRequest, Zones}; -use illumos_utils::ExecutionError; -use omicron_common::backoff::{retry_notify, retry_policy_local, BackoffError}; -use omicron_common::cmd::fatal; +use omicron_common::backoff::{BackoffError, retry_notify, retry_policy_local}; use omicron_common::cmd::CmdError; +use omicron_common::cmd::fatal; use omicron_sled_agent::services::SWITCH_ZONE_BASEBOARD_FILE; use oxnet::Ipv6Net; use sled_hardware_types::underlay::BOOTSTRAP_PREFIX; -use slog::{info, Logger}; +use slog::{Logger, info}; use std::fmt::Write as _; -use std::fs::{metadata, read_to_string, set_permissions, write, OpenOptions}; +use std::fs::{OpenOptions, metadata, read_to_string, set_permissions, write}; use std::io::Write as _; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::os::unix::fs::chown; diff --git a/zone-setup/src/switch_zone_user.rs b/zone-setup/src/switch_zone_user.rs index 0c4e478cc09..989e27247bd 100644 --- a/zone-setup/src/switch_zone_user.rs +++ b/zone-setup/src/switch_zone_user.rs @@ -4,8 +4,8 @@ use anyhow::Context; use camino::{Utf8Path, Utf8PathBuf}; -use illumos_utils::{execute, ExecutionError}; -use slog::{info, Logger}; +use illumos_utils::{ExecutionError, execute}; +use slog::{Logger, info}; use std::fs::{copy, create_dir_all}; use uzers::{get_group_by_name, get_user_by_name};