diff --git a/Cargo.toml b/Cargo.toml index 2a4ce65522..f103d223db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [workspace] -resolver = "2" +resolver = "3" members = ["agent-control", "resource-detection", "fs", "wrapper_with_default"] [workspace.package] authors = ["The New Relic Agent Control Team"] -edition = "2021" +edition = "2024" publish = false rust-version = "1.85.0" license-file = "./LICENSE.md" @@ -49,4 +49,4 @@ reqwest = { version = "0.12.11", default-features = false, features = [ strip = "debuginfo" [workspace.metadata.cargo-shear] -ignored = ["mockall_double"] \ No newline at end of file +ignored = ["mockall_double"] diff --git a/agent-control/src/agent_control/agent_control.rs b/agent-control/src/agent_control/agent_control.rs index d0ac043bee..c945396309 100644 --- a/agent-control/src/agent_control/agent_control.rs +++ b/agent-control/src/agent_control/agent_control.rs @@ -9,8 +9,8 @@ use crate::agent_control::config_validator::DynamicConfigValidator; use crate::agent_control::error::AgentError; use crate::agent_control::uptime_report::UptimeReporter; use crate::event::{ - channel::{EventConsumer, EventPublisher}, AgentControlEvent, ApplicationEvent, OpAMPEvent, SubAgentEvent, + channel::{EventConsumer, EventPublisher}, }; use crate::opamp::remote_config::report::OpampRemoteConfigStatus; use crate::opamp::{ @@ -436,18 +436,18 @@ fn sub_agents_difference<'a>( #[cfg(test)] mod tests { + use crate::agent_control::AgentControl; use crate::agent_control::agent_control::sub_agents_difference; use crate::agent_control::agent_id::AgentID; use crate::agent_control::config::{ AgentControlConfig, AgentControlDynamicConfig, SubAgentConfig, }; use crate::agent_control::config_storer::loader_storer::tests::MockAgentControlDynamicConfigStore; - use crate::agent_control::config_validator::tests::MockDynamicConfigValidator; use crate::agent_control::config_validator::DynamicConfigValidatorError; + use crate::agent_control::config_validator::tests::MockDynamicConfigValidator; + use crate::agent_control::resource_cleaner::ResourceCleanerError; use crate::agent_control::resource_cleaner::no_op::NoOpResourceCleaner; use crate::agent_control::resource_cleaner::tests::MockResourceCleaner; - use crate::agent_control::resource_cleaner::ResourceCleanerError; - use crate::agent_control::AgentControl; use crate::agent_type::agent_type_id::AgentTypeID; use crate::agent_type::agent_type_registry::AgentRepositoryError; use crate::event::channel::pub_sub; @@ -460,7 +460,7 @@ mod tests { use crate::sub_agent::health::health_checker::{Healthy, Unhealthy}; use crate::sub_agent::tests::MockStartedSubAgent; use crate::sub_agent::tests::MockSubAgentBuilder; - use mockall::{predicate, Sequence}; + use mockall::{Sequence, predicate}; use std::collections::HashMap; use std::sync::Arc; use std::thread::{sleep, spawn}; @@ -1113,9 +1113,11 @@ agents: )]))), ); - assert!(agent_control - .apply_remote_agent_control_config(&remote_config, &mut running_sub_agents) - .is_err()); + assert!( + agent_control + .apply_remote_agent_control_config(&remote_config, &mut running_sub_agents) + .is_err() + ); assert_eq!(running_sub_agents.len(), 1); @@ -1380,9 +1382,12 @@ agents: let ev = agent_control_consumer.as_ref().recv().unwrap(); assert_eq!(expected, ev); - let expected = AgentControlEvent::AgentControlBecameUnhealthy(Unhealthy::new(String::default(), String::from( - "Error applying Agent Control remote config: remote config error: `config hash: `a-hash` config error: `some error message``", - ))); + let expected = AgentControlEvent::AgentControlBecameUnhealthy(Unhealthy::new( + String::default(), + String::from( + "Error applying Agent Control remote config: remote config error: `config hash: `a-hash` config error: `some error message``", + ), + )); let ev = agent_control_consumer.as_ref().recv().unwrap(); assert_eq!(expected, ev); } @@ -1647,12 +1652,14 @@ agents: let diff: Vec<_> = sub_agents_difference(&old_sub_agents, &new_sub_agents).collect(); assert_eq!(diff.len(), 2); - assert!(diff - .iter() - .any(|(id, _)| id == &&AgentID::new("infra-agent").unwrap())); - assert!(diff - .iter() - .any(|(id, _)| id == &&AgentID::new("nrdot").unwrap())); + assert!( + diff.iter() + .any(|(id, _)| id == &&AgentID::new("infra-agent").unwrap()) + ); + assert!( + diff.iter() + .any(|(id, _)| id == &&AgentID::new("nrdot").unwrap()) + ); } #[test] diff --git a/agent-control/src/agent_control/agent_id.rs b/agent-control/src/agent_control/agent_id.rs index 9bdf28e4cd..b72ac32400 100644 --- a/agent-control/src/agent_control/agent_id.rs +++ b/agent-control/src/agent_control/agent_id.rs @@ -17,7 +17,9 @@ pub struct AgentID(String); #[derive(Error, Debug)] pub enum AgentIDError { - #[error("AgentID must contain 32 characters at most, contain lowercase alphanumeric characters or dashes only, start with alphabetic, and end with alphanumeric")] + #[error( + "AgentID must contain 32 characters at most, contain lowercase alphanumeric characters or dashes only, start with alphabetic, and end with alphanumeric" + )] InvalidFormat, #[error("AgentID '{0}' is reserved")] Reserved(String), diff --git a/agent-control/src/agent_control/config.rs b/agent-control/src/agent_control/config.rs index 637d0e8a9f..8648d4feaf 100644 --- a/agent-control/src/agent_control/config.rs +++ b/agent-control/src/agent_control/config.rs @@ -4,8 +4,8 @@ use super::uptime_report::UptimeReportConfig; use crate::http::config::ProxyConfig; use crate::instrumentation::config::logs::config::LoggingConfig; use crate::opamp::auth::config::AuthConfig; -use crate::opamp::remote_config::validators::signature::validator::SignatureValidatorConfig; use crate::opamp::remote_config::RemoteConfigError; +use crate::opamp::remote_config::validators::signature::validator::SignatureValidatorConfig; use crate::values::yaml_config::YAMLConfig; use crate::{ agent_type::agent_type_id::AgentTypeID, instrumentation::config::InstrumentationConfig, @@ -390,10 +390,12 @@ agents: {} serde_yaml::from_str::(EXAMPLE_SUBAGENTS_CONFIG).is_ok() ); assert!(serde_yaml::from_str::(EXAMPLE_K8S_CONFIG).is_ok()); - assert!(serde_yaml::from_str::( - EXAMPLE_AGENTCONTROL_CONFIG_EMPTY_AGENTS - ) - .is_ok()); + assert!( + serde_yaml::from_str::( + EXAMPLE_AGENTCONTROL_CONFIG_EMPTY_AGENTS + ) + .is_ok() + ); assert!( serde_yaml::from_str::(EXAMPLE_AGENTCONTROL_CONFIG_NO_AGENTS) .is_err() @@ -418,10 +420,12 @@ agents: {} let actual = serde_yaml::from_str::(AGENTCONTROL_CONFIG_RESERVED_AGENT_ID); assert!(actual.is_err()); - assert!(actual - .unwrap_err() - .to_string() - .contains("AgentID 'agent-control' is reserved at line")) + assert!( + actual + .unwrap_err() + .to_string() + .contains("AgentID 'agent-control' is reserved at line") + ) } #[test] @@ -429,10 +433,12 @@ agents: {} let actual = serde_yaml::from_str::(AGENTCONTROL_CONFIG_MISSING_K8S_FIELDS); assert!(actual.is_err()); - assert!(actual - .unwrap_err() - .to_string() - .contains("k8s: missing field")); + assert!( + actual + .unwrap_err() + .to_string() + .contains("k8s: missing field") + ); } #[test] diff --git a/agent-control/src/agent_control/config_storer/store.rs b/agent-control/src/agent_control/config_storer/store.rs index 6e17a62248..5c95d0ec16 100644 --- a/agent-control/src/agent_control/config_storer/store.rs +++ b/agent-control/src/agent_control/config_storer/store.rs @@ -6,7 +6,7 @@ use crate::agent_control::config_storer::loader_storer::{ AgentControlConfigLoader, AgentControlDynamicConfigDeleter, AgentControlDynamicConfigLoader, AgentControlDynamicConfigStorer, }; -use crate::agent_control::defaults::{default_capabilities, AGENT_CONTROL_CONFIG_ENV_VAR_PREFIX}; +use crate::agent_control::defaults::{AGENT_CONTROL_CONFIG_ENV_VAR_PREFIX, default_capabilities}; use crate::values::yaml_config::{YAMLConfig, YAMLConfigError}; use crate::values::yaml_config_repository::{YAMLConfigRepository, YAMLConfigRepositoryError}; use config::builder::DefaultState; @@ -210,7 +210,7 @@ fleet_control: // We set the environment variable with the `__` separator which will create the nested // configs appropriately. let env_var_name = "NR_AC_AGENTS__ROLLDICE1__AGENT_TYPE"; - env::set_var(env_var_name, "namespace/com.newrelic.infrastructure:0.0.2"); + unsafe { env::set_var(env_var_name, "namespace/com.newrelic.infrastructure:0.0.2") }; let vr = YAMLConfigRepositoryFile::new(local_dir, PathBuf::new()).with_remote(); let store = AgentControlConfigStore::new(Arc::new(vr)); @@ -236,7 +236,7 @@ fleet_control: }; // Env cleanup - env::remove_var(env_var_name); + unsafe { env::remove_var(env_var_name) }; assert_eq!(actual, expected); } @@ -258,7 +258,7 @@ agents: // We set the environment variable with the `__` separator which will create the nested // configs appropriately. let env_var_name = "NR_AC_AGENTS__ROLLDICE2__AGENT_TYPE"; - env::set_var(env_var_name, "namespace/com.newrelic.infrastructure:0.0.2"); + unsafe { env::set_var(env_var_name, "namespace/com.newrelic.infrastructure:0.0.2") }; let vr = YAMLConfigRepositoryFile::new(local_dir, PathBuf::new()).with_remote(); let store = AgentControlConfigStore::new(Arc::new(vr)); @@ -284,7 +284,7 @@ agents: }; // Env cleanup - env::remove_var(env_var_name); + unsafe { env::remove_var(env_var_name) }; assert_eq!(actual, expected); } diff --git a/agent-control/src/agent_control/event_handler/opamp/remote_config.rs b/agent-control/src/agent_control/event_handler/opamp/remote_config.rs index 8f48c48a70..ca4c315007 100644 --- a/agent-control/src/agent_control/event_handler/opamp/remote_config.rs +++ b/agent-control/src/agent_control/event_handler/opamp/remote_config.rs @@ -9,7 +9,7 @@ use crate::sub_agent::health::health_checker::{Healthy, Unhealthy}; use crate::{ agent_control::{agent_control::AgentControl, error::AgentError}, opamp::{hash_repository::HashRepository, remote_config::RemoteConfig}, - sub_agent::{collection::StartedSubAgents, NotStartedSubAgent, SubAgentBuilder}, + sub_agent::{NotStartedSubAgent, SubAgentBuilder, collection::StartedSubAgents}, }; use opamp_client::StartedClient; use tracing::{error, info}; @@ -82,7 +82,7 @@ mod tests { opamp::{ client_builder::tests::MockStartedOpAMPClient, hash_repository::repository::tests::MockHashRepository, - remote_config::{hash::Hash, ConfigurationMap, RemoteConfig}, + remote_config::{ConfigurationMap, RemoteConfig, hash::Hash}, }, sub_agent::{ collection::StartedSubAgents, diff --git a/agent-control/src/agent_control/http_server/async_bridge.rs b/agent-control/src/agent_control/http_server/async_bridge.rs index 91fd5ba668..8ce7e965bf 100644 --- a/agent-control/src/agent_control/http_server/async_bridge.rs +++ b/agent-control/src/agent_control/http_server/async_bridge.rs @@ -15,49 +15,51 @@ pub fn run_async_sync_bridge( sub_agent_consumer: EventConsumer, stop_rx: EventConsumer<()>, ) -> JoinHandle<()> { - spawn_named_thread("Async-Sync bridge", move || loop { - select! { - recv(&agent_control_consumer.as_ref()) -> sa_event_res => { - match sa_event_res { - Ok(agent_control_event) => { - let _ = async_sa_publisher.send(agent_control_event).inspect_err(|err| { - error!( + spawn_named_thread("Async-Sync bridge", move || { + loop { + select! { + recv(&agent_control_consumer.as_ref()) -> sa_event_res => { + match sa_event_res { + Ok(agent_control_event) => { + let _ = async_sa_publisher.send(agent_control_event).inspect_err(|err| { + error!( + error_msg = %err, + "cannot forward agent control event" + ); + }); + } + Err(err) => { + debug!( error_msg = %err, - "cannot forward agent control event" + "status server bridge channel closed" ); - }); + break; + } } - Err(err) => { - debug!( - error_msg = %err, - "status server bridge channel closed" - ); - break; - } - } - }, - recv(&sub_agent_consumer.as_ref()) -> suba_event_res => { - match suba_event_res { - Ok(sub_agent_event) => { - let _ = async_suba_publisher.send(sub_agent_event).inspect_err(|err| { - error!( + }, + recv(&sub_agent_consumer.as_ref()) -> suba_event_res => { + match suba_event_res { + Ok(sub_agent_event) => { + let _ = async_suba_publisher.send(sub_agent_event).inspect_err(|err| { + error!( + error_msg = %err, + "cannot forward agent control event" + ); + }); + } + Err(err) => { + debug!( error_msg = %err, - "cannot forward agent control event" + "status server bridge channel closed" ); - }); - } - Err(err) => { - debug!( - error_msg = %err, - "status server bridge channel closed" - ); - break; + break; + } } + }, + recv(&stop_rx.as_ref()) -> _ => { + debug!("status server bridge stopping"); + break; } - }, - recv(&stop_rx.as_ref()) -> _ => { - debug!("status server bridge stopping"); - break; } } }) diff --git a/agent-control/src/agent_control/http_server/config.rs b/agent-control/src/agent_control/http_server/config.rs index be1e0d44a2..5c7610ac6d 100644 --- a/agent-control/src/agent_control/http_server/config.rs +++ b/agent-control/src/agent_control/http_server/config.rs @@ -53,7 +53,7 @@ impl Display for Host { #[cfg(test)] mod tests { use crate::agent_control::http_server::config::{ - Host, Port, ServerConfig, DEFAULT_HOST, DEFAULT_PORT, + DEFAULT_HOST, DEFAULT_PORT, Host, Port, ServerConfig, }; use serde::Deserialize; diff --git a/agent-control/src/agent_control/http_server/runner.rs b/agent-control/src/agent_control/http_server/runner.rs index b5b4e5f824..e5c39f095c 100644 --- a/agent-control/src/agent_control/http_server/runner.rs +++ b/agent-control/src/agent_control/http_server/runner.rs @@ -164,8 +164,8 @@ mod tests { use tracing_test::traced_test; use crate::agent_control::http_server::config::ServerConfig; - use crate::event::channel::pub_sub; use crate::event::AgentControlEvent; + use crate::event::channel::pub_sub; use super::Runner; diff --git a/agent-control/src/agent_control/http_server/server.rs b/agent-control/src/agent_control/http_server/server.rs index 3f5dc64e78..1728832f24 100644 --- a/agent-control/src/agent_control/http_server/server.rs +++ b/agent-control/src/agent_control/http_server/server.rs @@ -1,16 +1,16 @@ use crate::agent_control::config::OpAMPClientConfig; -use crate::agent_control::http_server::config::{ServerConfig, DEFAULT_WORKERS}; +use crate::agent_control::http_server::StatusServerError; +use crate::agent_control::http_server::config::{DEFAULT_WORKERS, ServerConfig}; use crate::agent_control::http_server::status::Status; use crate::agent_control::http_server::status_handler::status_handler; use crate::agent_control::http_server::status_updater::on_agent_control_event_update_status; -use crate::agent_control::http_server::StatusServerError; use crate::event::{AgentControlEvent, SubAgentEvent}; -use actix_web::{dev::ServerHandle, web, App, HttpServer}; -use std::sync::mpsc; +use actix_web::{App, HttpServer, dev::ServerHandle, web}; use std::sync::Arc; +use std::sync::mpsc; use tokio::runtime::Handle; -use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::RwLock; +use tokio::sync::mpsc::UnboundedReceiver; use tracing::{debug, error, info}; pub async fn run_status_server( diff --git a/agent-control/src/agent_control/http_server/status.rs b/agent-control/src/agent_control/http_server/status.rs index 0ab070e5ce..99a83193cc 100644 --- a/agent-control/src/agent_control/http_server/status.rs +++ b/agent-control/src/agent_control/http_server/status.rs @@ -6,8 +6,8 @@ use crate::sub_agent::health::health_checker::{Healthy, Unhealthy}; use crate::sub_agent::health::with_start_time::HealthWithStartTime; use crate::sub_agent::identity::AgentIdentity; use serde::Serialize; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::time::SystemTime; use url::Url; diff --git a/agent-control/src/agent_control/http_server/status_handler.rs b/agent-control/src/agent_control/http_server/status_handler.rs index d69b1c6b07..df358d1109 100644 --- a/agent-control/src/agent_control/http_server/status_handler.rs +++ b/agent-control/src/agent_control/http_server/status_handler.rs @@ -24,10 +24,10 @@ mod tests { use crate::sub_agent::health::health_checker::{Healthy, Unhealthy}; use crate::sub_agent::health::with_start_time::HealthWithStartTime; use crate::sub_agent::identity::AgentIdentity; + use actix_web::Responder; use actix_web::body::MessageBody; use actix_web::test::TestRequest; use actix_web::web::Data; - use actix_web::Responder; use std::collections::HashMap; use std::sync::Arc; use std::time::SystemTime; diff --git a/agent-control/src/agent_control/http_server/status_updater.rs b/agent-control/src/agent_control/http_server/status_updater.rs index fe43a1fae9..3f458aa9e6 100644 --- a/agent-control/src/agent_control/http_server/status_updater.rs +++ b/agent-control/src/agent_control/http_server/status_updater.rs @@ -1,8 +1,8 @@ use crate::agent_control::http_server::status::{Status, SubAgentStatus}; use crate::event::{AgentControlEvent, SubAgentEvent}; use std::sync::Arc; -use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::RwLock; +use tokio::sync::mpsc::UnboundedReceiver; use tracing::{debug, trace, warn}; pub(super) async fn on_agent_control_event_update_status( @@ -124,8 +124,8 @@ mod tests { use fake::faker::lorem::en::{Word, Words}; use fake::{Fake, Faker}; use tokio::runtime::Handle; - use tokio::sync::mpsc::unbounded_channel; use tokio::sync::RwLock; + use tokio::sync::mpsc::unbounded_channel; use tokio::time::sleep; use url::Url; diff --git a/agent-control/src/agent_control/pid_cache.rs b/agent-control/src/agent_control/pid_cache.rs index 42aaed52ad..d86e13ed78 100644 --- a/agent-control/src/agent_control/pid_cache.rs +++ b/agent-control/src/agent_control/pid_cache.rs @@ -1,7 +1,7 @@ +use fs::LocalFile; use fs::directory_manager::{DirectoryManagementError, DirectoryManager, DirectoryManagerFs}; use fs::file_reader::FileReader; use fs::writer_file::{FileWriter, WriteError}; -use fs::LocalFile; use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; diff --git a/agent-control/src/agent_control/resource_cleaner/k8s_garbage_collector.rs b/agent-control/src/agent_control/resource_cleaner/k8s_garbage_collector.rs index 8307b24d2f..50cb63db74 100644 --- a/agent-control/src/agent_control/resource_cleaner/k8s_garbage_collector.rs +++ b/agent-control/src/agent_control/resource_cleaner/k8s_garbage_collector.rs @@ -13,7 +13,7 @@ use crate::k8s::annotations; #[cfg_attr(test, mockall_double::double)] use crate::k8s::client::SyncK8sClient; use crate::k8s::error::K8sError; -use crate::k8s::labels::{self, Labels, AGENT_ID_LABEL_KEY}; +use crate::k8s::labels::{self, AGENT_ID_LABEL_KEY, Labels}; use crate::{ agent_control::{agent_id::AgentIDError, config::AgentControlConfigError}, agent_type::agent_type_id::AgentTypeIDError, diff --git a/agent-control/src/agent_control/run.rs b/agent-control/src/agent_control/run.rs index c89e47d031..02263fa6a0 100644 --- a/agent-control/src/agent_control/run.rs +++ b/agent-control/src/agent_control/run.rs @@ -9,14 +9,14 @@ use crate::agent_control::http_server::runner::Runner; use crate::agent_type::embedded_registry::EmbeddedRegistry; use crate::event::channel::pub_sub; use crate::event::{ - channel::{EventConsumer, EventPublisher}, AgentControlEvent, ApplicationEvent, SubAgentEvent, + channel::{EventConsumer, EventPublisher}, }; use crate::http::config::ProxyConfig; use crate::opamp::auth::token_retriever::TokenRetrieverImpl; use crate::opamp::http::builder::OpAMPHttpClientBuilder; use crate::opamp::remote_config::validators::signature::validator::{ - build_signature_validator, SignatureValidator, + SignatureValidator, build_signature_validator, }; use std::error::Error; use std::fmt::{self, Display, Formatter}; diff --git a/agent-control/src/agent_control/run/k8s.rs b/agent-control/src/agent_control/run/k8s.rs index 164d0402ec..1a434fbba7 100644 --- a/agent-control/src/agent_control/run/k8s.rs +++ b/agent-control/src/agent_control/run/k8s.rs @@ -1,3 +1,4 @@ +use crate::agent_control::AgentControl; use crate::agent_control::config::K8sConfig; use crate::agent_control::config_storer::loader_storer::AgentControlConfigLoader; use crate::agent_control::config_storer::store::AgentControlConfigStore; @@ -6,20 +7,19 @@ use crate::agent_control::defaults::{ AGENT_CONTROL_VERSION, FLEET_ID_ATTRIBUTE_KEY, HOST_NAME_ATTRIBUTE_KEY, OPAMP_AGENT_VERSION_ATTRIBUTE_KEY, OPAMP_CHART_VERSION_ATTRIBUTE_KEY, }; -use crate::agent_control::resource_cleaner::k8s_garbage_collector::K8sGarbageCollector; use crate::agent_control::resource_cleaner::ResourceCleanerError; +use crate::agent_control::resource_cleaner::k8s_garbage_collector::K8sGarbageCollector; use crate::agent_control::run::{AgentControlRunner, Environment}; -use crate::agent_control::AgentControl; use crate::agent_type::render::renderer::TemplateRenderer; #[cfg_attr(test, mockall_double::double)] use crate::k8s::client::SyncK8sClient; use crate::opamp::effective_config::loader::DefaultEffectiveConfigLoaderBuilder; use crate::opamp::instance_id::getter::InstanceIDWithIdentifiersGetter; -use crate::opamp::instance_id::k8s::getter::{get_identifiers, Identifiers}; +use crate::opamp::instance_id::k8s::getter::{Identifiers, get_identifiers}; use crate::opamp::operations::build_opamp_with_channel; +use crate::opamp::remote_config::validators::SupportedRemoteConfigValidator; use crate::opamp::remote_config::validators::regexes::RegexValidator; use crate::opamp::remote_config::validators::values::ValuesValidator; -use crate::opamp::remote_config::validators::SupportedRemoteConfigValidator; use crate::sub_agent::effective_agents_assembler::LocalEffectiveAgentsAssembler; use crate::sub_agent::identity::AgentIdentity; use crate::sub_agent::k8s::builder::SupervisorBuilderK8s; diff --git a/agent-control/src/agent_control/run/on_host.rs b/agent-control/src/agent_control/run/on_host.rs index a48a8b829b..b892c20754 100644 --- a/agent-control/src/agent_control/run/on_host.rs +++ b/agent-control/src/agent_control/run/on_host.rs @@ -1,3 +1,4 @@ +use crate::agent_control::AgentControl; use crate::agent_control::config_storer::loader_storer::AgentControlConfigLoader; use crate::agent_control::config_storer::store::AgentControlConfigStore; use crate::agent_control::config_validator::RegistryDynamicConfigValidator; @@ -7,7 +8,6 @@ use crate::agent_control::defaults::{ }; use crate::agent_control::resource_cleaner::no_op::NoOpResourceCleaner; use crate::agent_control::run::{AgentControlRunner, Environment}; -use crate::agent_control::AgentControl; use crate::agent_type::render::persister::config_persister_file::ConfigurationPersisterFile; use crate::agent_type::render::renderer::TemplateRenderer; use crate::agent_type::variable::definition::VariableDefinition; @@ -18,9 +18,9 @@ use crate::opamp::instance_id::getter::InstanceIDWithIdentifiersGetter; use crate::opamp::instance_id::on_host::getter::{Identifiers, IdentifiersProvider}; use crate::opamp::instance_id::on_host::storer::Storer; use crate::opamp::operations::build_opamp_with_channel; +use crate::opamp::remote_config::validators::SupportedRemoteConfigValidator; use crate::opamp::remote_config::validators::regexes::RegexValidator; use crate::opamp::remote_config::validators::values::ValuesValidator; -use crate::opamp::remote_config::validators::SupportedRemoteConfigValidator; use crate::sub_agent::effective_agents_assembler::LocalEffectiveAgentsAssembler; use crate::sub_agent::identity::AgentIdentity; use crate::sub_agent::on_host::builder::SupervisortBuilderOnHost; @@ -31,8 +31,8 @@ use crate::{ opamp::hash_repository::on_host::HashRepositoryFile, sub_agent::on_host::builder::OnHostSubAgentBuilder, values::file::YAMLConfigRepositoryFile, }; -use fs::directory_manager::DirectoryManagerFs; use fs::LocalFile; +use fs::directory_manager::DirectoryManagerFs; use opamp_client::operation::settings::DescriptionValueType; use resource_detection::cloud::http_client::DEFAULT_CLIENT_TIMEOUT; use std::collections::HashMap; diff --git a/agent-control/src/agent_control/uptime_report.rs b/agent-control/src/agent_control/uptime_report.rs index b394224f00..ca401648ea 100644 --- a/agent-control/src/agent_control/uptime_report.rs +++ b/agent-control/src/agent_control/uptime_report.rs @@ -23,7 +23,7 @@ //! assert!(reporter.report().is_ok()); //! ``` -use crossbeam::channel::{never, tick, Receiver}; +use crossbeam::channel::{Receiver, never, tick}; use duration_str::deserialize_duration; use serde::Deserialize; use std::time::{Duration, Instant, SystemTime, SystemTimeError}; diff --git a/agent-control/src/agent_type/agent_type_id.rs b/agent-control/src/agent_type/agent_type_id.rs index 5a31556e62..cc714bd177 100644 --- a/agent-control/src/agent_type/agent_type_id.rs +++ b/agent-control/src/agent_type/agent_type_id.rs @@ -344,9 +344,10 @@ version: 0.1.0-alpha.1 agent_type_id: namespace/name:invalid_version "#, ); - assert!(foo - .unwrap_err() - .to_string() - .contains("Invalid AgentType version")); + assert!( + foo.unwrap_err() + .to_string() + .contains("Invalid AgentType version") + ); } } diff --git a/agent-control/src/agent_type/definition/agent_type_validation_tests.rs b/agent-control/src/agent_type/definition/agent_type_validation_tests.rs index e6aec31545..6cdf613557 100644 --- a/agent-control/src/agent_type/definition/agent_type_validation_tests.rs +++ b/agent-control/src/agent_type/definition/agent_type_validation_tests.rs @@ -15,7 +15,7 @@ use crate::{ embedded_registry::EmbeddedRegistry, render::{ persister::config_persister_file::ConfigurationPersisterFile, - renderer::{tests::testing_agent_attributes, Renderer, TemplateRenderer}, + renderer::{Renderer, TemplateRenderer, tests::testing_agent_attributes}, }, variable::{definition::VariableDefinition, namespace::Namespace}, }, diff --git a/agent-control/src/agent_type/render/persister/config_persister_file.rs b/agent-control/src/agent_type/render/persister/config_persister_file.rs index fbd747bf5d..638052e6fa 100644 --- a/agent-control/src/agent_type/render/persister/config_persister_file.rs +++ b/agent-control/src/agent_type/render/persister/config_persister_file.rs @@ -2,9 +2,9 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::{AGENT_CONTROL_DATA_DIR, GENERATED_FOLDER_NAME}; use crate::agent_type::variable::definition::VariableDefinition; use crate::agent_type::variable::kind::Kind; +use fs::LocalFile; use fs::directory_manager::{DirectoryManagementError, DirectoryManager, DirectoryManagerFs}; use fs::writer_file::{FileWriter, WriteError}; -use fs::LocalFile; use std::collections::HashMap; use std::fs::Permissions; #[cfg(target_family = "unix")] @@ -189,8 +189,8 @@ mod tests { use crate::agent_type::render::persister::config_persister_file::{ DIRECTORY_PERMISSIONS, FILE_PERMISSIONS, }; - use fs::directory_manager::mock::MockDirectoryManager; use fs::directory_manager::DirectoryManager; + use fs::directory_manager::mock::MockDirectoryManager; use fs::mock::MockLocalFile; use fs::writer_file::FileWriter; use std::fs::Permissions; @@ -279,9 +279,11 @@ mod tests { generated_conf_path.as_path(), ); - assert!(persister - .persist_agent_config(&agent_id, &filled_variables) - .is_ok()); + assert!( + persister + .persist_agent_config(&agent_id, &filled_variables) + .is_ok() + ); } #[test] @@ -361,9 +363,11 @@ mod tests { generated_conf_path.as_path(), ); - assert!(persister - .persist_agent_config(&agent_id, &filled_variables) - .is_ok()); + assert!( + persister + .persist_agent_config(&agent_id, &filled_variables) + .is_ok() + ); } #[test] @@ -454,9 +458,11 @@ mod tests { generated_conf_path.as_path(), ); - assert!(persister - .persist_agent_config(&agent_id, &filled_variables) - .is_ok()); + assert!( + persister + .persist_agent_config(&agent_id, &filled_variables) + .is_ok() + ); } #[test] diff --git a/agent-control/src/agent_type/render/renderer.rs b/agent-control/src/agent_type/render/renderer.rs index c6993a107b..c34cbd451b 100644 --- a/agent-control/src/agent_type/render/renderer.rs +++ b/agent-control/src/agent_type/render/renderer.rs @@ -166,7 +166,7 @@ pub(crate) mod tests { agent_type::{ definition::AgentType, render::persister::{ - config_persister::{tests::MockConfigurationPersister, PersistError}, + config_persister::{PersistError, tests::MockConfigurationPersister}, config_persister_file::ConfigurationPersisterFile, }, runtime_config::{ @@ -489,11 +489,13 @@ pub(crate) mod tests { for yaml in wrong_backoff_yamls.into_iter() { let values = serde_yaml::from_str::(yaml).unwrap(); - assert!(agent_type - .variables - .clone() - .fill_with_values(values) - .is_err()) + assert!( + agent_type + .variables + .clone() + .fill_with_values(values) + .is_err() + ) } } diff --git a/agent-control/src/agent_type/runtime_config/restart_policy.rs b/agent-control/src/agent_type/runtime_config/restart_policy.rs index 2493ed2e8a..3e0b26b95a 100644 --- a/agent-control/src/agent_type/runtime_config/restart_policy.rs +++ b/agent-control/src/agent_type/runtime_config/restart_policy.rs @@ -108,7 +108,9 @@ impl Templateable for BackoffStrategyConfig { }; if !result.are_values_in_sync_with_type() { - warn!("Backoff strategy type is set to `none`, but some of the backoff strategy fields are set. They will be ignored"); + warn!( + "Backoff strategy type is set to `none`, but some of the backoff strategy fields are set. They will be ignored" + ); } Ok(result) diff --git a/agent-control/src/bin/main_config_migrate.rs b/agent-control/src/bin/main_config_migrate.rs index f858dacdd7..37ade6c612 100644 --- a/agent-control/src/bin/main_config_migrate.rs +++ b/agent-control/src/bin/main_config_migrate.rs @@ -10,7 +10,7 @@ use newrelic_agent_control::config_migrate::migration::defaults::NEWRELIC_INFRA_ use newrelic_agent_control::config_migrate::migration::migrator::{ConfigMigrator, MigratorError}; use newrelic_agent_control::config_migrate::migration::persister::legacy_config_renamer::LegacyConfigRenamer; use newrelic_agent_control::config_migrate::migration::persister::values_persister_file::ValuesPersisterFile; -use newrelic_agent_control::instrumentation::tracing::{try_init_tracing, TracingConfig}; +use newrelic_agent_control::instrumentation::tracing::{TracingConfig, try_init_tracing}; use newrelic_agent_control::values::file::YAMLConfigRepositoryFile; use std::error::Error; use std::path::PathBuf; diff --git a/agent-control/src/bin/main_k8s.rs b/agent-control/src/bin/main_k8s.rs index bf7f287503..a51ba761c9 100644 --- a/agent-control/src/bin/main_k8s.rs +++ b/agent-control/src/bin/main_k8s.rs @@ -6,8 +6,8 @@ use newrelic_agent_control::agent_control::run::{AgentControlRunner, Environment}; use newrelic_agent_control::cli::{AgentControlCliConfig, Cli, CliCommand}; -use newrelic_agent_control::event::channel::{pub_sub, EventPublisher}; use newrelic_agent_control::event::ApplicationEvent; +use newrelic_agent_control::event::channel::{EventPublisher, pub_sub}; use newrelic_agent_control::http::tls::install_rustls_default_crypto_provider; use newrelic_agent_control::instrumentation::tracing::TracingGuardBox; use std::error::Error; diff --git a/agent-control/src/bin/main_onhost.rs b/agent-control/src/bin/main_onhost.rs index efb31148a1..641e377b91 100644 --- a/agent-control/src/bin/main_onhost.rs +++ b/agent-control/src/bin/main_onhost.rs @@ -8,8 +8,8 @@ use newrelic_agent_control::agent_control::pid_cache::PIDCache; use newrelic_agent_control::agent_control::run::{AgentControlRunner, Environment}; use newrelic_agent_control::cli::{AgentControlCliConfig, Cli, CliCommand}; -use newrelic_agent_control::event::channel::{pub_sub, EventPublisher}; use newrelic_agent_control::event::ApplicationEvent; +use newrelic_agent_control::event::channel::{EventPublisher, pub_sub}; use newrelic_agent_control::http::tls::install_rustls_default_crypto_provider; use newrelic_agent_control::instrumentation::tracing::TracingGuardBox; use std::error::Error; diff --git a/agent-control/src/cli.rs b/agent-control/src/cli.rs index be12017aa7..46b8793d13 100644 --- a/agent-control/src/cli.rs +++ b/agent-control/src/cli.rs @@ -5,11 +5,11 @@ mod one_shot_operation; use crate::agent_control::config::K8sConfig; +use crate::agent_control::run::Environment; #[cfg(debug_assertions)] use crate::agent_control::run::set_debug_dirs; -use crate::agent_control::run::Environment; use crate::instrumentation::tracing::{ - try_init_tracing, TracingConfig, TracingError, TracingGuardBox, + TracingConfig, TracingError, TracingGuardBox, try_init_tracing, }; use crate::opamp::client_builder::DEFAULT_POLL_INTERVAL; use crate::values::file::YAMLConfigRepositoryFile; diff --git a/agent-control/src/config_migrate/migration/agent_value_spec.rs b/agent-control/src/config_migrate/migration/agent_value_spec.rs index 9724f5f27d..db8d4f2889 100644 --- a/agent-control/src/config_migrate/migration/agent_value_spec.rs +++ b/agent-control/src/config_migrate/migration/agent_value_spec.rs @@ -96,7 +96,7 @@ mod tests { AgentValueSpecEnd, AgentValueSpecMapping, }; use crate::config_migrate::migration::agent_value_spec::{ - from_fqn_and_value, merge_agent_values_recursive, AgentValueSpec, + AgentValueSpec, from_fqn_and_value, merge_agent_values_recursive, }; use crate::config_migrate::migration::config::AgentTypeFieldFQN; use std::collections::HashMap; diff --git a/agent-control/src/config_migrate/migration/converter.rs b/agent-control/src/config_migrate/migration/converter.rs index 7350d3db77..fc45cdc949 100644 --- a/agent-control/src/config_migrate/migration/converter.rs +++ b/agent-control/src/config_migrate/migration/converter.rs @@ -4,16 +4,16 @@ use crate::agent_type::embedded_registry::EmbeddedRegistry; use crate::agent_type::variable::kind::Kind; use crate::config_migrate::migration::agent_value_spec::AgentValueSpec::AgentValueSpecEnd; use crate::config_migrate::migration::agent_value_spec::{ - from_fqn_and_value, merge_agent_values, AgentValueError, AgentValueSpec, + AgentValueError, AgentValueSpec, from_fqn_and_value, merge_agent_values, }; use crate::config_migrate::migration::config::{ AgentTypeFieldFQN, DirInfo, FilePath, MigrationAgentConfig, }; use crate::config_migrate::migration::config::{FILE_SEPARATOR, FILE_SEPARATOR_REPLACE}; use crate::config_migrate::migration::converter::ConversionError::RequiredFileMappingNotFoundError; -use crate::sub_agent::effective_agents_assembler::{build_agent_type, AgentTypeDefinitionError}; -use fs::file_reader::{FileReader, FileReaderError}; +use crate::sub_agent::effective_agents_assembler::{AgentTypeDefinitionError, build_agent_type}; use fs::LocalFile; +use fs::file_reader::{FileReader, FileReaderError}; use std::collections::HashMap; use thiserror::Error; use tracing::{debug, error}; diff --git a/agent-control/src/config_migrate/migration/migrator.rs b/agent-control/src/config_migrate/migration/migrator.rs index 2197e0e641..eb343ea07c 100644 --- a/agent-control/src/config_migrate/migration/migrator.rs +++ b/agent-control/src/config_migrate/migration/migrator.rs @@ -13,9 +13,9 @@ use crate::config_migrate::migration::persister::values_persister_file::PersistE #[cfg_attr(test, mockall_double::double)] use crate::config_migrate::migration::persister::values_persister_file::ValuesPersisterFile; use crate::values::file::YAMLConfigRepositoryFile; +use fs::LocalFile; use fs::directory_manager::{DirectoryManager, DirectoryManagerFs}; use fs::file_reader::FileReader; -use fs::LocalFile; use thiserror::Error; use tracing::{debug, info, warn}; diff --git a/agent-control/src/config_migrate/migration/persister/legacy_config_renamer.rs b/agent-control/src/config_migrate/migration/persister/legacy_config_renamer.rs index d319e3dabc..735fb0f9fa 100644 --- a/agent-control/src/config_migrate/migration/persister/legacy_config_renamer.rs +++ b/agent-control/src/config_migrate/migration/persister/legacy_config_renamer.rs @@ -1,6 +1,6 @@ use fs::{ - file_renamer::{FileRenamer, FileRenamerError}, LocalFile, + file_renamer::{FileRenamer, FileRenamerError}, }; use std::path::{Path, PathBuf}; diff --git a/agent-control/src/config_migrate/migration/persister/values_persister_file.rs b/agent-control/src/config_migrate/migration/persister/values_persister_file.rs index cae3fa20cc..e18b4bfde3 100644 --- a/agent-control/src/config_migrate/migration/persister/values_persister_file.rs +++ b/agent-control/src/config_migrate/migration/persister/values_persister_file.rs @@ -1,8 +1,8 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::{VALUES_DIR, VALUES_FILENAME}; +use fs::LocalFile; use fs::directory_manager::{DirectoryManagementError, DirectoryManager, DirectoryManagerFs}; use fs::writer_file::{FileWriter, WriteError}; -use fs::LocalFile; use std::fs::Permissions; #[cfg(target_family = "unix")] use std::os::unix::fs::PermissionsExt; diff --git a/agent-control/src/event/broadcaster/unbounded.rs b/agent-control/src/event/broadcaster/unbounded.rs index 08cf3cb7f6..34ceb3dbbb 100644 --- a/agent-control/src/event/broadcaster/unbounded.rs +++ b/agent-control/src/event/broadcaster/unbounded.rs @@ -1,4 +1,4 @@ -use crossbeam::channel::{unbounded, Receiver, Sender}; +use crossbeam::channel::{Receiver, Sender, unbounded}; use std::sync::{Arc, Mutex}; #[derive(Debug, Clone, Default)] diff --git a/agent-control/src/event/channel.rs b/agent-control/src/event/channel.rs index 3dcd30d8ef..d30f9894fe 100644 --- a/agent-control/src/event/channel.rs +++ b/agent-control/src/event/channel.rs @@ -1,4 +1,4 @@ -use crossbeam::channel::{unbounded, Receiver, Sender}; +use crossbeam::channel::{Receiver, Sender, unbounded}; use thiserror::Error; pub struct EventConsumer(Receiver); diff --git a/agent-control/src/http/client.rs b/agent-control/src/http/client.rs index 1e4b8f62ec..a25e05350f 100644 --- a/agent-control/src/http/client.rs +++ b/agent-control/src/http/client.rs @@ -12,8 +12,8 @@ use opamp_client::http::HttpClientError as OpampHttpClientError; use opentelemetry_http::HttpError; use reqwest::tls::TlsInfo; use reqwest::{ - blocking::{Client, Response as BlockingResponse}, Certificate, Proxy, + blocking::{Client, Response as BlockingResponse}, }; use resource_detection::cloud::http_client::HttpClient as CloudClient; use resource_detection::cloud::http_client::HttpClientError as CloudClientError; diff --git a/agent-control/src/instrumentation/config/logs/config.rs b/agent-control/src/instrumentation/config/logs/config.rs index 35bc8663b6..9652c47c33 100644 --- a/agent-control/src/instrumentation/config/logs/config.rs +++ b/agent-control/src/instrumentation/config/logs/config.rs @@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize, Serializer}; use std::fmt::Debug; use std::str::FromStr; use thiserror::Error; -use tracing::level_filters::LevelFilter; use tracing::Level; +use tracing::level_filters::LevelFilter; use tracing_subscriber::filter::{Directive, FilterExt, FilterFn}; use tracing_subscriber::layer::Filter; use tracing_subscriber::{EnvFilter, Registry}; @@ -50,7 +50,7 @@ pub struct LoggingConfig { impl LoggingConfig { /// Returns the configured filter according to the corresponding fields. The filter will also allow /// any span whose level doesn't exceed [SPAN_ATTRIBUTES_MAX_LEVEL]. - pub fn filter(&self) -> Result, LoggingConfigError> { + pub fn filter(&self) -> Result + use<>, LoggingConfigError> { let configured_logs_filter = self.logging_filter()?; let allow_spans_filter = FilterFn::new(|metadata| { @@ -326,8 +326,10 @@ mod tests { // WARN and ERROR messages should be included // Logs inside info-spans should include the corresponding fields - assert!(log_file_content - .contains(r#"ERROR info-span{key: "value"}: error message inside span"#)); + assert!( + log_file_content + .contains(r#"ERROR info-span{key: "value"}: error message inside span"#) + ); // Logs inside debug-spans should not include the corresponding fields assert!(log_file_content.contains(r"ERROR error message inside debug span")); // Logs outside should also be reported diff --git a/agent-control/src/instrumentation/tracing.rs b/agent-control/src/instrumentation/tracing.rs index 117bc5dd22..e99f1f690e 100644 --- a/agent-control/src/instrumentation/tracing.rs +++ b/agent-control/src/instrumentation/tracing.rs @@ -2,8 +2,8 @@ use super::{ config::{ - logs::config::{LoggingConfig, LoggingConfigError}, InstrumentationConfig, + logs::config::{LoggingConfig, LoggingConfigError}, }, tracing_layers::{ file::file, @@ -14,7 +14,7 @@ use super::{ use std::path::PathBuf; use thiserror::Error; use tracing::debug; -use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer, Registry}; +use tracing_subscriber::{Layer, Registry, layer::SubscriberExt, util::SubscriberInitExt}; /// Represents errors while setting up or shutting down tracing. #[derive(Error, Debug)] diff --git a/agent-control/src/instrumentation/tracing_layers/file.rs b/agent-control/src/instrumentation/tracing_layers/file.rs index a2225be2b2..4cbd2b5ec8 100644 --- a/agent-control/src/instrumentation/tracing_layers/file.rs +++ b/agent-control/src/instrumentation/tracing_layers/file.rs @@ -2,9 +2,9 @@ use crate::instrumentation::config::logs::config::{LoggingConfig, LoggingConfigE use crate::instrumentation::tracing::{LayerBox, TracingGuard}; use std::path::PathBuf; use tracing_appender::non_blocking::WorkerGuard; +use tracing_subscriber::Layer; use tracing_subscriber::fmt::format::PrettyFields; use tracing_subscriber::fmt::time::ChronoLocal; -use tracing_subscriber::Layer; pub type FileTracingExporter = WorkerGuard; diff --git a/agent-control/src/instrumentation/tracing_layers/otel.rs b/agent-control/src/instrumentation/tracing_layers/otel.rs index 38051abc35..9c1d1a02f0 100644 --- a/agent-control/src/instrumentation/tracing_layers/otel.rs +++ b/agent-control/src/instrumentation/tracing_layers/otel.rs @@ -2,15 +2,15 @@ use crate::http::client::{HttpBuildError, HttpClient}; use crate::http::config::HttpConfig; use crate::instrumentation::config::otel::OtelConfig; use crate::instrumentation::tracing::LayerBox; -use opentelemetry::trace::TracerProvider; use opentelemetry::KeyValue; +use opentelemetry::trace::TracerProvider; use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; use opentelemetry_http::HttpClient as OtelHttpClient; use opentelemetry_otlp::{ExporterBuildError, WithExportConfig, WithHttpConfig}; +use opentelemetry_sdk::Resource; use opentelemetry_sdk::logs::{BatchLogProcessor, SdkLoggerProvider}; use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider}; use opentelemetry_sdk::trace::{BatchSpanProcessor, SdkTracerProvider}; -use opentelemetry_sdk::Resource; use thiserror::Error; use tracing_opentelemetry::MetricsLayer; use tracing_subscriber::{EnvFilter, Layer}; @@ -212,8 +212,8 @@ mod tests { use http::Response; use opentelemetry_sdk::Resource; use tracing::{debug, info, trace}; - use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::EnvFilter; + use tracing_subscriber::layer::SubscriberExt; use crate::http::client::tests::MockOtelHttpClient; use crate::instrumentation::config::otel::{LogsConfig, OtelConfig}; diff --git a/agent-control/src/instrumentation/tracing_layers/stdout.rs b/agent-control/src/instrumentation/tracing_layers/stdout.rs index 01ad541c48..c5c54e84dc 100644 --- a/agent-control/src/instrumentation/tracing_layers/stdout.rs +++ b/agent-control/src/instrumentation/tracing_layers/stdout.rs @@ -1,8 +1,8 @@ use crate::instrumentation::config::logs::config::{LoggingConfig, LoggingConfigError}; use crate::instrumentation::tracing::LayerBox; +use tracing_subscriber::Layer; use tracing_subscriber::fmt::format::PrettyFields; use tracing_subscriber::fmt::time::ChronoLocal; -use tracing_subscriber::Layer; /// Returns the [LayerBox] corresponding to the standard output. pub fn stdout(config: &LoggingConfig) -> Result { diff --git a/agent-control/src/k8s/client.rs b/agent-control/src/k8s/client.rs index 1bc35f185a..fcf552ab0f 100644 --- a/agent-control/src/k8s/client.rs +++ b/agent-control/src/k8s/client.rs @@ -6,13 +6,13 @@ use super::{ use k8s_openapi::api::apps::v1::{DaemonSet, Deployment, StatefulSet}; use k8s_openapi::api::core::v1::{ConfigMap, Namespace}; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; -use kube::api::entry::Entry; use kube::api::ObjectList; +use kube::api::entry::Entry; use kube::{ + Api, Client, Config, Resource, api::{DeleteParams, ListParams, PostParams}, config::KubeConfigOptions, core::{DynamicObject, TypeMeta}, - Api, Client, Config, Resource, }; use serde::de::DeserializeOwned; use std::fmt::Debug; @@ -336,8 +336,8 @@ pub(crate) mod tests { use crate::k8s::reflector::resources::ResourceWithReflector; use k8s_openapi::api::apps::v1::{DaemonSet, Deployment}; use k8s_openapi::serde_json; - use kube::runtime::reflector; use kube::Client; + use kube::runtime::reflector; use tower_test::mock; #[tokio::test] diff --git a/agent-control/src/k8s/dynamic_object.rs b/agent-control/src/k8s/dynamic_object.rs index 433bf7b5ae..cf0492b9ff 100644 --- a/agent-control/src/k8s/dynamic_object.rs +++ b/agent-control/src/k8s/dynamic_object.rs @@ -8,10 +8,10 @@ use super::{ }; use base64::engine::general_purpose::STANDARD; use kube::{ + Api, Resource, api::{DeleteParams, DynamicObject, PostParams, TypeMeta}, core::GroupVersion, discovery::pinned_kind, - Api, Resource, }; use std::{collections::HashMap, str::FromStr, sync::Arc}; use tokio::sync::Mutex; diff --git a/agent-control/src/k8s/labels.rs b/agent-control/src/k8s/labels.rs index 95bdf53550..7c1551ef73 100644 --- a/agent-control/src/k8s/labels.rs +++ b/agent-control/src/k8s/labels.rs @@ -62,7 +62,7 @@ pub fn get_agent_id(labels: &BTreeMap) -> Option<&String> { #[cfg(test)] pub(crate) mod tests { - use super::{Labels, AGENT_ID_LABEL_KEY, MANAGED_BY_KEY, MANAGED_BY_VAL}; + use super::{AGENT_ID_LABEL_KEY, Labels, MANAGED_BY_KEY, MANAGED_BY_VAL}; use crate::agent_control::agent_id::AgentID; use std::collections::BTreeMap; diff --git a/agent-control/src/k8s/reflector/definition.rs b/agent-control/src/k8s/reflector/definition.rs index a06ff81832..968c02ba90 100644 --- a/agent-control/src/k8s/reflector/definition.rs +++ b/agent-control/src/k8s/reflector/definition.rs @@ -1,12 +1,13 @@ use futures::StreamExt; use kube::{ + Api, Client, core::DynamicObject, discovery::ApiResource, runtime::{ - reflector::{self, store::Writer, Store}, - watcher, WatchStreamExt, + WatchStreamExt, + reflector::{self, Store, store::Writer}, + watcher, }, - Api, Client, }; use std::{fmt::Debug, future::Future, time::Duration}; diff --git a/agent-control/src/k8s/reflector/resources.rs b/agent-control/src/k8s/reflector/resources.rs index 149bf39809..39de3070e8 100644 --- a/agent-control/src/k8s/reflector/resources.rs +++ b/agent-control/src/k8s/reflector/resources.rs @@ -2,8 +2,8 @@ use super::definition::{Reflector, ReflectorBuilder}; use crate::k8s::error::K8sError; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use k8s_openapi::{ - api::apps::v1::{DaemonSet, Deployment, StatefulSet}, Metadata, NamespaceResourceScope, Resource, + api::apps::v1::{DaemonSet, Deployment, StatefulSet}, }; use serde::de::DeserializeOwned; use std::{fmt::Debug, sync::Arc}; diff --git a/agent-control/src/k8s/store.rs b/agent-control/src/k8s/store.rs index fca3d489b0..5aa75071d0 100644 --- a/agent-control/src/k8s/store.rs +++ b/agent-control/src/k8s/store.rs @@ -1,7 +1,7 @@ +use super::Error; #[cfg_attr(test, mockall_double::double)] use super::client::SyncK8sClient; use super::labels::Labels; -use super::Error; use crate::agent_control::agent_id::AgentID; use std::sync::{Arc, RwLock}; @@ -112,8 +112,8 @@ impl K8sStore { #[cfg(test)] pub mod tests { - use super::{K8sStore, StoreKey}; use super::{CM_NAME_LOCAL_DATA_PREFIX, CM_NAME_OPAMP_DATA_PREFIX}; + use super::{K8sStore, StoreKey}; use crate::agent_control::agent_id::AgentID; use crate::k8s::client::MockSyncK8sClient; use crate::k8s::error::K8sError; diff --git a/agent-control/src/k8s/utils.rs b/agent-control/src/k8s/utils.rs index fe171e502d..3ffd5a5d52 100644 --- a/agent-control/src/k8s/utils.rs +++ b/agent-control/src/k8s/utils.rs @@ -1,5 +1,5 @@ use k8s_openapi::{ - apimachinery::pkg::util::intstr::IntOrString, Metadata, NamespaceResourceScope, Resource, + Metadata, NamespaceResourceScope, Resource, apimachinery::pkg::util::intstr::IntOrString, }; use kube::api::{ObjectMeta, TypeMeta}; diff --git a/agent-control/src/opamp/auth/token_retriever.rs b/agent-control/src/opamp/auth/token_retriever.rs index 020b3c5dfb..1ede798ef5 100644 --- a/agent-control/src/opamp/auth/token_retriever.rs +++ b/agent-control/src/opamp/auth/token_retriever.rs @@ -5,11 +5,11 @@ use crate::http::config::ProxyConfig; use crate::{agent_control::run::BasePaths, http::client::HttpBuildError}; use chrono::DateTime; use nr_auth::{ + TokenRetriever, TokenRetrieverError, authenticator::HttpAuthenticator, - jwt::signer::{local::LocalPrivateKeySigner, JwtSignerImpl, JwtSignerImplError}, + jwt::signer::{JwtSignerImpl, JwtSignerImplError, local::LocalPrivateKeySigner}, token::{AccessToken, Token, TokenType}, token_retriever::TokenRetrieverWithCache, - TokenRetriever, TokenRetrieverError, }; use std::time::Duration; use thiserror::Error; diff --git a/agent-control/src/opamp/callbacks.rs b/agent-control/src/opamp/callbacks.rs index ba7e82fec9..c4d6b9a158 100644 --- a/agent-control/src/opamp/callbacks.rs +++ b/agent-control/src/opamp/callbacks.rs @@ -1,14 +1,15 @@ use super::effective_config::{error::EffectiveConfigError, loader::EffectiveConfigLoader}; use crate::opamp::remote_config::signature::Signatures; -use crate::opamp::remote_config::{hash::Hash, ConfigurationMap, RemoteConfig}; +use crate::opamp::remote_config::{ConfigurationMap, RemoteConfig, hash::Hash}; use crate::{agent_control::agent_id::AgentID, opamp::remote_config::RemoteConfigError}; use crate::{ event::{ - channel::{EventPublisher, EventPublisherError}, OpAMPEvent, + channel::{EventPublisher, EventPublisherError}, }, opamp::remote_config::signature::SignatureError, }; +use HttpClientError::UnsuccessfulResponse; use opamp_client::{ error::ConnectionError, error::ConnectionError::HTTPClientError, @@ -22,7 +23,6 @@ use opamp_client::{ use std::string::FromUtf8Error; use thiserror::Error; use tracing::{debug, error, trace}; -use HttpClientError::UnsuccessfulResponse; #[derive(Debug, Error)] pub enum AgentCallbacksError { @@ -123,8 +123,7 @@ where trace!( agent_id = self.agent_id.to_string(), - "remote config received: {:?}", - &remote_config + "remote config received: {:?}", &remote_config ); Ok(self @@ -254,8 +253,8 @@ fn log_connection_error(err: &ConnectionError, agent_id: AgentID) { #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::event::channel::pub_sub; use crate::event::OpAMPEvent; + use crate::event::channel::pub_sub; use crate::opamp::effective_config::loader::tests::MockEffectiveConfigLoader; use crate::opamp::remote_config::hash::Hash; use crate::opamp::remote_config::signature::{ diff --git a/agent-control/src/opamp/client_builder.rs b/agent-control/src/opamp/client_builder.rs index 181ba29457..e6c8cf9454 100644 --- a/agent-control/src/opamp/client_builder.rs +++ b/agent-control/src/opamp/client_builder.rs @@ -3,8 +3,8 @@ use super::effective_config::loader::EffectiveConfigLoaderBuilder; use super::http::builder::{HttpClientBuilder, HttpClientBuilderError}; use super::instance_id::getter::GetterError; use crate::agent_control::agent_id::AgentID; -use crate::event::channel::EventPublisher; use crate::event::OpAMPEvent; +use crate::event::channel::EventPublisher; use opamp_client::http::client::OpAMPHttpClient; use opamp_client::http::{NotStartedHttpClient, StartedHttpClient}; use opamp_client::operation::settings::StartSettings; @@ -110,9 +110,9 @@ pub(crate) mod tests { use mockall::{mock, predicate}; use opamp_client::operation::settings::StartSettings; use opamp_client::{ - opamp::proto::{AgentDescription, ComponentHealth, CustomCapabilities, RemoteConfigStatus}, Client, ClientResult, NotStartedClient, NotStartedClientResult, StartedClient, StartedClientResult, + opamp::proto::{AgentDescription, ComponentHealth, CustomCapabilities, RemoteConfigStatus}, }; use super::*; diff --git a/agent-control/src/opamp/effective_config/agent_control.rs b/agent-control/src/opamp/effective_config/agent_control.rs index 308575e454..2caf9dfcad 100644 --- a/agent-control/src/opamp/effective_config/agent_control.rs +++ b/agent-control/src/opamp/effective_config/agent_control.rs @@ -8,7 +8,7 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::default_capabilities; use crate::opamp::remote_config::ConfigurationMap; use crate::values::yaml_config::YAMLConfig; -use crate::values::yaml_config_repository::{load_remote_fallback_local, YAMLConfigRepository}; +use crate::values::yaml_config_repository::{YAMLConfigRepository, load_remote_fallback_local}; use super::error::LoaderError; use super::loader::EffectiveConfigLoader; diff --git a/agent-control/src/opamp/effective_config/sub_agent.rs b/agent-control/src/opamp/effective_config/sub_agent.rs index 2bf34d3c22..0d72066b66 100644 --- a/agent-control/src/opamp/effective_config/sub_agent.rs +++ b/agent-control/src/opamp/effective_config/sub_agent.rs @@ -3,7 +3,7 @@ use super::loader::EffectiveConfigLoader; use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::default_capabilities; use crate::opamp::remote_config::ConfigurationMap; -use crate::values::yaml_config_repository::{load_remote_fallback_local, YAMLConfigRepository}; +use crate::values::yaml_config_repository::{YAMLConfigRepository, load_remote_fallback_local}; use std::collections::HashMap; use std::sync::Arc; diff --git a/agent-control/src/opamp/hash_repository/k8s.rs b/agent-control/src/opamp/hash_repository/k8s.rs index d5d09447b6..e39243bbc2 100644 --- a/agent-control/src/opamp/hash_repository/k8s.rs +++ b/agent-control/src/opamp/hash_repository/k8s.rs @@ -2,8 +2,8 @@ use crate::agent_control::agent_id::AgentID; use crate::k8s; use crate::k8s::store::K8sStore; use crate::k8s::store::STORE_KEY_OPAMP_DATA_CONFIG_HASH; -use crate::opamp::hash_repository::repository::HashRepositoryError; use crate::opamp::hash_repository::HashRepository; +use crate::opamp::hash_repository::repository::HashRepositoryError; use crate::opamp::remote_config::hash::Hash; use std::sync::Arc; use thiserror::Error; diff --git a/agent-control/src/opamp/hash_repository/on_host.rs b/agent-control/src/opamp/hash_repository/on_host.rs index 845741c922..5c9c3e364a 100644 --- a/agent-control/src/opamp/hash_repository/on_host.rs +++ b/agent-control/src/opamp/hash_repository/on_host.rs @@ -1,12 +1,12 @@ use crate::agent_control::agent_id::AgentID; use crate::opamp::hash_repository::repository::{HashRepository, HashRepositoryError}; use crate::opamp::remote_config::hash::Hash; +use fs::LocalFile; use fs::directory_manager::DirectoryManagementError; use fs::directory_manager::{DirectoryManager, DirectoryManagerFs}; use fs::file_reader::FileReader; use fs::file_reader::FileReaderError; use fs::writer_file::{FileWriter, WriteError}; -use fs::LocalFile; use std::fs::Permissions; #[cfg(target_family = "unix")] use std::os::unix::fs::PermissionsExt; @@ -146,11 +146,11 @@ where //////////////////////////////////////////////////////////////////////////////////// #[cfg(test)] pub mod tests { - use super::{Hash, HashRepository, HashRepositoryFile, DIRECTORY_PERMISSIONS, HASH_FILE_NAME}; + use super::{DIRECTORY_PERMISSIONS, HASH_FILE_NAME, Hash, HashRepository, HashRepositoryFile}; use crate::agent_control::agent_id::AgentID; use crate::values::file::FILE_PERMISSIONS; - use fs::directory_manager::mock::MockDirectoryManager; use fs::directory_manager::DirectoryManager; + use fs::directory_manager::mock::MockDirectoryManager; use fs::file_reader::FileReader; use fs::mock::MockLocalFile; use fs::writer_file::FileWriter; diff --git a/agent-control/src/opamp/http/builder.rs b/agent-control/src/opamp/http/builder.rs index 4ff461dcd5..d457f3a9ac 100644 --- a/agent-control/src/opamp/http/builder.rs +++ b/agent-control/src/opamp/http/builder.rs @@ -98,7 +98,7 @@ pub(crate) mod tests { use http::Response; use mockall::mock; use opamp_client::operation::settings::StartSettings; - use opamp_client::{http::HttpClientError, StartedClient}; + use opamp_client::{StartedClient, http::HttpClientError}; use crate::opamp::client_builder::OpAMPClientBuilderError; use crate::{ @@ -106,7 +106,7 @@ pub(crate) mod tests { event::channel::pub_sub, opamp::{ client_builder::{ - DefaultOpAMPClientBuilder, OpAMPClientBuilder, DEFAULT_POLL_INTERVAL, + DEFAULT_POLL_INTERVAL, DefaultOpAMPClientBuilder, OpAMPClientBuilder, }, effective_config::loader::tests::{ MockEffectiveConfigLoader, MockEffectiveConfigLoaderBuilder, diff --git a/agent-control/src/opamp/http/client.rs b/agent-control/src/opamp/http/client.rs index 98c3d36842..9cf5658039 100644 --- a/agent-control/src/opamp/http/client.rs +++ b/agent-control/src/opamp/http/client.rs @@ -4,8 +4,8 @@ use crate::opamp::http::client::OpAMPHttpClientError::AuthorizationHeadersError; use http::header::AUTHORIZATION; use http::{HeaderMap, HeaderValue, Response}; use nr_auth::TokenRetriever; -use opamp_client::http::http_client::HttpClient as OpampHttpClient; use opamp_client::http::HttpClientError; +use opamp_client::http::http_client::HttpClient as OpampHttpClient; use std::sync::Arc; use url::Url; @@ -105,8 +105,8 @@ pub mod tests { use super::*; use chrono::Utc; - use fake::faker::lorem::en::Word; use fake::Fake; + use fake::faker::lorem::en::Word; use mockall::mock; use crate::http::config::HttpConfig; diff --git a/agent-control/src/opamp/instance_id/getter.rs b/agent-control/src/opamp/instance_id/getter.rs index a8b7d843ce..d12b104dcc 100644 --- a/agent-control/src/opamp/instance_id/getter.rs +++ b/agent-control/src/opamp/instance_id/getter.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use std::sync::Mutex; use tracing::debug; -use super::{definition::InstanceIdentifiers, InstanceID}; +use super::{InstanceID, definition::InstanceIdentifiers}; // IDGetter returns an InstanceID for a specific agentID. pub trait InstanceIDGetter { diff --git a/agent-control/src/opamp/instance_id/on_host/getter.rs b/agent-control/src/opamp/instance_id/on_host/getter.rs index 7170caa7e8..d80574463e 100644 --- a/agent-control/src/opamp/instance_id/on_host/getter.rs +++ b/agent-control/src/opamp/instance_id/on_host/getter.rs @@ -1,17 +1,17 @@ use crate::http::client::HttpClient; use crate::opamp::instance_id::definition::InstanceIdentifiers; +use resource_detection::DetectError; +use resource_detection::cloud::CLOUD_INSTANCE_ID; use resource_detection::cloud::aws::detector::{ - AWSDetector, AWS_IPV4_METADATA_ENDPOINT, AWS_IPV4_METADATA_TOKEN_ENDPOINT, + AWS_IPV4_METADATA_ENDPOINT, AWS_IPV4_METADATA_TOKEN_ENDPOINT, AWSDetector, }; -use resource_detection::cloud::azure::detector::{AzureDetector, AZURE_IPV4_METADATA_ENDPOINT}; +use resource_detection::cloud::azure::detector::{AZURE_IPV4_METADATA_ENDPOINT, AzureDetector}; use resource_detection::cloud::cloud_id::detector::CloudIdDetector; -use resource_detection::cloud::gcp::detector::{GCPDetector, GCP_IPV4_METADATA_ENDPOINT}; +use resource_detection::cloud::gcp::detector::{GCP_IPV4_METADATA_ENDPOINT, GCPDetector}; use resource_detection::cloud::http_client::HttpClientError; -use resource_detection::cloud::CLOUD_INSTANCE_ID; use resource_detection::system::{HOSTNAME_KEY, MACHINE_ID_KEY}; -use resource_detection::DetectError; -use resource_detection::{system::detector::SystemDetector, Detector}; +use resource_detection::{Detector, system::detector::SystemDetector}; use serde::{Deserialize, Serialize}; use std::fmt::{Display, Formatter}; use thiserror::Error; @@ -33,14 +33,16 @@ impl Display for Identifiers { write!( f, "hostname = '{}', machine_id = '{}', cloud_instance_id = '{}', host_id = '{}', fleet_id = '{}'", - self.hostname, self.machine_id, self.cloud_instance_id, self.host_id,self.fleet_id, + self.hostname, self.machine_id, self.cloud_instance_id, self.host_id, self.fleet_id, ) } } #[derive(Error, Debug)] pub enum IdentifiersProviderError { - #[error("generating host identification: adding a `host_id` in the agent-control config is required for this case`")] + #[error( + "generating host identification: adding a `host_id` in the agent-control config is required for this case`" + )] MissingHostIDError, #[error("detecting resources: `{0}`")] DetectError(#[from] DetectError), diff --git a/agent-control/src/opamp/instance_id/on_host/storer.rs b/agent-control/src/opamp/instance_id/on_host/storer.rs index 69635c286a..e1afdf53c0 100644 --- a/agent-control/src/opamp/instance_id/on_host/storer.rs +++ b/agent-control/src/opamp/instance_id/on_host/storer.rs @@ -2,11 +2,11 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::IDENTIFIERS_FILENAME; use crate::opamp::instance_id::getter::DataStored; use crate::opamp::instance_id::storer::InstanceIDStorer; +use fs::LocalFile; use fs::directory_manager::{DirectoryManagementError, DirectoryManager, DirectoryManagerFs}; use fs::file_reader::{FileReader, FileReaderError}; use fs::utils::FsError; use fs::writer_file::{FileWriter, WriteError}; -use fs::LocalFile; use std::fs::Permissions; use std::io; use std::os::unix::fs::PermissionsExt; @@ -155,11 +155,11 @@ where #[cfg(test)] mod tests { use crate::agent_control::agent_id::AgentID; + use crate::opamp::instance_id::InstanceID; use crate::opamp::instance_id::getter::DataStored; use crate::opamp::instance_id::on_host::getter::Identifiers; use crate::opamp::instance_id::on_host::storer::Storer; use crate::opamp::instance_id::storer::InstanceIDStorer; - use crate::opamp::instance_id::InstanceID; use fs::directory_manager::mock::MockDirectoryManager; use fs::mock::MockLocalFile; use mockall::predicate; @@ -308,13 +308,9 @@ mod tests { } fn expected_file(instance_id: InstanceID) -> String { - format!("instance_id: {}\nidentifiers:\n hostname: {}\n machine_id: {}\n cloud_instance_id: {}\n host_id: {}\n fleet_id: {}\n", - instance_id, - HOSTNAME, - MICHINE_ID, - CLOUD_INSTANCE_ID, - HOST_ID, - FLEET_ID, + format!( + "instance_id: {}\nidentifiers:\n hostname: {}\n machine_id: {}\n cloud_instance_id: {}\n host_id: {}\n fleet_id: {}\n", + instance_id, HOSTNAME, MICHINE_ID, CLOUD_INSTANCE_ID, HOST_ID, FLEET_ID, ) } diff --git a/agent-control/src/opamp/instance_id/storer.rs b/agent-control/src/opamp/instance_id/storer.rs index 856d53e1a7..25261f6a27 100644 --- a/agent-control/src/opamp/instance_id/storer.rs +++ b/agent-control/src/opamp/instance_id/storer.rs @@ -15,7 +15,7 @@ where data: &DataStored, ) -> Result<(), Self::Error>; fn get(&self, agent_id: &AgentID) - -> Result>, Self::Error>; + -> Result>, Self::Error>; } #[cfg(test)] diff --git a/agent-control/src/opamp/operations.rs b/agent-control/src/opamp/operations.rs index 128a660561..c995a4c57d 100644 --- a/agent-control/src/opamp/operations.rs +++ b/agent-control/src/opamp/operations.rs @@ -4,22 +4,22 @@ use super::{ instance_id::getter::InstanceIDGetter, }; use crate::agent_control::defaults::{ - default_capabilities, get_custom_capabilities, OPAMP_SERVICE_NAME, OPAMP_SERVICE_NAMESPACE, - PARENT_AGENT_ID_ATTRIBUTE_KEY, + OPAMP_SERVICE_NAME, OPAMP_SERVICE_NAMESPACE, PARENT_AGENT_ID_ATTRIBUTE_KEY, + default_capabilities, get_custom_capabilities, }; use crate::agent_type::agent_type_id::AgentTypeID; use crate::sub_agent::identity::AgentIdentity; use crate::{ agent_control::agent_id::AgentID, event::{ - channel::{pub_sub, EventConsumer}, OpAMPEvent, + channel::{EventConsumer, pub_sub}, }, sub_agent::error::SubAgentError, }; use opamp_client::{ - operation::settings::{AgentDescription, DescriptionValueType, StartSettings}, StartedClient, + operation::settings::{AgentDescription, DescriptionValueType, StartSettings}, }; use std::collections::HashMap; use tracing::info; diff --git a/agent-control/src/opamp/remote_config/signature.rs b/agent-control/src/opamp/remote_config/signature.rs index f6bfbe7f93..042599c186 100644 --- a/agent-control/src/opamp/remote_config/signature.rs +++ b/agent-control/src/opamp/remote_config/signature.rs @@ -338,10 +338,10 @@ impl TryFrom<&CustomMessage> for Signatures { mod tests { use super::SignatureData; use super::Signatures; - use crate::opamp::remote_config::signature::SigningAlgorithm; use crate::opamp::remote_config::signature::ECDSA_P256_SHA256; use crate::opamp::remote_config::signature::ECDSA_P256_SHA384; use crate::opamp::remote_config::signature::ED25519; + use crate::opamp::remote_config::signature::SigningAlgorithm; use opamp_client::opamp::proto::CustomMessage; use std::collections::HashMap; diff --git a/agent-control/src/opamp/remote_config/validators/regexes.rs b/agent-control/src/opamp/remote_config/validators/regexes.rs index 27d43f258a..f5d3cbeb27 100644 --- a/agent-control/src/opamp/remote_config/validators/regexes.rs +++ b/agent-control/src/opamp/remote_config/validators/regexes.rs @@ -182,8 +182,8 @@ pub(super) mod tests { use crate::agent_control::defaults::{AGENT_TYPE_NAME_INFRA_AGENT, AGENT_TYPE_NAME_NRDOT}; use crate::agent_type::agent_type_id::AgentTypeID; use crate::opamp::remote_config::hash::Hash; - use crate::opamp::remote_config::validators::regexes::{RegexValidator, RegexValidatorError}; use crate::opamp::remote_config::validators::RemoteConfigValidator; + use crate::opamp::remote_config::validators::regexes::{RegexValidator, RegexValidatorError}; use crate::opamp::remote_config::{ConfigurationMap, RemoteConfig}; use crate::sub_agent::identity::AgentIdentity; use assert_matches::assert_matches; diff --git a/agent-control/src/opamp/remote_config/validators/signature/certificate_fetcher.rs b/agent-control/src/opamp/remote_config/validators/signature/certificate_fetcher.rs index 9e09df6d71..060b8adebb 100644 --- a/agent-control/src/opamp/remote_config/validators/signature/certificate_fetcher.rs +++ b/agent-control/src/opamp/remote_config/validators/signature/certificate_fetcher.rs @@ -1,8 +1,8 @@ use super::certificate::Certificate; use crate::http::client::HttpClient; use reqwest::tls::TlsInfo; -use rustls::pki_types::pem::PemObject; use rustls::pki_types::CertificateDer; +use rustls::pki_types::pem::PemObject; use std::path::PathBuf; use thiserror::Error; use tracing::log::error; diff --git a/agent-control/src/opamp/remote_config/validators/signature/certificate_store.rs b/agent-control/src/opamp/remote_config/validators/signature/certificate_store.rs index df55714cdb..8bddf883c5 100644 --- a/agent-control/src/opamp/remote_config/validators/signature/certificate_store.rs +++ b/agent-control/src/opamp/remote_config/validators/signature/certificate_store.rs @@ -1,7 +1,7 @@ use super::certificate::Certificate; use super::certificate_fetcher::CertificateFetcher; -use base64::prelude::BASE64_STANDARD; use base64::Engine; +use base64::prelude::BASE64_STANDARD; use std::sync::Mutex; use thiserror::Error; use tracing::log::error; @@ -10,7 +10,9 @@ use tracing::log::error; pub enum CertificateStoreError { #[error("fetching certificate: `{0}`")] CertificateFetch(String), - #[error("signature keyId({signature_key_id}) does not match certificate keyId({certificate_key_id})")] + #[error( + "signature keyId({signature_key_id}) does not match certificate keyId({certificate_key_id})" + )] KeyMismatch { signature_key_id: String, certificate_key_id: String, diff --git a/agent-control/src/opamp/remote_config/validators/signature/validator.rs b/agent-control/src/opamp/remote_config/validators/signature/validator.rs index 839f800dfa..69481ed822 100644 --- a/agent-control/src/opamp/remote_config/validators/signature/validator.rs +++ b/agent-control/src/opamp/remote_config/validators/signature/validator.rs @@ -2,9 +2,9 @@ use crate::agent_control::defaults::get_custom_capabilities; use crate::http::client::HttpClient; use crate::http::config::HttpConfig; use crate::http::config::ProxyConfig; +use crate::opamp::remote_config::RemoteConfig; use crate::opamp::remote_config::signature::SIGNATURE_CUSTOM_CAPABILITY; use crate::opamp::remote_config::validators::RemoteConfigValidator; -use crate::opamp::remote_config::RemoteConfig; use crate::sub_agent::identity::AgentIdentity; use nix::NixPath; use serde::Deserialize; @@ -210,14 +210,14 @@ mod tests { use super::*; use crate::agent_control::agent_id::AgentID; + use crate::opamp::remote_config::ConfigurationMap; use crate::opamp::remote_config::hash::Hash; use crate::opamp::remote_config::signature::{ - SignatureData, Signatures, ECDSA_P256_SHA256, ED25519, + ECDSA_P256_SHA256, ED25519, SignatureData, Signatures, }; use crate::opamp::remote_config::validators::signature::certificate_store::tests::TestSigner; - use crate::opamp::remote_config::ConfigurationMap; - use crate::sub_agent::identity::tests::test_agent_identity; use crate::sub_agent::identity::AgentIdentity; + use crate::sub_agent::identity::tests::test_agent_identity; use assert_matches::assert_matches; #[test] @@ -433,9 +433,11 @@ certificate_pem_file_path: /path/to/file None, ); // Signature custom capability is not set for agent-control agent, therefore signature is not checked - assert!(signature_validator - .validate(&AgentIdentity::new_agent_control_identity(), &rc) - .is_ok()); + assert!( + signature_validator + .validate(&AgentIdentity::new_agent_control_identity(), &rc) + .is_ok() + ); } #[test] @@ -464,8 +466,10 @@ certificate_pem_file_path: /path/to/file test_signer.key_id(), )); - assert!(signature_validator - .validate(&test_agent_identity(), &remote_config) - .is_ok()) + assert!( + signature_validator + .validate(&test_agent_identity(), &remote_config) + .is_ok() + ) } } diff --git a/agent-control/src/opamp/remote_config/validators/values.rs b/agent-control/src/opamp/remote_config/validators/values.rs index acd9210a4c..159610bd78 100644 --- a/agent-control/src/opamp/remote_config/validators/values.rs +++ b/agent-control/src/opamp/remote_config/validators/values.rs @@ -70,11 +70,11 @@ mod tests { use crate::agent_control::run::Environment; use crate::agent_type::runtime_config::{Deployment, Runtime}; use crate::opamp::remote_config::hash::Hash; - use crate::opamp::remote_config::validators::values::ValuesValidatorError; use crate::opamp::remote_config::validators::RemoteConfigValidator; + use crate::opamp::remote_config::validators::values::ValuesValidatorError; use crate::opamp::remote_config::{ConfigurationMap, RemoteConfig}; - use crate::sub_agent::effective_agents_assembler::tests::MockEffectiveAgentAssembler; use crate::sub_agent::effective_agents_assembler::EffectiveAgent; + use crate::sub_agent::effective_agents_assembler::tests::MockEffectiveAgentAssembler; use crate::sub_agent::identity::tests::test_agent_identity; use assert_matches::assert_matches; use std::collections::HashMap; diff --git a/agent-control/src/sub_agent/collection.rs b/agent-control/src/sub_agent/collection.rs index eaa59e5a6f..fd8e66c3ea 100644 --- a/agent-control/src/sub_agent/collection.rs +++ b/agent-control/src/sub_agent/collection.rs @@ -1,4 +1,4 @@ -use super::{error::SubAgentCollectionError, StartedSubAgent}; +use super::{StartedSubAgent, error::SubAgentCollectionError}; use crate::agent_control::agent_id::AgentID; use std::collections::HashMap; use tracing::{error, info}; @@ -61,8 +61,8 @@ where #[cfg(test)] pub mod tests { use crate::agent_control::agent_id::AgentID; - use crate::sub_agent::collection::StartedSubAgents; use crate::sub_agent::StartedSubAgent; + use crate::sub_agent::collection::StartedSubAgents; use std::collections::HashMap; impl StartedSubAgents diff --git a/agent-control/src/sub_agent/event_handler/on_health.rs b/agent-control/src/sub_agent/event_handler/on_health.rs index cb1d4a2eea..b057384ae3 100644 --- a/agent-control/src/sub_agent/event_handler/on_health.rs +++ b/agent-control/src/sub_agent/event_handler/on_health.rs @@ -1,5 +1,5 @@ -use crate::event::channel::EventPublisher; use crate::event::SubAgentEvent; +use crate::event::channel::EventPublisher; use crate::sub_agent::error::SubAgentError; use crate::sub_agent::health::with_start_time::HealthWithStartTime; use crate::sub_agent::identity::AgentIdentity; diff --git a/agent-control/src/sub_agent/event_handler/on_version.rs b/agent-control/src/sub_agent/event_handler/on_version.rs index b500c92880..e4026824da 100644 --- a/agent-control/src/sub_agent/event_handler/on_version.rs +++ b/agent-control/src/sub_agent/event_handler/on_version.rs @@ -1,7 +1,7 @@ use crate::sub_agent::error::SubAgentError; use crate::sub_agent::version::version_checker::AgentVersion; -use opamp_client::opamp::proto::{any_value, AgentDescription, AnyValue, KeyValue}; use opamp_client::StartedClient; +use opamp_client::opamp::proto::{AgentDescription, AnyValue, KeyValue, any_value}; /// This method request the AgentDescription from the current opamp client and, updates or add the /// field from agent version to be sent to opamp server diff --git a/agent-control/src/sub_agent/health/health_checker.rs b/agent-control/src/sub_agent/health/health_checker.rs index ba99cdc915..6cbd2b95c4 100644 --- a/agent-control/src/sub_agent/health/health_checker.rs +++ b/agent-control/src/sub_agent/health/health_checker.rs @@ -1,8 +1,8 @@ use super::with_start_time::StartTime; use crate::agent_type::runtime_config::HealthCheckInterval; +use crate::event::SubAgentInternalEvent; use crate::event::cancellation::CancellationMessage; use crate::event::channel::{EventConsumer, EventPublisher}; -use crate::event::SubAgentInternalEvent; use crate::k8s; use crate::sub_agent::health::with_start_time::HealthWithStartTime; @@ -283,7 +283,7 @@ pub mod tests { use crate::event::channel::pub_sub; use super::*; - use mockall::{mock, Sequence}; + use mockall::{Sequence, mock}; impl Default for Healthy { fn default() -> Self { diff --git a/agent-control/src/sub_agent/health/k8s/daemon_set.rs b/agent-control/src/sub_agent/health/k8s/daemon_set.rs index 0b32280824..5eabd15c4a 100644 --- a/agent-control/src/sub_agent/health/k8s/daemon_set.rs +++ b/agent-control/src/sub_agent/health/k8s/daemon_set.rs @@ -142,8 +142,8 @@ pub mod tests { k8s::health_checker::LABEL_RELEASE_FLUX, }, }; - use k8s_openapi::api::apps::v1::DaemonSetUpdateStrategy; use k8s_openapi::Resource as _; // Needed to access resource's KIND. e.g.: Deployment::KIND + use k8s_openapi::api::apps::v1::DaemonSetUpdateStrategy; use k8s_openapi::{ api::apps::v1::{DaemonSetSpec, DaemonSetStatus}, apimachinery::pkg::apis::meta::v1::ObjectMeta, diff --git a/agent-control/src/sub_agent/health/k8s/health_checker.rs b/agent-control/src/sub_agent/health/k8s/health_checker.rs index 5801f5edcb..2f5352937e 100644 --- a/agent-control/src/sub_agent/health/k8s/health_checker.rs +++ b/agent-control/src/sub_agent/health/k8s/health_checker.rs @@ -155,13 +155,15 @@ pub mod tests { #[test] fn no_resource_set() { let mock_client = MockSyncK8sClient::default(); - assert!(SubAgentHealthChecker::try_new( - Arc::new(mock_client), - Arc::new(vec![]), - StartTime::now() + assert!( + SubAgentHealthChecker::try_new( + Arc::new(mock_client), + Arc::new(vec![]), + StartTime::now() + ) + .unwrap() + .is_none() ) - .unwrap() - .is_none()) } #[test] fn failing_build_health_check_resource_with_no_type() { @@ -212,16 +214,18 @@ pub mod tests { #[test] fn logic_health_check() { let start_time = StartTime::now(); - assert!(SubAgentHealthChecker { - health_checkers: vec![ - MockHealthCheck::new_healthy(), - MockHealthCheck::new_healthy() - ], - start_time, - } - .check_health() - .unwrap() - .is_healthy()); + assert!( + SubAgentHealthChecker { + health_checkers: vec![ + MockHealthCheck::new_healthy(), + MockHealthCheck::new_healthy() + ], + start_time, + } + .check_health() + .unwrap() + .is_healthy() + ); assert!( !SubAgentHealthChecker { @@ -237,15 +241,17 @@ pub mod tests { .is_healthy() //Notice that this assert has a ! at the beginning ); - assert!(SubAgentHealthChecker { - health_checkers: vec![ - MockHealthCheck::new_healthy(), - MockHealthCheck::new_with_error(), - MockHealthCheck::new_healthy() - ], - start_time - } - .check_health() - .is_err()); + assert!( + SubAgentHealthChecker { + health_checkers: vec![ + MockHealthCheck::new_healthy(), + MockHealthCheck::new_with_error(), + MockHealthCheck::new_healthy() + ], + start_time + } + .check_health() + .is_err() + ); } } diff --git a/agent-control/src/sub_agent/health/k8s/helm_release.rs b/agent-control/src/sub_agent/health/k8s/helm_release.rs index fcea981573..80805be788 100644 --- a/agent-control/src/sub_agent/health/k8s/helm_release.rs +++ b/agent-control/src/sub_agent/health/k8s/helm_release.rs @@ -175,7 +175,7 @@ impl HealthChecker for K8sHealthFluxHelmRelease { pub mod tests { use super::*; use crate::agent_control::config::helmrelease_v2_type_meta; - use crate::k8s::{client::MockSyncK8sClient, Error}; + use crate::k8s::{Error, client::MockSyncK8sClient}; use crate::sub_agent::health::health_checker::Health; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use kube::core::DynamicObject; diff --git a/agent-control/src/sub_agent/health/k8s/utils.rs b/agent-control/src/sub_agent/health/k8s/utils.rs index ebcabc3a8d..613da70007 100644 --- a/agent-control/src/sub_agent/health/k8s/utils.rs +++ b/agent-control/src/sub_agent/health/k8s/utils.rs @@ -3,7 +3,7 @@ use super::health_checker::LABEL_RELEASE_FLUX; use crate::sub_agent::health::health_checker::{Health, HealthCheckerError, Healthy}; use k8s_openapi::{ - apimachinery::pkg::apis::meta::v1::ObjectMeta, Metadata, NamespaceResourceScope, Resource, + Metadata, NamespaceResourceScope, Resource, apimachinery::pkg::apis::meta::v1::ObjectMeta, }; use kube::core::{Expression, Selector, SelectorExt}; use std::{any::Any, sync::Arc}; diff --git a/agent-control/src/sub_agent/k8s/builder.rs b/agent-control/src/sub_agent/k8s/builder.rs index 0a9a88e969..351f5b7fcb 100644 --- a/agent-control/src/sub_agent/k8s/builder.rs +++ b/agent-control/src/sub_agent/k8s/builder.rs @@ -1,23 +1,23 @@ use crate::agent_control::config::K8sConfig; use crate::agent_control::defaults::{CLUSTER_NAME_ATTRIBUTE_KEY, OPAMP_SERVICE_VERSION}; -use crate::event::channel::{pub_sub, EventPublisher}; use crate::event::SubAgentEvent; +use crate::event::channel::{EventPublisher, pub_sub}; #[cfg_attr(test, mockall_double::double)] use crate::k8s::client::SyncK8sClient; use crate::opamp::hash_repository::HashRepository; use crate::opamp::instance_id::getter::InstanceIDGetter; use crate::opamp::operations::build_sub_agent_opamp; +use crate::sub_agent::SubAgent; use crate::sub_agent::effective_agents_assembler::EffectiveAgent; use crate::sub_agent::identity::AgentIdentity; use crate::sub_agent::remote_config_parser::RemoteConfigParser; use crate::sub_agent::supervisor::assembler::SupervisorAssembler; use crate::sub_agent::supervisor::builder::SupervisorBuilder; -use crate::sub_agent::SubAgent; use crate::values::yaml_config_repository::YAMLConfigRepository; use crate::{ opamp::client_builder::OpAMPClientBuilder, sub_agent::k8s::supervisor::NotStartedSupervisorK8s, - sub_agent::{error::SubAgentBuilderError, SubAgentBuilder}, + sub_agent::{SubAgentBuilder, error::SubAgentBuilderError}, }; use opamp_client::operation::settings::DescriptionValueType; use std::collections::{HashMap, HashSet}; @@ -192,12 +192,12 @@ pub mod tests { use crate::agent_type::runtime_config::k8s::{K8s, K8sObject}; use crate::agent_type::runtime_config::{Deployment, Runtime}; use crate::event::channel::pub_sub; - use crate::opamp::client_builder::tests::MockStartedOpAMPClient; use crate::opamp::client_builder::OpAMPClientBuilderError; + use crate::opamp::client_builder::tests::MockStartedOpAMPClient; use crate::opamp::hash_repository::repository::tests::MockHashRepository; use crate::opamp::http::builder::HttpClientBuilderError; - use crate::opamp::instance_id::getter::tests::MockInstanceIDGetter; use crate::opamp::instance_id::InstanceID; + use crate::opamp::instance_id::getter::tests::MockInstanceIDGetter; use crate::opamp::operations::start_settings; use crate::sub_agent::remote_config_parser::tests::MockRemoteConfigParser; use crate::sub_agent::supervisor::assembler::tests::MockSupervisorAssembler; diff --git a/agent-control/src/sub_agent/k8s/supervisor.rs b/agent-control/src/sub_agent/k8s/supervisor.rs index 2286dcbb36..f0eeecdfff 100644 --- a/agent-control/src/sub_agent/k8s/supervisor.rs +++ b/agent-control/src/sub_agent/k8s/supervisor.rs @@ -1,9 +1,9 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_type::runtime_config::k8s::{K8s, K8sObject}; use crate::agent_type::version_config::VersionCheckerInterval; +use crate::event::SubAgentInternalEvent; use crate::event::cancellation::CancellationMessage; use crate::event::channel::{EventConsumer, EventPublisher}; -use crate::event::SubAgentInternalEvent; use crate::k8s::annotations::Annotations; #[cfg_attr(test, mockall_double::double)] use crate::k8s::client::SyncK8sClient; @@ -236,8 +236,8 @@ pub mod tests { use crate::agent_control::config::helmrelease_v2_type_meta; use crate::agent_type::agent_type_id::AgentTypeID; use crate::agent_type::runtime_config::k8s::{K8sHealthConfig, K8sObjectMeta}; - use crate::event::channel::pub_sub; use crate::event::SubAgentEvent; + use crate::event::channel::pub_sub; use crate::k8s::client::MockSyncK8sClient; use crate::k8s::error::K8sError; use crate::k8s::labels::AGENT_ID_LABEL_KEY; @@ -406,10 +406,12 @@ pub mod tests { let started = not_started .start(sub_agent_internal_publisher) .expect("supervisor started"); - assert!(!started - .thread_contexts - .iter() - .any(|thread_contexts| thread_contexts.thread_name() == "k8s health checker")); + assert!( + !started + .thread_contexts + .iter() + .any(|thread_contexts| thread_contexts.thread_name() == "k8s health checker") + ); } fn k8s_object() -> K8sObject { diff --git a/agent-control/src/sub_agent/on_host/builder.rs b/agent-control/src/sub_agent/on_host/builder.rs index cd05fbf9d1..5183ca583a 100644 --- a/agent-control/src/sub_agent/on_host/builder.rs +++ b/agent-control/src/sub_agent/on_host/builder.rs @@ -1,10 +1,11 @@ use crate::agent_control::defaults::{HOST_NAME_ATTRIBUTE_KEY, OPAMP_SERVICE_VERSION}; use crate::context::Context; -use crate::event::channel::{pub_sub, EventPublisher}; use crate::event::SubAgentEvent; +use crate::event::channel::{EventPublisher, pub_sub}; use crate::opamp::hash_repository::HashRepository; use crate::opamp::instance_id::getter::InstanceIDGetter; use crate::opamp::operations::build_sub_agent_opamp; +use crate::sub_agent::SubAgent; use crate::sub_agent::effective_agents_assembler::EffectiveAgent; use crate::sub_agent::identity::AgentIdentity; use crate::sub_agent::on_host::command::executable_data::ExecutableData; @@ -12,11 +13,10 @@ use crate::sub_agent::on_host::supervisor::NotStartedSupervisorOnHost; use crate::sub_agent::remote_config_parser::RemoteConfigParser; use crate::sub_agent::supervisor::assembler::SupervisorAssembler; use crate::sub_agent::supervisor::builder::SupervisorBuilder; -use crate::sub_agent::SubAgent; use crate::values::yaml_config_repository::YAMLConfigRepository; use crate::{ opamp::client_builder::OpAMPClientBuilder, - sub_agent::{error::SubAgentBuilderError, SubAgentBuilder}, + sub_agent::{SubAgentBuilder, error::SubAgentBuilderError}, }; #[cfg(unix)] use nix::unistd::gethostname; @@ -181,16 +181,16 @@ mod tests { use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::{ - default_capabilities, default_sub_agent_custom_capabilities, OPAMP_SERVICE_NAME, - OPAMP_SERVICE_NAMESPACE, OPAMP_SERVICE_VERSION, PARENT_AGENT_ID_ATTRIBUTE_KEY, + OPAMP_SERVICE_NAME, OPAMP_SERVICE_NAMESPACE, OPAMP_SERVICE_VERSION, + PARENT_AGENT_ID_ATTRIBUTE_KEY, default_capabilities, default_sub_agent_custom_capabilities, }; use crate::agent_type::agent_type_id::AgentTypeID; use crate::event::channel::pub_sub; use crate::opamp::client_builder::tests::MockOpAMPClientBuilder; use crate::opamp::client_builder::tests::MockStartedOpAMPClient; use crate::opamp::hash_repository::repository::tests::MockHashRepository; - use crate::opamp::instance_id::getter::tests::MockInstanceIDGetter; use crate::opamp::instance_id::InstanceID; + use crate::opamp::instance_id::getter::tests::MockInstanceIDGetter; use crate::sub_agent::remote_config_parser::tests::MockRemoteConfigParser; use crate::sub_agent::supervisor::assembler::tests::MockSupervisorAssembler; use crate::sub_agent::supervisor::starter::tests::MockSupervisorStarter; diff --git a/agent-control/src/sub_agent/on_host/command/logging/file_logger.rs b/agent-control/src/sub_agent/on_host/command/logging/file_logger.rs index 47c5aa69ae..6727485fac 100644 --- a/agent-control/src/sub_agent/on_host/command/logging/file_logger.rs +++ b/agent-control/src/sub_agent/on_host/command/logging/file_logger.rs @@ -8,8 +8,8 @@ use tracing_appender::{ rolling::RollingFileAppender, }; use tracing_subscriber::{ - fmt::format::{DefaultFields, Format, Full}, FmtSubscriber, + fmt::format::{DefaultFields, Format, Full}, }; use crate::agent_control::agent_id::AgentID; diff --git a/agent-control/src/sub_agent/on_host/command/logging/thread.rs b/agent-control/src/sub_agent/on_host/command/logging/thread.rs index 9e7caf627a..88ed44344e 100644 --- a/agent-control/src/sub_agent/on_host/command/logging/thread.rs +++ b/agent-control/src/sub_agent/on_host/command/logging/thread.rs @@ -50,7 +50,7 @@ mod tests { use crate::agent_control::agent_id::AgentID; use crate::sub_agent::on_host::command::logging::file_logger::FileLogger; use mockall::predicate::*; - use mockall::{mock, Sequence}; + use mockall::{Sequence, mock}; use std::io::{Read, Seek, SeekFrom, Write}; use tempfile::tempfile; use tracing_test::internal::logs_with_scope_contain; diff --git a/agent-control/src/sub_agent/on_host/command/restart_policy.rs b/agent-control/src/sub_agent/on_host/command/restart_policy.rs index 5aabb05043..9891c30ce7 100644 --- a/agent-control/src/sub_agent/on_host/command/restart_policy.rs +++ b/agent-control/src/sub_agent/on_host/command/restart_policy.rs @@ -68,9 +68,9 @@ pub const LAST_RETRY_INTERVAL: Duration = Duration::new(30, 0); impl BackoffStrategy { fn should_backoff(&mut self) -> bool { match self { - BackoffStrategy::Fixed(ref mut b) - | BackoffStrategy::Linear(ref mut b) - | BackoffStrategy::Exponential(ref mut b) => b.should_backoff(), + BackoffStrategy::Fixed(b) + | BackoffStrategy::Linear(b) + | BackoffStrategy::Exponential(b) => b.should_backoff(), BackoffStrategy::None => true, } } @@ -80,9 +80,9 @@ impl BackoffStrategy { S: FnOnce(Duration), { match self { - BackoffStrategy::Fixed(ref mut b) => b.backoff(fixed, sleep_func), - BackoffStrategy::Linear(ref mut b) => b.backoff(linear, sleep_func), - BackoffStrategy::Exponential(ref mut b) => b.backoff(exponential, sleep_func), + BackoffStrategy::Fixed(b) => b.backoff(fixed, sleep_func), + BackoffStrategy::Linear(b) => b.backoff(linear, sleep_func), + BackoffStrategy::Exponential(b) => b.backoff(exponential, sleep_func), BackoffStrategy::None => {} } } diff --git a/agent-control/src/sub_agent/on_host/supervisor.rs b/agent-control/src/sub_agent/on_host/supervisor.rs index 0c29378c50..7670782588 100644 --- a/agent-control/src/sub_agent/on_host/supervisor.rs +++ b/agent-control/src/sub_agent/on_host/supervisor.rs @@ -2,12 +2,12 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_type::runtime_config::health_config::OnHostHealthConfig; use crate::agent_type::version_config::VersionCheckerInterval; use crate::context::Context; -use crate::event::channel::EventPublisher; use crate::event::SubAgentInternalEvent; +use crate::event::channel::EventPublisher; use crate::http::client::HttpClient; use crate::http::config::{HttpConfig, ProxyConfig}; use crate::sub_agent::health::health_checker::{ - publish_health_event, spawn_health_checker, HealthCheckerError, + HealthCheckerError, publish_health_event, spawn_health_checker, }; use crate::sub_agent::health::health_checker::{Healthy, Unhealthy}; use crate::sub_agent::health::on_host::health_checker::OnHostHealthChecker; @@ -18,7 +18,7 @@ use crate::sub_agent::on_host::command::command_os::CommandOSNotStarted; use crate::sub_agent::on_host::command::executable_data::ExecutableData; use crate::sub_agent::on_host::command::restart_policy::BackoffStrategy; use crate::sub_agent::on_host::command::shutdown::{ - wait_exit_timeout, wait_exit_timeout_default, ProcessTerminator, + ProcessTerminator, wait_exit_timeout, wait_exit_timeout_default, }; use crate::sub_agent::supervisor::starter::{SupervisorStarter, SupervisorStarterError}; use crate::sub_agent::supervisor::stopper::SupervisorStopper; @@ -253,7 +253,9 @@ impl NotStartedSupervisorOnHost { if !restart_policy.should_retry(exit_code.unwrap_or_default()) { // Log if we are not restarting anymore due to the restart policy being broken if restart_policy.backoff != BackoffStrategy::None { - warn!("supervisor won't restart anymore due to having exceeded its restart policy"); + warn!( + "supervisor won't restart anymore due to having exceeded its restart policy" + ); let unhealthy = Unhealthy::new( String::default(), @@ -366,7 +368,6 @@ fn wait_for_termination( drop(cvar.wait_while(lck.lock().unwrap(), |finish| !*finish)); // context is unlocked here so locking it again in other thread that is blocking current_pid is safe. - if let Some(pid) = *current_pid.lock().unwrap() { info!(pid = pid, msg = "stopping supervisor process"); _ = ProcessTerminator::new(pid).shutdown(|| wait_exit_timeout_default(shutdown_ctx)); diff --git a/agent-control/src/sub_agent/remote_config_parser.rs b/agent-control/src/sub_agent/remote_config_parser.rs index b5f0c2defb..d3b8dd196c 100644 --- a/agent-control/src/sub_agent/remote_config_parser.rs +++ b/agent-control/src/sub_agent/remote_config_parser.rs @@ -1,5 +1,5 @@ -use crate::opamp::remote_config::validators::RemoteConfigValidator; use crate::opamp::remote_config::RemoteConfig; +use crate::opamp::remote_config::validators::RemoteConfigValidator; use crate::sub_agent::identity::AgentIdentity; use crate::values::yaml_config::YAMLConfig; use thiserror::Error; @@ -98,8 +98,8 @@ pub mod tests { use crate::opamp::remote_config::hash::Hash; use crate::opamp::remote_config::validators::tests::MockRemoteConfigValidator; use crate::opamp::remote_config::{ConfigurationMap, RemoteConfig}; - use crate::sub_agent::identity::tests::test_agent_identity; use crate::sub_agent::identity::AgentIdentity; + use crate::sub_agent::identity::tests::test_agent_identity; use crate::values::yaml_config::YAMLConfig; use assert_matches::assert_matches; use mockall::mock; diff --git a/agent-control/src/sub_agent/sub_agent.rs b/agent-control/src/sub_agent/sub_agent.rs index e49cdf2799..f186b43951 100644 --- a/agent-control/src/sub_agent/sub_agent.rs +++ b/agent-control/src/sub_agent/sub_agent.rs @@ -1,13 +1,13 @@ use super::error::SubAgentStopError; use super::health::health_checker::Health; use crate::agent_control::uptime_report::{UptimeReportConfig, UptimeReporter}; -use crate::event::channel::{EventConsumer, EventPublisher}; use crate::event::SubAgentEvent::SubAgentStarted; +use crate::event::channel::{EventConsumer, EventPublisher}; use crate::event::{OpAMPEvent, SubAgentEvent, SubAgentInternalEvent}; use crate::opamp::hash_repository::HashRepository; use crate::opamp::operations::stop_opamp_client; -use crate::opamp::remote_config::report::OpampRemoteConfigStatus; use crate::opamp::remote_config::RemoteConfig; +use crate::opamp::remote_config::report::OpampRemoteConfigStatus; use crate::sub_agent::error::{SubAgentBuilderError, SubAgentError}; use crate::sub_agent::event_handler::on_health::on_health; use crate::sub_agent::event_handler::on_version::on_version; diff --git a/agent-control/src/sub_agent/supervisor/assembler.rs b/agent-control/src/sub_agent/supervisor/assembler.rs index 343144f0e9..42479fdb82 100644 --- a/agent-control/src/sub_agent/supervisor/assembler.rs +++ b/agent-control/src/sub_agent/supervisor/assembler.rs @@ -7,7 +7,7 @@ use crate::sub_agent::identity::AgentIdentity; use crate::sub_agent::supervisor::builder::SupervisorBuilder; use crate::sub_agent::supervisor::starter::SupervisorStarter; use crate::values::yaml_config_repository::{ - load_remote_fallback_local, YAMLConfigRepository, YAMLConfigRepositoryError, + YAMLConfigRepository, YAMLConfigRepositoryError, load_remote_fallback_local, }; use opamp_client::StartedClient; use std::sync::Arc; @@ -188,8 +188,8 @@ pub mod tests { use crate::agent_type::runtime_config::onhost::OnHost; use crate::agent_type::runtime_config::{Deployment, Runtime}; use crate::opamp::client_builder::tests::MockStartedOpAMPClient; - use crate::opamp::hash_repository::repository::tests::MockHashRepository; use crate::opamp::hash_repository::repository::HashRepositoryError; + use crate::opamp::hash_repository::repository::tests::MockHashRepository; use crate::opamp::remote_config::hash::Hash; use crate::sub_agent::effective_agents_assembler::tests::MockEffectiveAgentAssembler; use crate::sub_agent::effective_agents_assembler::{ @@ -200,15 +200,15 @@ pub mod tests { AgentSupervisorAssembler, SupervisorAssembler, SupervisorAssemblerError, }; use crate::sub_agent::supervisor::builder::tests::MockSupervisorBuilder; - use crate::sub_agent::supervisor::starter::tests::MockSupervisorStarter; use crate::sub_agent::supervisor::starter::SupervisorStarter; + use crate::sub_agent::supervisor::starter::tests::MockSupervisorStarter; use crate::sub_agent::supervisor::stopper::tests::MockSupervisorStopper; use crate::values::yaml_config::YAMLConfig; use crate::values::yaml_config_repository::tests::MockYAMLConfigRepository; use mockall::mock; + use opamp_client::StartedClient; use opamp_client::opamp::proto::RemoteConfigStatus; use opamp_client::opamp::proto::RemoteConfigStatuses::{Applied, Failed}; - use opamp_client::StartedClient; use predicates::prelude::predicate; use std::sync::Arc; @@ -377,9 +377,11 @@ pub mod tests { started_opamp_client.should_update_effective_config(1); let maybe_opamp_client = Some(started_opamp_client); - assert!(assembler - .assemble_supervisor(&maybe_opamp_client, agent_identity) - .is_ok()); + assert!( + assembler + .assemble_supervisor(&maybe_opamp_client, agent_identity) + .is_ok() + ); } /// `maybe_opamp_client == Some(_)` @@ -403,9 +405,11 @@ pub mod tests { // Expected calls on the opamp client let maybe_opamp_client = Some(OpampClientForTest::new()); - assert!(assembler - .assemble_supervisor(&maybe_opamp_client, agent_identity) - .is_ok()); + assert!( + assembler + .assemble_supervisor(&maybe_opamp_client, agent_identity) + .is_ok() + ); } /// `maybe_opamp_client == Some(_)` @@ -469,9 +473,11 @@ pub mod tests { let maybe_opamp_client = Some(opamp_client); - assert!(supervisor_assembler - .assemble_supervisor(&maybe_opamp_client, agent_identity) - .is_err()); + assert!( + supervisor_assembler + .assemble_supervisor(&maybe_opamp_client, agent_identity) + .is_err() + ); } fn setup_hash_repository(hash: String, agent_identity: AgentIdentity) -> MockHashRepository { @@ -557,13 +563,17 @@ pub mod tests { ); if should_return_effective_agent { - assert!(supervisor_assembler - .assemble_supervisor(&maybe_opamp_client, agent_identity) - .is_ok()); + assert!( + supervisor_assembler + .assemble_supervisor(&maybe_opamp_client, agent_identity) + .is_ok() + ); } else { - assert!(supervisor_assembler - .assemble_supervisor(&maybe_opamp_client, agent_identity) - .is_err()); + assert!( + supervisor_assembler + .assemble_supervisor(&maybe_opamp_client, agent_identity) + .is_err() + ); } } } diff --git a/agent-control/src/sub_agent/supervisor/starter.rs b/agent-control/src/sub_agent/supervisor/starter.rs index 3314b7e393..92778f1f45 100644 --- a/agent-control/src/sub_agent/supervisor/starter.rs +++ b/agent-control/src/sub_agent/supervisor/starter.rs @@ -1,5 +1,5 @@ -use crate::event::channel::EventPublisher; use crate::event::SubAgentInternalEvent; +use crate::event::channel::EventPublisher; use crate::sub_agent::error::SubAgentBuilderError; use crate::sub_agent::health::health_checker::HealthCheckerError; use crate::sub_agent::supervisor::stopper::SupervisorStopper; @@ -31,8 +31,8 @@ pub trait SupervisorStarter { #[cfg(test)] pub(crate) mod tests { - use crate::event::channel::EventPublisher; use crate::event::SubAgentInternalEvent; + use crate::event::channel::EventPublisher; use crate::sub_agent::supervisor::starter::{SupervisorStarter, SupervisorStarterError}; use crate::sub_agent::supervisor::stopper::tests::MockSupervisorStopper; use mockall::mock; diff --git a/agent-control/src/sub_agent/version/k8s/checkers.rs b/agent-control/src/sub_agent/version/k8s/checkers.rs index 7d1a0db036..e74366b5e0 100644 --- a/agent-control/src/sub_agent/version/k8s/checkers.rs +++ b/agent-control/src/sub_agent/version/k8s/checkers.rs @@ -75,7 +75,9 @@ impl K8sAgentVersionChecker { }; return Some(health_checker); } - warn!("Version cannot be fetched from any of the agent underlying resources, it won't be reported"); + warn!( + "Version cannot be fetched from any of the agent underlying resources, it won't be reported" + ); None } } diff --git a/agent-control/src/sub_agent/version/k8s/helmrelease.rs b/agent-control/src/sub_agent/version/k8s/helmrelease.rs index 0882ef901c..f96dbfb458 100644 --- a/agent-control/src/sub_agent/version/k8s/helmrelease.rs +++ b/agent-control/src/sub_agent/version/k8s/helmrelease.rs @@ -136,7 +136,7 @@ pub mod tests { use crate::agent_control::defaults::OPAMP_CHART_VERSION_ATTRIBUTE_KEY; use crate::k8s::client::MockSyncK8sClient; use kube::api::DynamicObject; - use serde_json::{json, Value}; + use serde_json::{Value, json}; use std::sync::Arc; impl std::fmt::Debug for HelmReleaseVersionChecker { diff --git a/agent-control/src/sub_agent/version/version_checker.rs b/agent-control/src/sub_agent/version/version_checker.rs index e43a764fec..316bb062d0 100644 --- a/agent-control/src/sub_agent/version/version_checker.rs +++ b/agent-control/src/sub_agent/version/version_checker.rs @@ -1,7 +1,7 @@ use crate::agent_type::version_config::VersionCheckerInterval; +use crate::event::SubAgentInternalEvent; use crate::event::cancellation::CancellationMessage; use crate::event::channel::{EventConsumer, EventPublisher}; -use crate::event::SubAgentInternalEvent; use crate::utils::thread_context::{NotStartedThreadContext, StartedThreadContext}; use tracing::{debug, error, info, warn}; @@ -100,12 +100,12 @@ pub(crate) fn publish_version_event( #[cfg(test)] pub mod tests { use crate::agent_control::defaults::OPAMP_CHART_VERSION_ATTRIBUTE_KEY; - use crate::event::channel::pub_sub; use crate::event::SubAgentInternalEvent::AgentVersionInfo; + use crate::event::channel::pub_sub; use crate::sub_agent::version::version_checker::{ - spawn_version_checker, AgentVersion, VersionCheckError, VersionChecker, + AgentVersion, VersionCheckError, VersionChecker, spawn_version_checker, }; - use mockall::{mock, Sequence}; + use mockall::{Sequence, mock}; use std::time::Duration; mock! { diff --git a/agent-control/src/utils/binary_metadata.rs b/agent-control/src/utils/binary_metadata.rs index d2819a4bb0..1f17184862 100644 --- a/agent-control/src/utils/binary_metadata.rs +++ b/agent-control/src/utils/binary_metadata.rs @@ -7,5 +7,7 @@ pub(crate) const GIT_COMMIT: &str = konst::option::unwrap_or!(option_env!("GIT_COMMIT"), "development"); pub fn binary_metadata(env: Environment) -> String { - format!("New Relic Agent Control Version: {VERSION}, Rust Version: {RUST_VERSION}, GitCommit: {GIT_COMMIT}, Environment: {env}") + format!( + "New Relic Agent Control Version: {VERSION}, Rust Version: {RUST_VERSION}, GitCommit: {GIT_COMMIT}, Environment: {env}" + ) } diff --git a/agent-control/src/utils/tests.rs b/agent-control/src/utils/tests.rs index fdc65dd35b..b6d32855d0 100644 --- a/agent-control/src/utils/tests.rs +++ b/agent-control/src/utils/tests.rs @@ -10,11 +10,10 @@ where { let mut last_err = Ok(()); for _ in 0..max_attempts { - if let Err(err) = f() { - last_err = Err(err) - } else { + let Err(err) = f() else { return; - } + }; + last_err = Err(err); std::thread::sleep(interval); } last_err.unwrap_or_else(|err| panic!("retry failed after {max_attempts} attempts: {err}")) diff --git a/agent-control/src/utils/thread_context.rs b/agent-control/src/utils/thread_context.rs index 37bb59e7dc..46e0b8536c 100644 --- a/agent-control/src/utils/thread_context.rs +++ b/agent-control/src/utils/thread_context.rs @@ -1,5 +1,5 @@ use std::{ - thread::{sleep, JoinHandle}, + thread::{JoinHandle, sleep}, time::Duration, }; use tracing::{debug, debug_span, trace}; @@ -10,7 +10,7 @@ const GRACEFUL_STOP_RETRY_INTERVAL: Duration = Duration::from_millis(100); use crate::{ event::{ cancellation::CancellationMessage, - channel::{pub_sub, EventConsumer, EventPublisher}, + channel::{EventConsumer, EventPublisher, pub_sub}, }, utils::threads::spawn_named_thread, }; diff --git a/agent-control/src/values/file.rs b/agent-control/src/values/file.rs index 3970e8eb39..52221be4aa 100644 --- a/agent-control/src/values/file.rs +++ b/agent-control/src/values/file.rs @@ -2,12 +2,12 @@ use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::{ AGENT_CONTROL_CONFIG_FILENAME, SUB_AGENT_DIR, VALUES_DIR, VALUES_FILENAME, }; -use crate::values::yaml_config::{has_remote_management, YAMLConfig}; +use crate::values::yaml_config::{YAMLConfig, has_remote_management}; use crate::values::yaml_config_repository::{YAMLConfigRepository, YAMLConfigRepositoryError}; +use fs::LocalFile; use fs::directory_manager::{DirectoryManagementError, DirectoryManager, DirectoryManagerFs}; use fs::file_reader::{FileReader, FileReaderError}; use fs::writer_file::{FileWriter, WriteError}; -use fs::LocalFile; use opamp_client::operation::capabilities::Capabilities; use std::fs::Permissions; #[cfg(target_family = "unix")] @@ -220,17 +220,17 @@ pub fn concatenate_sub_agent_dir_path(dir: &Path, agent_id: &AgentID) -> PathBuf pub mod tests { use rstest::*; - use super::{concatenate_sub_agent_dir_path, YAMLConfigRepositoryFile}; + use super::{YAMLConfigRepositoryFile, concatenate_sub_agent_dir_path}; use crate::agent_control::agent_id::AgentID; use crate::agent_control::defaults::default_capabilities; use crate::values::yaml_config::YAMLConfig; use crate::values::yaml_config_repository::{ - load_remote_fallback_local, YAMLConfigRepository, YAMLConfigRepositoryError, + YAMLConfigRepository, YAMLConfigRepositoryError, load_remote_fallback_local, }; use assert_matches::assert_matches; - use fs::directory_manager::mock::MockDirectoryManager; use fs::directory_manager::DirectoryManagementError::ErrorCreatingDirectory; use fs::directory_manager::DirectoryManager; + use fs::directory_manager::mock::MockDirectoryManager; use fs::file_reader::FileReader; use fs::mock::MockLocalFile; use fs::writer_file::FileWriter; diff --git a/agent-control/src/values/k8s.rs b/agent-control/src/values/k8s.rs index 1bf65e75f9..e6f7a10ebe 100644 --- a/agent-control/src/values/k8s.rs +++ b/agent-control/src/values/k8s.rs @@ -1,7 +1,7 @@ use crate::agent_control::agent_id::AgentID; use crate::k8s; use crate::k8s::store::{K8sStore, STORE_KEY_LOCAL_DATA_CONFIG, STORE_KEY_OPAMP_DATA_CONFIG}; -use crate::values::yaml_config::{has_remote_management, YAMLConfig}; +use crate::values::yaml_config::{YAMLConfig, has_remote_management}; use crate::values::yaml_config_repository::{YAMLConfigRepository, YAMLConfigRepositoryError}; use opamp_client::operation::capabilities::Capabilities; use std::sync::Arc; diff --git a/agent-control/tests/common/agent_control.rs b/agent-control/tests/common/agent_control.rs index 1f109d27b5..2c977a081b 100644 --- a/agent-control/tests/common/agent_control.rs +++ b/agent-control/tests/common/agent_control.rs @@ -5,8 +5,8 @@ use newrelic_agent_control::agent_control::config_storer::store::AgentControlCon use newrelic_agent_control::agent_control::run::{ AgentControlRunConfig, AgentControlRunner, BasePaths, Environment, }; -use newrelic_agent_control::event::channel::{pub_sub, EventPublisher}; use newrelic_agent_control::event::ApplicationEvent; +use newrelic_agent_control::event::channel::{EventPublisher, pub_sub}; use newrelic_agent_control::http::tls::install_rustls_default_crypto_provider; use newrelic_agent_control::values::file::YAMLConfigRepositoryFile; use std::sync::Arc; diff --git a/agent-control/tests/common/global_logger.rs b/agent-control/tests/common/global_logger.rs index 20942fe0df..d234fd56f8 100644 --- a/agent-control/tests/common/global_logger.rs +++ b/agent-control/tests/common/global_logger.rs @@ -3,7 +3,7 @@ use std::sync::Once; use newrelic_agent_control::agent_control::defaults::AGENT_CONTROL_LOG_DIR; use newrelic_agent_control::instrumentation::config::logs::config::LoggingConfig; -use newrelic_agent_control::instrumentation::tracing::{try_init_tracing, TracingConfig}; +use newrelic_agent_control::instrumentation::tracing::{TracingConfig, try_init_tracing}; static INIT_LOGGER: Once = Once::new(); diff --git a/agent-control/tests/common/opamp.rs b/agent-control/tests/common/opamp.rs index 8da343fce5..2a8983ac27 100644 --- a/agent-control/tests/common/opamp.rs +++ b/agent-control/tests/common/opamp.rs @@ -1,10 +1,10 @@ use super::runtime::tokio_runtime; -use actix_web::{web, App, HttpResponse, HttpServer}; -use base64::prelude::BASE64_STANDARD; +use actix_web::{App, HttpResponse, HttpServer, web}; use base64::Engine; +use base64::prelude::BASE64_STANDARD; use newrelic_agent_control::opamp::instance_id::InstanceID; use newrelic_agent_control::opamp::remote_config::signature::{ - SignatureFields, ED25519, SIGNATURE_CUSTOM_CAPABILITY, SIGNATURE_CUSTOM_MESSAGE_TYPE, + ED25519, SIGNATURE_CUSTOM_CAPABILITY, SIGNATURE_CUSTOM_MESSAGE_TYPE, SignatureFields, }; use newrelic_agent_control::opamp::remote_config::validators::signature::public_key_fingerprint; use opamp_client::opamp; diff --git a/agent-control/tests/common/retry.rs b/agent-control/tests/common/retry.rs index 80cb7c2f8e..9e85521bc9 100644 --- a/agent-control/tests/common/retry.rs +++ b/agent-control/tests/common/retry.rs @@ -9,11 +9,10 @@ where { let mut last_err = Ok(()); for _ in 0..max_attempts { - if let Err(err) = f() { - last_err = Err(err) - } else { + let Err(err) = f() else { return; - } + }; + last_err = Err(err); std::thread::sleep(interval); } last_err.unwrap_or_else(|err| panic!("retry failed after {max_attempts} attempts: {err}")) diff --git a/agent-control/tests/k8s/client.rs b/agent-control/tests/k8s/client.rs index bc63ff90ec..fee50c4f8b 100644 --- a/agent-control/tests/k8s/client.rs +++ b/agent-control/tests/k8s/client.rs @@ -1,18 +1,18 @@ use super::tools::{ k8s_env::K8sEnv, - test_crd::{create_foo_cr, foo_type_meta, get_dynamic_api_foo, Foo, FooSpec}, + test_crd::{Foo, FooSpec, create_foo_cr, foo_type_meta, get_dynamic_api_foo}, }; use crate::k8s::tools::test_crd::{build_dynamic_object, create_crd, delete_crd}; use assert_matches::assert_matches; use kube::core::DynamicObject; use kube::{ - api::{Api, DeleteParams, TypeMeta}, CustomResource, + api::{Api, DeleteParams, TypeMeta}, }; use kube::{CustomResourceExt, ResourceExt}; use newrelic_agent_control::k8s::Error::MissingAPIResource; -use newrelic_agent_control::k8s::{client::AsyncK8sClient, Error}; +use newrelic_agent_control::k8s::{Error, client::AsyncK8sClient}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -553,25 +553,29 @@ async fn k8s_remove_crd_after_dynamic_resource_initialized() { tokio::time::sleep(Duration::from_secs(5)).await; // Old removed CR should not be found - assert!(k8s_client - .dynamic_object_managers() - .get( - &dynamic_object.types.clone().unwrap(), - &dynamic_object.name_unchecked(), - ) - .await - .unwrap() - .is_none()); + assert!( + k8s_client + .dynamic_object_managers() + .get( + &dynamic_object.types.clone().unwrap(), + &dynamic_object.name_unchecked(), + ) + .await + .unwrap() + .is_none() + ); // New CR should be found - assert!(k8s_client - .dynamic_object_managers() - .get( - &new_dyn_object.types.clone().unwrap(), - &new_dyn_object.name_unchecked(), - ) - .await - .unwrap() - .is_some()); + assert!( + k8s_client + .dynamic_object_managers() + .get( + &new_dyn_object.types.clone().unwrap(), + &new_dyn_object.name_unchecked(), + ) + .await + .unwrap() + .is_some() + ); // clean up delete_crd(k8s.client.clone(), ClientTest::crd()) diff --git a/agent-control/tests/k8s/garbage_collector.rs b/agent-control/tests/k8s/garbage_collector.rs index acae436aa0..ab3c393cd0 100644 --- a/agent-control/tests/k8s/garbage_collector.rs +++ b/agent-control/tests/k8s/garbage_collector.rs @@ -5,7 +5,7 @@ use crate::common::{ use super::tools::{ k8s_env::K8sEnv, - test_crd::{create_foo_cr, foo_type_meta, Foo}, + test_crd::{Foo, create_foo_cr, foo_type_meta}, }; use k8s_openapi::api::core::v1::Secret; use kube::{api::Api, core::TypeMeta}; diff --git a/agent-control/tests/k8s/scenarios/ac_restarts.rs b/agent-control/tests/k8s/scenarios/ac_restarts.rs index 361386f0b5..acaa72fa20 100644 --- a/agent-control/tests/k8s/scenarios/ac_restarts.rs +++ b/agent-control/tests/k8s/scenarios/ac_restarts.rs @@ -4,8 +4,8 @@ use crate::common::opamp::{ConfigResponse, FakeServer}; use crate::common::retry::retry; use crate::common::runtime::block_on; use crate::k8s::tools::agent_control::{ - start_agent_control_with_testdata_config, wait_until_agent_control_with_opamp_is_started, - CUSTOM_AGENT_TYPE_PATH, + CUSTOM_AGENT_TYPE_PATH, start_agent_control_with_testdata_config, + wait_until_agent_control_with_opamp_is_started, }; use crate::k8s::tools::instance_id; use crate::k8s::tools::k8s_api::check_helmrelease_spec_values; diff --git a/agent-control/tests/k8s/scenarios/attributes.rs b/agent-control/tests/k8s/scenarios/attributes.rs index ab3a79b717..90cfe4edad 100644 --- a/agent-control/tests/k8s/scenarios/attributes.rs +++ b/agent-control/tests/k8s/scenarios/attributes.rs @@ -6,7 +6,7 @@ use crate::common::opamp::ConfigResponse; use crate::common::retry::retry; use crate::common::{opamp::FakeServer, runtime::block_on}; use crate::k8s::tools::agent_control::{ - wait_until_agent_control_with_opamp_is_started, CUSTOM_AGENT_TYPE_PATH, + CUSTOM_AGENT_TYPE_PATH, wait_until_agent_control_with_opamp_is_started, }; use crate::k8s::tools::{ agent_control::start_agent_control_with_testdata_config, instance_id, k8s_env::K8sEnv, diff --git a/agent-control/tests/k8s/scenarios/cr_based_agents.rs b/agent-control/tests/k8s/scenarios/cr_based_agents.rs index 247dff9ae5..4736f2979c 100644 --- a/agent-control/tests/k8s/scenarios/cr_based_agents.rs +++ b/agent-control/tests/k8s/scenarios/cr_based_agents.rs @@ -1,6 +1,6 @@ use crate::k8s::tools::agent_control::BAR_CR_AGENT_TYPE_PATH; use crate::k8s::tools::k8s_api::check_config_map_exist; -use crate::k8s::tools::test_crd::{create_crd, delete_crd, Foo}; +use crate::k8s::tools::test_crd::{Foo, create_crd, delete_crd}; use crate::k8s::tools::{ agent_control::{ start_agent_control_with_testdata_config, wait_until_agent_control_with_opamp_is_started, diff --git a/agent-control/tests/k8s/scenarios/garbage_collector.rs b/agent-control/tests/k8s/scenarios/garbage_collector.rs index 3bc504a445..3baa07e620 100644 --- a/agent-control/tests/k8s/scenarios/garbage_collector.rs +++ b/agent-control/tests/k8s/scenarios/garbage_collector.rs @@ -8,11 +8,11 @@ use crate::{ common::{opamp::FakeServer, retry::retry, runtime::block_on}, k8s::tools::{ agent_control::{ - start_agent_control_with_testdata_config, - wait_until_agent_control_with_opamp_is_started, CUSTOM_AGENT_TYPE_PATH, + CUSTOM_AGENT_TYPE_PATH, start_agent_control_with_testdata_config, + wait_until_agent_control_with_opamp_is_started, }, k8s_env::K8sEnv, - test_crd::{create_foo_cr, Foo}, + test_crd::{Foo, create_foo_cr}, }, }; diff --git a/agent-control/tests/k8s/store.rs b/agent-control/tests/k8s/store.rs index 47e86d5e83..ec2e7b210f 100644 --- a/agent-control/tests/k8s/store.rs +++ b/agent-control/tests/k8s/store.rs @@ -13,18 +13,18 @@ use newrelic_agent_control::agent_control::defaults::default_capabilities; use newrelic_agent_control::k8s::client::SyncK8sClient; use newrelic_agent_control::k8s::labels::Labels; use newrelic_agent_control::k8s::store::{ - K8sStore, StoreKey, CM_NAME_LOCAL_DATA_PREFIX, CM_NAME_OPAMP_DATA_PREFIX, - STORE_KEY_INSTANCE_ID, STORE_KEY_OPAMP_DATA_CONFIG_HASH, + CM_NAME_LOCAL_DATA_PREFIX, CM_NAME_OPAMP_DATA_PREFIX, K8sStore, STORE_KEY_INSTANCE_ID, + STORE_KEY_OPAMP_DATA_CONFIG_HASH, StoreKey, }; -use newrelic_agent_control::opamp::hash_repository::k8s::HashRepositoryConfigMap; use newrelic_agent_control::opamp::hash_repository::HashRepository; +use newrelic_agent_control::opamp::hash_repository::k8s::HashRepositoryConfigMap; use newrelic_agent_control::opamp::instance_id::getter::{ InstanceIDGetter, InstanceIDWithIdentifiersGetter, }; use newrelic_agent_control::opamp::instance_id::k8s::getter::Identifiers; use newrelic_agent_control::opamp::remote_config::hash::Hash; use newrelic_agent_control::values::yaml_config_repository::{ - load_remote_fallback_local, YAMLConfigRepository, + YAMLConfigRepository, load_remote_fallback_local, }; use newrelic_agent_control::{ values::k8s::YAMLConfigRepositoryConfigMap, values::yaml_config::YAMLConfig, @@ -225,9 +225,11 @@ agents: not-infra-agent: agent_type: "newrelic/io.opentelemetry.collector:0.1.0" "#; - assert!(store_sa - .store(&from_str::(agents_cfg).unwrap()) - .is_ok()); + assert!( + store_sa + .store(&from_str::(agents_cfg).unwrap()) + .is_ok() + ); assert_eq!(store_sa.load().unwrap().agents.len(), 4); // After enabling remote we can load the "remote" config diff --git a/agent-control/tests/k8s/tools/agent_control.rs b/agent-control/tests/k8s/tools/agent_control.rs index 45a90832bb..891bf87874 100644 --- a/agent-control/tests/k8s/tools/agent_control.rs +++ b/agent-control/tests/k8s/tools/agent_control.rs @@ -1,14 +1,14 @@ use super::k8s_api::check_config_map_exist; use crate::common::{ - agent_control::{start_agent_control_with_custom_config, StartedAgentControl}, + agent_control::{StartedAgentControl, start_agent_control_with_custom_config}, retry::retry, runtime::block_on, }; use k8s_openapi::api::core::v1::ConfigMap; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use kube::{ - api::{Api, DeleteParams, PostParams}, Client, + api::{Api, DeleteParams, PostParams}, }; use newrelic_agent_control::agent_control::defaults::{ AGENT_CONTROL_CONFIG_FILENAME, DYNAMIC_AGENT_TYPE_FILENAME, @@ -16,7 +16,7 @@ use newrelic_agent_control::agent_control::defaults::{ use newrelic_agent_control::agent_control::{agent_id::AgentID, run::Environment}; use newrelic_agent_control::{ agent_control::run::BasePaths, - k8s::store::{K8sStore, CM_NAME_LOCAL_DATA_PREFIX, STORE_KEY_LOCAL_DATA_CONFIG}, + k8s::store::{CM_NAME_LOCAL_DATA_PREFIX, K8sStore, STORE_KEY_LOCAL_DATA_CONFIG}, }; use std::io::Read; use std::path::Path; diff --git a/agent-control/tests/k8s/tools/instance_id.rs b/agent-control/tests/k8s/tools/instance_id.rs index 6f608c4dc5..7fb0f1c9c1 100644 --- a/agent-control/tests/k8s/tools/instance_id.rs +++ b/agent-control/tests/k8s/tools/instance_id.rs @@ -4,11 +4,11 @@ use k8s_openapi::api::core::v1::ConfigMap; use kube::{Api, Client}; use newrelic_agent_control::agent_control::agent_id::AgentID; use newrelic_agent_control::k8s::store::{ - K8sStore, CM_NAME_OPAMP_DATA_PREFIX, STORE_KEY_INSTANCE_ID, + CM_NAME_OPAMP_DATA_PREFIX, K8sStore, STORE_KEY_INSTANCE_ID, }; +use newrelic_agent_control::opamp::instance_id::InstanceID; use newrelic_agent_control::opamp::instance_id::getter::DataStored; use newrelic_agent_control::opamp::instance_id::k8s::getter::Identifiers; -use newrelic_agent_control::opamp::instance_id::InstanceID; use std::time::Duration; pub fn get_instance_id(k8s_client: Client, namespace: &str, agent_id: &AgentID) -> InstanceID { diff --git a/agent-control/tests/k8s/tools/k8s_api.rs b/agent-control/tests/k8s/tools/k8s_api.rs index 84445b9f36..c1c36d19f3 100644 --- a/agent-control/tests/k8s/tools/k8s_api.rs +++ b/agent-control/tests/k8s/tools/k8s_api.rs @@ -1,6 +1,6 @@ use k8s_openapi::api::apps::v1::Deployment; use k8s_openapi::api::core::v1::ConfigMap; -use kube::{api::DynamicObject, core::GroupVersion, Api, Client}; +use kube::{Api, Client, api::DynamicObject, core::GroupVersion}; use std::time::Duration; use std::{error::Error, str::FromStr}; use tokio::time::sleep; diff --git a/agent-control/tests/k8s/tools/k8s_env.rs b/agent-control/tests/k8s/tools/k8s_env.rs index d8fb5cbddf..bbceca20ac 100644 --- a/agent-control/tests/k8s/tools/k8s_env.rs +++ b/agent-control/tests/k8s/tools/k8s_env.rs @@ -3,8 +3,8 @@ use crate::common::runtime::tokio_runtime; use super::test_crd::create_foo_crd; use k8s_openapi::api::core::v1::Namespace; use kube::{ - api::{DeleteParams, PostParams}, Api, Client, + api::{DeleteParams, PostParams}, }; use newrelic_agent_control::http::tls::install_rustls_default_crypto_provider; use std::{env, sync::Once}; @@ -28,7 +28,7 @@ impl K8sEnv { }); // Forces the client to use the dev kubeconfig file. - env::set_var("KUBECONFIG", KUBECONFIG_PATH); + unsafe { env::set_var("KUBECONFIG", KUBECONFIG_PATH) }; let client = Client::try_default().await.expect("fail to create client"); create_foo_crd(client.to_owned()).await; diff --git a/agent-control/tests/k8s/tools/test_crd.rs b/agent-control/tests/k8s/tools/test_crd.rs index 8e56af4060..be01f29310 100644 --- a/agent-control/tests/k8s/tools/test_crd.rs +++ b/agent-control/tests/k8s/tools/test_crd.rs @@ -1,9 +1,9 @@ use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition; use kube::{ + Api, Client, CustomResource, CustomResourceExt, api::{DynamicObject, ObjectMeta, Patch, PatchParams, PostParams, TypeMeta}, core::GroupVersion, runtime::reflector::Lookup, - Api, Client, CustomResource, CustomResourceExt, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/agent-control/tests/on_host/cli.rs b/agent-control/tests/on_host/cli.rs index 5ef62951b6..2bc2381ba8 100644 --- a/agent-control/tests/on_host/cli.rs +++ b/agent-control/tests/on_host/cli.rs @@ -235,7 +235,7 @@ fn runs_with_no_config_as_root() -> Result<(), Box> { // We set the environment variable with the `__` separator which will create the nested // configs appropriately. let env_var_name = "NR_AC_AGENTS__ROLLDICE__AGENT_TYPE"; - env::set_var(env_var_name, "namespace/com.newrelic.infrastructure:0.0.2"); + unsafe { env::set_var(env_var_name, "namespace/com.newrelic.infrastructure:0.0.2") }; // cmd_assert is not made for long running programs, so we kill it anyway after 1 second cmd.timeout(Duration::from_secs(1)); @@ -254,7 +254,7 @@ fn runs_with_no_config_as_root() -> Result<(), Box> { ); // Env cleanup - env::remove_var(env_var_name); + unsafe { env::remove_var(env_var_name) }; // No supervisor group, so we don't check for it. Ok(()) diff --git a/agent-control/tests/on_host/config_persister.rs b/agent-control/tests/on_host/config_persister.rs index a1771ecf22..39d0222882 100644 --- a/agent-control/tests/on_host/config_persister.rs +++ b/agent-control/tests/on_host/config_persister.rs @@ -37,9 +37,11 @@ fn test_configuration_persister_single_file() { .unwrap() .flatten(); - assert!(persister - .persist_agent_config(&agent_id.clone(), &filled_variables) - .is_ok()); + assert!( + persister + .persist_agent_config(&agent_id.clone(), &filled_variables) + .is_ok() + ); temp_path.push("auto-generated"); temp_path.push(agent_id); diff --git a/agent-control/tests/on_host/logging/file_logging.rs b/agent-control/tests/on_host/logging/file_logging.rs index 9fb8972d3a..5851cca2ee 100644 --- a/agent-control/tests/on_host/logging/file_logging.rs +++ b/agent-control/tests/on_host/logging/file_logging.rs @@ -48,11 +48,12 @@ fn default_log_level_no_root() { .collect(); for file in dir { - assert!(file - .path() - .to_str() - .unwrap() - .contains(log_path.to_str().unwrap())); + assert!( + file.path() + .to_str() + .unwrap() + .contains(log_path.to_str().unwrap()) + ); } } @@ -95,10 +96,11 @@ fn default_log_level_as_root() { .collect(); for file in dir { - assert!(file - .path() - .to_str() - .unwrap() - .contains(log_path.to_str().unwrap())); + assert!( + file.path() + .to_str() + .unwrap() + .contains(log_path.to_str().unwrap()) + ); } } diff --git a/agent-control/tests/on_host/scenarios/opamp.rs b/agent-control/tests/on_host/scenarios/opamp.rs index 1b6a9e62b4..560d639a76 100644 --- a/agent-control/tests/on_host/scenarios/opamp.rs +++ b/agent-control/tests/on_host/scenarios/opamp.rs @@ -288,7 +288,7 @@ fn onhost_opamp_sub_agent_local_effective_config_with_env_var() { // Having an env_var placeholder and the corresponding env_var set in order to // check that is not expanded on the effective config - env::set_var("my_env_var", "my-value"); + unsafe { env::set_var("my_env_var", "my-value") }; let values_config = format!( "fake_variable: ${{{}}}", @@ -325,7 +325,7 @@ fn onhost_opamp_sub_agent_local_effective_config_with_env_var() { } }); - env::remove_var("my_env_var"); + unsafe { env::remove_var("my_env_var") }; } /// The agent-control is configured with on agent with local configuration and a remote configuration was also set for the diff --git a/agent-control/tests/on_host/tools/config.rs b/agent-control/tests/on_host/tools/config.rs index 55b7b0e25a..cbcee6c221 100644 --- a/agent-control/tests/on_host/tools/config.rs +++ b/agent-control/tests/on_host/tools/config.rs @@ -1,10 +1,10 @@ -use std::fs::{create_dir_all, File}; +use std::fs::{File, create_dir_all}; use std::io::Write; use std::path::PathBuf; use newrelic_agent_control::agent_control::agent_id::AgentID; use newrelic_agent_control::agent_control::defaults::{ - default_capabilities, AGENT_CONTROL_CONFIG_FILENAME, SUB_AGENT_DIR, VALUES_DIR, VALUES_FILENAME, + AGENT_CONTROL_CONFIG_FILENAME, SUB_AGENT_DIR, VALUES_DIR, VALUES_FILENAME, default_capabilities, }; use newrelic_agent_control::agent_control::run::BasePaths; use newrelic_agent_control::values::file::YAMLConfigRepositoryFile; diff --git a/agent-control/tests/on_host/tools/instance_id.rs b/agent-control/tests/on_host/tools/instance_id.rs index 3477fd00ac..6f94fa0ac8 100644 --- a/agent-control/tests/on_host/tools/instance_id.rs +++ b/agent-control/tests/on_host/tools/instance_id.rs @@ -1,12 +1,12 @@ use crate::common::retry::retry; -use fs::directory_manager::DirectoryManagerFs; use fs::LocalFile; +use fs::directory_manager::DirectoryManagerFs; use newrelic_agent_control::agent_control::agent_id::AgentID; use newrelic_agent_control::agent_control::defaults::SUB_AGENT_DIR; use newrelic_agent_control::agent_control::run::BasePaths; +use newrelic_agent_control::opamp::instance_id::InstanceID; use newrelic_agent_control::opamp::instance_id::on_host::storer::Storer; use newrelic_agent_control::opamp::instance_id::storer::InstanceIDStorer; -use newrelic_agent_control::opamp::instance_id::InstanceID; use std::error::Error; use std::time::Duration; diff --git a/agent-control/tests/on_host/yaml_config_repository.rs b/agent-control/tests/on_host/yaml_config_repository.rs index 3e84c061e3..bb1ace998c 100644 --- a/agent-control/tests/on_host/yaml_config_repository.rs +++ b/agent-control/tests/on_host/yaml_config_repository.rs @@ -1,7 +1,7 @@ use ::fs::directory_manager::{DirectoryManager, DirectoryManagerFs}; use newrelic_agent_control::agent_control::agent_id::AgentID; use newrelic_agent_control::values::file::{ - concatenate_sub_agent_dir_path, YAMLConfigRepositoryFile, + YAMLConfigRepositoryFile, concatenate_sub_agent_dir_path, }; use newrelic_agent_control::values::yaml_config::YAMLConfig; use newrelic_agent_control::values::yaml_config_repository::YAMLConfigRepository; diff --git a/fs/src/directory_manager.rs b/fs/src/directory_manager.rs index 0e186cbc84..d7066479e4 100644 --- a/fs/src/directory_manager.rs +++ b/fs/src/directory_manager.rs @@ -1,5 +1,5 @@ -use super::utils::{validate_path, FsError}; -use std::fs::{remove_dir_all, DirBuilder, Permissions}; +use super::utils::{FsError, validate_path}; +use std::fs::{DirBuilder, Permissions, remove_dir_all}; #[cfg(target_family = "unix")] use std::os::unix::fs::DirBuilderExt; #[cfg(target_family = "unix")] @@ -24,7 +24,7 @@ pub trait DirectoryManager { #[cfg(target_family = "unix")] /// create will create a folder fn create(&self, path: &Path, permissions: Permissions) - -> Result<(), DirectoryManagementError>; + -> Result<(), DirectoryManagementError>; /// Delete the folder and its contents. If the folder does not exist it /// will not return an error. diff --git a/fs/src/writer_file.rs b/fs/src/writer_file.rs index 83584ef280..41db14cceb 100644 --- a/fs/src/writer_file.rs +++ b/fs/src/writer_file.rs @@ -1,6 +1,6 @@ -use super::directory_manager::DirectoryManagementError; -use super::utils::{validate_path, FsError}; use super::LocalFile; +use super::directory_manager::DirectoryManagementError; +use super::utils::{FsError, validate_path}; use std::fs::Permissions; use std::io::Write; #[cfg(target_family = "unix")] diff --git a/resource-detection/src/cloud/aws/detector.rs b/resource-detection/src/cloud/aws/detector.rs index c4adb97be7..33dd18bb3c 100644 --- a/resource-detection/src/cloud/aws/detector.rs +++ b/resource-detection/src/cloud/aws/detector.rs @@ -3,7 +3,7 @@ use super::metadata::AWSMetadata; use crate::cloud::aws::http_client::AWSHttpClient; use crate::cloud::http_client::{HttpClient, HttpClientError}; -use crate::{cloud::AWS_INSTANCE_ID, DetectError, Detector, Key, Resource, Value}; +use crate::{DetectError, Detector, Key, Resource, Value, cloud::AWS_INSTANCE_ID}; use core::str; use std::time::Duration; use thiserror::Error; diff --git a/resource-detection/src/cloud/aws/http_client.rs b/resource-detection/src/cloud/aws/http_client.rs index 8a5e7f80be..6a3695a787 100644 --- a/resource-detection/src/cloud/aws/http_client.rs +++ b/resource-detection/src/cloud/aws/http_client.rs @@ -89,8 +89,8 @@ where #[cfg(test)] mod tests { use crate::cloud::aws::http_client::AWSHttpClient; - use crate::cloud::http_client::tests::MockHttpClient; use crate::cloud::http_client::HttpClientError; + use crate::cloud::http_client::tests::MockHttpClient; use http::{Response, StatusCode}; use mockall::Sequence; use std::time::Duration; diff --git a/resource-detection/src/cloud/azure/detector.rs b/resource-detection/src/cloud/azure/detector.rs index c5149d753b..cb91fe481c 100644 --- a/resource-detection/src/cloud/azure/detector.rs +++ b/resource-detection/src/cloud/azure/detector.rs @@ -1,7 +1,7 @@ //! Azure EC2 instance id detector implementation use super::metadata::AzureMetadata; use crate::cloud::http_client::{HttpClient, HttpClientError}; -use crate::{cloud::AZURE_INSTANCE_ID, DetectError, Detector, Key, Resource, Value}; +use crate::{DetectError, Detector, Key, Resource, Value, cloud::AZURE_INSTANCE_ID}; use http::HeaderMap; use thiserror::Error; use tracing::instrument; diff --git a/resource-detection/src/cloud/cloud_id/detector.rs b/resource-detection/src/cloud/cloud_id/detector.rs index 0f2ee40fba..2e1909930f 100644 --- a/resource-detection/src/cloud/cloud_id/detector.rs +++ b/resource-detection/src/cloud/cloud_id/detector.rs @@ -8,7 +8,7 @@ use crate::cloud::{ AZURE_INSTANCE_ID, CLOUD_INSTANCE_ID, CLOUD_TYPE, CLOUD_TYPE_AWS, CLOUD_TYPE_AZURE, CLOUD_TYPE_GCP, CLOUD_TYPE_NO, GCP_INSTANCE_ID, }; -use crate::{cloud::AWS_INSTANCE_ID, DetectError, Detector, Key, Resource, Value}; +use crate::{DetectError, Detector, Key, Resource, Value, cloud::AWS_INSTANCE_ID}; use thiserror::Error; use tracing::warn; @@ -121,11 +121,11 @@ where #[cfg(test)] mod tests { use super::*; + use crate::cloud::CLOUD_TYPE_GCP; use crate::cloud::aws::detector::AWSDetectorError; use crate::cloud::azure::detector::AzureDetectorError; use crate::cloud::gcp::detector::GCPDetectorError; use crate::cloud::http_client::HttpClientError; - use crate::cloud::CLOUD_TYPE_GCP; use mockall::mock; mock! { diff --git a/resource-detection/src/cloud/gcp/detector.rs b/resource-detection/src/cloud/gcp/detector.rs index 0828fe94e9..27ba6ec09c 100644 --- a/resource-detection/src/cloud/gcp/detector.rs +++ b/resource-detection/src/cloud/gcp/detector.rs @@ -1,7 +1,7 @@ //! GCP instance id detector implementation use super::metadata::GCPMetadata; -use crate::cloud::http_client::{HttpClient, HttpClientError}; use crate::cloud::GCP_INSTANCE_ID; +use crate::cloud::http_client::{HttpClient, HttpClientError}; use crate::{DetectError, Detector, Key, Resource, Value}; use http::HeaderMap; use thiserror::Error; diff --git a/resource-detection/src/system/detector.rs b/resource-detection/src/system/detector.rs index 48d21975e9..b17860078f 100644 --- a/resource-detection/src/system/detector.rs +++ b/resource-detection/src/system/detector.rs @@ -5,8 +5,8 @@ use tracing::{error, instrument}; use crate::{DetectError, Detector, Key, Resource, Value}; use super::{ - hostname::HostnameGetter, identifier_machine_id_unix::IdentifierProviderMachineId, - HOSTNAME_KEY, MACHINE_ID_KEY, + HOSTNAME_KEY, MACHINE_ID_KEY, hostname::HostnameGetter, + identifier_machine_id_unix::IdentifierProviderMachineId, }; /// An enumeration of potential errors related to the system detector. diff --git a/resource-detection/src/system/identifier_machine_id_unix.rs b/resource-detection/src/system/identifier_machine_id_unix.rs index 638787621f..e384656a1f 100644 --- a/resource-detection/src/system/identifier_machine_id_unix.rs +++ b/resource-detection/src/system/identifier_machine_id_unix.rs @@ -1,8 +1,8 @@ use std::path::{Path, PathBuf}; use fs::{ - file_reader::{FileReader, FileReaderError}, LocalFile, + file_reader::{FileReader, FileReaderError}, }; use super::detector::SystemDetectorError; diff --git a/wrapper_with_default/src/lib.rs b/wrapper_with_default/src/lib.rs index 4ad236dae2..14ae7d0f40 100644 --- a/wrapper_with_default/src/lib.rs +++ b/wrapper_with_default/src/lib.rs @@ -1,6 +1,6 @@ use proc_macro::TokenStream; use quote::quote; -use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput, Fields, Path}; +use syn::{Data, DeriveInput, Fields, Path, parse_macro_input, spanned::Spanned}; /// Procedural derive macro to make easier the implementation of wrappers setting a default value. /// It automatically generates the [Default] implementation with the provided `wrapper_default_value` (which should