diff --git a/proxy_agent/src/acl/linux_acl.rs b/proxy_agent/src/acl/linux_acl.rs index d49440f3..d588c3d9 100644 --- a/proxy_agent/src/acl/linux_acl.rs +++ b/proxy_agent/src/acl/linux_acl.rs @@ -10,19 +10,16 @@ use std::path::PathBuf; pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { let dir_str = misc_helpers::path_to_string(&dir_to_acl); logger::write(format!( - "acl_directory: start to set root-only permission to folder {}.", - dir_str + "acl_directory: start to set root-only permission to folder {dir_str}." )); match chown(&dir_to_acl, Some(Uid::from_raw(0)), Some(Gid::from_raw(0))) { Ok(_) => logger::write(format!( - "acl_directory: successfully set root-only permission to folder {}.", - dir_str + "acl_directory: successfully set root-only permission to folder {dir_str}." )), Err(e) => { logger::write(format!( - "acl_directory: failed to set root-only permission to folder {}. Error: {:?}", - dir_str, e + "acl_directory: failed to set root-only permission to folder {dir_str}. Error: {e:?}" )); } } @@ -31,13 +28,11 @@ pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { let permissions = fs::Permissions::from_mode(0o700); match fs::set_permissions(dir_to_acl, permissions) { Ok(_) => logger::write(format!( - "acl_directory: successfully set root-only permission to folder {}.", - dir_str + "acl_directory: successfully set root-only permission to folder {dir_str}." )), Err(e) => { logger::write(format!( - "acl_directory: failed to set root-only permission to folder {}. Error: {:?}", - dir_str, e + "acl_directory: failed to set root-only permission to folder {dir_str}. Error: {e:?}" )); } } diff --git a/proxy_agent/src/acl/windows_acl.rs b/proxy_agent/src/acl/windows_acl.rs index 532a2893..eb63a896 100644 --- a/proxy_agent/src/acl/windows_acl.rs +++ b/proxy_agent/src/acl/windows_acl.rs @@ -31,16 +31,14 @@ pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { .map_err(|e| Error::Acl(AclErrorType::Sid(BUILDIN_ADMIN_SID.to_string()), e))?; logger::write(format!( - "acl_directory: removing all the remaining access rules for folder {}.", - dir_str + "acl_directory: removing all the remaining access rules for folder {dir_str}." )); match acl.all() { Ok(entries) => { logger::write(format!( - "acl_directory: get '{}' access rules for folder {}.", - entries.len(), - dir_str + "acl_directory: get '{len}' access rules for folder {dir_str}.", + len = entries.len() )); for entry in entries { match entry.sid { @@ -55,12 +53,11 @@ pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { None, // remove all, including inherited permissions ) { Ok(r) => { - logger::write(format!("acl_directory: removed '{}' entry.", r)); + logger::write(format!("acl_directory: removed '{r}' entry.")); } Err(e) => { logger::write_warning(format!( - "acl_directory: remove_entry failed with error '{}' entry.", - e + "acl_directory: remove_entry failed with error '{e}' entry.", )); } } @@ -77,8 +74,7 @@ pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { } logger::write(format!( - "acl_directory: Adding new access rules for the target directory {}.", - dir_str + "acl_directory: Adding new access rules for the target directory {dir_str}." )); let flags = (CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE) as u8; let mask = FULL_CONTROL; @@ -90,8 +86,7 @@ pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { ) { Ok(r) => { logger::write(format!( - "acl_directory: Adding new access rules for sid {} with result {}.", - LOCAL_SYSTEM_SID, r + "acl_directory: Adding new access rules for sid {LOCAL_SYSTEM_SID} with result {r}.", )); } Err(e) => { @@ -109,8 +104,7 @@ pub fn acl_directory(dir_to_acl: PathBuf) -> Result<()> { ) { Ok(r) => { logger::write(format!( - "acl_directory: Adding new access rules for sid {} with result {}.", - BUILDIN_ADMIN_SID, r + "acl_directory: Adding new access rules for sid {BUILDIN_ADMIN_SID} with result {r}." )); } Err(e) => { diff --git a/proxy_agent/src/common/helpers.rs b/proxy_agent/src/common/helpers.rs index c945e9ea..112c957a 100644 --- a/proxy_agent/src/common/helpers.rs +++ b/proxy_agent/src/common/helpers.rs @@ -18,7 +18,7 @@ static CURRENT_SYS_INFO: Lazy<(u64, usize)> = Lazy::new(|| { let ram_in_mb = match windows::get_memory_in_mb() { Ok(ram) => ram, Err(e) => { - logger::write_error(format!("get_memory_in_mb failed: {}", e)); + logger::write_error(format!("get_memory_in_mb failed: {e}")); 0 } }; diff --git a/proxy_agent/src/common/hyper_client.rs b/proxy_agent/src/common/hyper_client.rs index 9eea2cbc..bc52c375 100644 --- a/proxy_agent/src/common/hyper_client.rs +++ b/proxy_agent/src/common/hyper_client.rs @@ -166,8 +166,7 @@ where Err(e) => Err(Error::Hyper( HyperErrorType::Deserialize( format!( - "Failed to xml deserialize response body with content_type {} from: {} with error {}", - content_type, body_string, e + "Failed to xml deserialize response body with content_type {content_type} from: {body_string} with error {e}" ) ), )), @@ -178,8 +177,7 @@ where Err(e) => Err(Error::Hyper( HyperErrorType::Deserialize( format!( - "Failed to json deserialize response body with {} from: {} with error {}", - content_type, body_string, e + "Failed to json deserialize response body with {content_type} from: {body_string} with error {e}" ) ), )), @@ -246,8 +244,7 @@ pub fn build_request( match request_builder.body(boxed_body) { Ok(r) => Ok(r), Err(e) => Err(Error::Hyper(HyperErrorType::RequestBuilder(format!( - "Failed to build request body: {}", - e + "Failed to build request body: {e}" )))), } } @@ -268,7 +265,7 @@ where let mut sender = build_http_sender(host, port, log_fun).await?; sender.send_request(request).await.map_err(|e| { Error::Hyper(HyperErrorType::Custom( - format!("Failed to send request to {}", full_url), + format!("Failed to send request to {full_url}"), e, )) }) @@ -285,12 +282,12 @@ where B::Error: Into>, F: FnMut(String) + Send + 'static, { - let addr = format!("{}:{}", host, port); + let addr = format!("{host}:{port}"); let stream = match TcpStream::connect(addr.to_string()).await { Ok(tcp_stream) => tcp_stream, Err(e) => { return Err(Error::Io( - format!("Failed to open TCP connection to {}", addr), + format!("Failed to open TCP connection to {addr}"), e, )) } @@ -301,13 +298,13 @@ where .await .map_err(|e| { Error::Hyper(HyperErrorType::Custom( - format!("Failed to establish connection to {}", addr), + format!("Failed to establish connection to {addr}"), e, )) })?; tokio::task::spawn(async move { if let Err(err) = conn.await { - log_fun(format!("Connection failed: {:?}", err)); + log_fun(format!("Connection failed: {err:?}")); } }); @@ -428,7 +425,7 @@ fn get_path_and_canonicalized_parameters(url: &Uri) -> (String, String) { pairs.insert( // add the query parameter value for sorting, // just in case of duplicate keys by value lexicographically in ascending order. - format!("{}{}", key, value), + format!("{key}{value}"), (key.to_lowercase(), value.to_string()), ); } diff --git a/proxy_agent/src/common/logger.rs b/proxy_agent/src/common/logger.rs index 87432231..a3e06819 100644 --- a/proxy_agent/src/common/logger.rs +++ b/proxy_agent/src/common/logger.rs @@ -64,11 +64,11 @@ pub fn write_serial_console_log(message: String) { { Ok(mut serial_console) => { if serial_console.write_all(message.as_bytes()).is_err() { - eprintln!("Failed to write to serial console: {}", message); + eprintln!("Failed to write to serial console: {message}"); } } Err(e) => { - eprintln!("Failed to open serial console: {}", e); + eprintln!("Failed to open serial console: {e}"); } } } diff --git a/proxy_agent/src/host_clients/wire_server_client.rs b/proxy_agent/src/host_clients/wire_server_client.rs index 252b1a7f..ced98348 100644 --- a/proxy_agent/src/host_clients/wire_server_client.rs +++ b/proxy_agent/src/host_clients/wire_server_client.rs @@ -82,7 +82,7 @@ impl WireServerClient { Err(e) => { return Err(Error::WireServer( WireServerErrorType::Telemetry, - format!("Failed to send request {}", e), + format!("Failed to send request {e}"), )) } }; @@ -91,10 +91,7 @@ impl WireServerClient { if !status.is_success() { return Err(Error::WireServer( WireServerErrorType::Telemetry, - format!( - "Failed to get response from {}, status code: {}", - url, status - ), + format!("Failed to get response from {url}, status code: {status}"), )); } diff --git a/proxy_agent/src/key_keeper.rs b/proxy_agent/src/key_keeper.rs index 11d939df..81e5b177 100644 --- a/proxy_agent/src/key_keeper.rs +++ b/proxy_agent/src/key_keeper.rs @@ -175,7 +175,7 @@ impl KeyKeeper { let notify = match self.key_keeper_shared_state.get_notify().await { Ok(notify) => notify, Err(e) => { - logger::write_error(format!("Failed to get notify: {}", e)); + logger::write_error(format!("Failed to get notify: {e}")); return; } }; @@ -187,8 +187,7 @@ impl KeyKeeper { .await { logger::write_error(format!( - "Failed to set key_keeper module state to 'Running' with error: {} ", - e + "Failed to set key_keeper module state to 'Running' with error: {e} " )); } @@ -205,8 +204,7 @@ impl KeyKeeper { Ok(state) => state, Err(e) => { logger::write_warning(format!( - "Failed to get current secure channel state: {}", - e + "Failed to get current secure channel state: {e}" )); UNKNOWN_STATE.to_string() } @@ -229,10 +227,10 @@ impl KeyKeeper { // this is to handle quicker response to the secure channel state change during VM provisioning. _ = notify.notified() => { if current_state == DISABLE_STATE || current_state == UNKNOWN_STATE { - logger::write_warning(format!("poll_secure_channel_status task notified and secure channel state is '{}', reset states and start poll status now.", current_state)); + logger::write_warning(format!("poll_secure_channel_status task notified and secure channel state is '{current_state}', reset states and start poll status now.")); provision::key_latch_ready_state_reset(self.provision_shared_state.clone()).await; if let Err(e) = self.key_keeper_shared_state.update_current_secure_channel_state(UNKNOWN_STATE.to_string()).await{ - logger::write_warning(format!("Failed to update secure channel state to 'Unknown': {}", e)); + logger::write_warning(format!("Failed to update secure channel state to 'Unknown': {e}")); } if start.elapsed().as_millis() > PROVISION_TIMEUP_IN_MILLISECONDS { @@ -253,7 +251,7 @@ impl KeyKeeper { let continue_sleep = sleep.as_millis() - slept_time_in_millisec; if continue_sleep > 0 { let continue_sleep = Duration::from_millis(continue_sleep as u64); - let message = format!("poll_secure_channel_status task notified but secure channel state is '{}', continue with sleep wait for {:?}.", current_state, continue_sleep); + let message = format!("poll_secure_channel_status task notified but secure channel state is '{current_state}', continue with sleep wait for {continue_sleep:?}."); logger::write_warning(message); tokio::time::sleep(continue_sleep).await; } @@ -292,12 +290,12 @@ impl KeyKeeper { let status = match key::get_status(&self.base_url).await { Ok(s) => s, Err(e) => { - self.update_status_message(format!("Failed to get key status - {}", e), true) + self.update_status_message(format!("Failed to get key status - {e}"), true) .await; continue; } }; - self.update_status_message(format!("Got key status successfully: {}.", status), true) + self.update_status_message(format!("Got key status successfully: {status}."), true) .await; let mut access_control_rules_changed = false; @@ -313,21 +311,20 @@ impl KeyKeeper { Ok((updated, old_wire_server_rule_id)) => { if updated { logger::write_warning(format!( - "Wireserver rule id changed from '{}' to '{}'.", - old_wire_server_rule_id, wireserver_rule_id + "Wireserver rule id changed from '{old_wire_server_rule_id}' to '{wireserver_rule_id}'." )); if let Err(e) = self .key_keeper_shared_state .set_wireserver_rules(status.get_wireserver_rules()) .await { - logger::write_error(format!("Failed to set wireserver rules: {}", e)); + logger::write_error(format!("Failed to set wireserver rules: {e}")); } access_control_rules_changed = true; } } Err(e) => { - logger::write_warning(format!("Failed to update wireserver rule id: {}", e)); + logger::write_warning(format!("Failed to update wireserver rule id: {e}")); } } @@ -339,21 +336,20 @@ impl KeyKeeper { Ok((updated, old_imds_rule_id)) => { if updated { logger::write_warning(format!( - "IMDS rule id changed from '{}' to '{}'.", - old_imds_rule_id, imds_rule_id + "IMDS rule id changed from '{old_imds_rule_id}' to '{imds_rule_id}'." )); if let Err(e) = self .key_keeper_shared_state .set_imds_rules(status.get_imds_rules()) .await { - logger::write_error(format!("Failed to set imds rules: {}", e)); + logger::write_error(format!("Failed to set imds rules: {e}")); } access_control_rules_changed = true; } } Err(e) => { - logger::write_warning(format!("Failed to update imds rule id: {}", e)); + logger::write_warning(format!("Failed to update imds rule id: {e}")); } } @@ -365,21 +361,20 @@ impl KeyKeeper { Ok((updated, old_hostga_rule_id)) => { if updated { logger::write_warning(format!( - "HostGA rule id changed from '{}' to '{}'.", - old_hostga_rule_id, hostga_rule_id + "HostGA rule id changed from '{old_hostga_rule_id}' to '{hostga_rule_id}'." )); if let Err(e) = self .key_keeper_shared_state .set_hostga_rules(status.get_hostga_rules()) .await { - logger::write_error(format!("Failed to set HostGA rules: {}", e)); + logger::write_error(format!("Failed to set HostGA rules: {e}")); } access_control_rules_changed = true; } } Err(e) => { - logger::write_warning(format!("Failed to update HostGA rule id: {}", e)); + logger::write_warning(format!("Failed to update HostGA rule id: {e}")); } } @@ -416,7 +411,7 @@ impl KeyKeeper { if let Err(e) = self.key_keeper_shared_state.update_key(key.clone()).await { - logger::write_warning(format!("Failed to update key: {}", e)); + logger::write_warning(format!("Failed to update key: {e}")); } let message = helpers::write_startup_event( @@ -440,7 +435,7 @@ impl KeyKeeper { Err(e) => { event_logger::write_event( LoggerLevel::Info, - format!("Failed to fetch local key details with error: {:?}. Will try acquire the key details from Server.", e), + format!("Failed to fetch local key details with error: {e:?}. Will try acquire the key details from Server."), "poll_secure_channel_status", "key_keeper", logger::AGENT_LOGGER_KEY, @@ -458,7 +453,7 @@ impl KeyKeeper { Ok(k) => k, Err(e) => { self.update_status_message( - format!("Failed to acquire key details: {:?}", e), + format!("Failed to acquire key details: {e:?}"), true, ) .await; @@ -471,11 +466,11 @@ impl KeyKeeper { match Self::store_key(&self.key_dir, &key) { Ok(()) => { logger::write_information(format!( - "Successfully acquired the key '{}' details from server and saved locally.", guid)); + "Successfully acquired the key '{guid}' details from server and saved locally.")); } Err(e) => { self.update_status_message( - format!("Failed to save key details to file: {:?}", e), + format!("Failed to save key details to file: {e:?}"), true, ) .await; @@ -487,8 +482,7 @@ impl KeyKeeper { if let Err(e) = Self::check_key(&self.key_dir, &key) { self.update_status_message( format!( - "Failed to check the key '{}' details saved locally: {:?}.", - guid, e + "Failed to check the key '{guid}' details saved locally: {e:?}." ), true, ) @@ -501,7 +495,7 @@ impl KeyKeeper { if let Err(e) = self.key_keeper_shared_state.update_key(key.clone()).await { - logger::write_warning(format!("Failed to update key: {}", e)); + logger::write_warning(format!("Failed to update key: {e}")); } let message = helpers::write_startup_event( @@ -521,7 +515,7 @@ impl KeyKeeper { .await; } Err(e) => { - logger::write_warning(format!("Failed to attest the key: {:?}", e)); + logger::write_warning(format!("Failed to attest the key: {e:?}")); continue; } } @@ -567,7 +561,7 @@ impl KeyKeeper { // clear key in memory for disabled state if let Err(e) = self.key_keeper_shared_state.clear_key().await { - logger::write_warning(format!("Failed to clear key: {}", e)); + logger::write_warning(format!("Failed to clear key: {e}")); } provision::key_latched( self.cancellation_token.clone(), @@ -581,7 +575,7 @@ impl KeyKeeper { } } Err(e) => { - logger::write_warning(format!("Failed to update secure channel state: {}", e)); + logger::write_warning(format!("Failed to update secure channel state: {e}")); } } } @@ -600,7 +594,7 @@ impl KeyKeeper { } } Err(e) => { - logger::write_warning(format!("Failed to set module status message: {}", e)); + logger::write_warning(format!("Failed to set module status message: {e}")); } } } @@ -616,8 +610,7 @@ impl KeyKeeper { &key_file, serde_json::to_string(&key).map_err(|e| { Error::Key(KeyErrorType::StoreLocalKey(format!( - "serialize key error: {:?} ", - e + "serialize key error: {e:?} " ))) })?, ) @@ -690,8 +683,7 @@ impl KeyKeeper { serde_json::from_str::(&key_data).map_err(|e| { Error::Key(crate::common::error::KeyErrorType::FetchLocalKey(format!( - "Parse key data with error: {}", - e + "Parse key data with error: {e}" ))) }) } @@ -704,8 +696,7 @@ impl KeyKeeper { #[cfg(windows)] { logger::write_information(format!( - "Failed to fetch .encrypted file with error: {}. Fallback to fetch .key file for windows platform.", - _e + "Failed to fetch .encrypted file with error: {_e}. Fallback to fetch .key file for windows platform." )); } @@ -760,8 +751,7 @@ impl KeyKeeper { .await { logger::write_warning(format!( - "Failed to set key_keeper module state to 'Stopped' with error: {} ", - e + "Failed to set key_keeper module state to 'Stopped' with error: {e} " )); } } diff --git a/proxy_agent/src/key_keeper/key.rs b/proxy_agent/src/key_keeper/key.rs index 9adcd118..bf8ba5ac 100644 --- a/proxy_agent/src/key_keeper/key.rs +++ b/proxy_agent/src/key_keeper/key.rs @@ -419,8 +419,7 @@ impl KeyStatus { && key_delivery_method != constants::KEY_DELIVERY_METHOD_VTPM { validate_message.push_str(&format!( - "keyDeliveryMethod '{}' is invalid; ", - key_delivery_method + "keyDeliveryMethod '{key_delivery_method}' is invalid; " )); } @@ -444,7 +443,7 @@ impl KeyStatus { && state != super::MUST_SIG_WIRESERVER_IMDS { validate_message - .push_str(&format!("secureChannelState '{}' is invalid; ", state)); + .push_str(&format!("secureChannelState '{state}' is invalid; ")); validate_result = false; } } @@ -528,7 +527,7 @@ impl KeyStatus { None => return super::DISABLE_STATE.to_string(), } - format!("{} - {} - {}", wireserver, imds, hostga) + format!("{wireserver} - {imds} - {hostga}") } else { super::DISABLE_STATE.to_string() } @@ -720,7 +719,7 @@ const KEY_URL: &str = "/secure-channel/key"; pub async fn get_status(base_url: &Uri) -> Result { let (host, port) = hyper_client::host_port_from_uri(base_url)?; - let url = format!("http://{}:{}{}", host, port, STATUS_URL); + let url = format!("http://{host}:{port}{STATUS_URL}"); let url: Uri = url.parse().map_err(|e| { Error::Key(KeyErrorType::ParseKeyUrl( base_url.to_string(), @@ -739,7 +738,7 @@ pub async fn get_status(base_url: &Uri) -> Result { pub async fn acquire_key(base_url: &Uri) -> Result { let (host, port) = hyper_client::host_port_from_uri(base_url)?; - let url = format!("http://{}:{}{}", host, port, KEY_URL); + let url = format!("http://{host}:{port}{KEY_URL}"); let url: Uri = url.parse().map_err(|e| { Error::Key(KeyErrorType::ParseKeyUrl( base_url.to_string(), diff --git a/proxy_agent/src/main.rs b/proxy_agent/src/main.rs index 63ae8657..74940119 100644 --- a/proxy_agent/src/main.rs +++ b/proxy_agent/src/main.rs @@ -97,7 +97,7 @@ async fn main() { match service_dispatcher::start(constants::PROXY_AGENT_SERVICE_NAME, ffi_service_main) { Ok(_) => {} Err(e) => { - logger::write_error(format!("Error in starting the service dispatcher: {}", e)); + logger::write_error(format!("Error in starting the service dispatcher: {e}")); } } } @@ -121,7 +121,7 @@ fn proxy_agent_windows_service_main(_args: Vec) { .expect("You must provide the Tokio runtime handle before this function is called"); handle.block_on(async { if let Err(e) = windows::run_service().await { - logger::write_error(format!("Error in running the service: {}", e)); + logger::write_error(format!("Error in running the service: {e}")); } }); } diff --git a/proxy_agent/src/provision.rs b/proxy_agent/src/provision.rs index 806fa0ad..bec9c783 100644 --- a/proxy_agent/src/provision.rs +++ b/proxy_agent/src/provision.rs @@ -596,10 +596,7 @@ pub mod provision_query { let state = match self.get_current_provision_status(first_loop).await { Ok(state) => state, Err(e) => { - println!( - "Failed to query the current provision state with error: {}.", - e - ); + println!("Failed to query the current provision state with error: {e}."); ProvisionState::new(false, String::new()) } }; diff --git a/proxy_agent/src/proxy.rs b/proxy_agent/src/proxy.rs index 31de00a9..19be4655 100644 --- a/proxy_agent/src/proxy.rs +++ b/proxy_agent/src/proxy.rs @@ -91,7 +91,7 @@ async fn get_user( } else { let user = User::from_logon_id(logon_id)?; if let Err(e) = proxy_server_shared_state.add_user(user.clone()).await { - println!("Failed to add user: {} to cache", e); + println!("Failed to add user: {e} to cache"); } Ok(user) } @@ -166,7 +166,7 @@ impl Process { #[cfg(windows)] { let handler = windows::get_process_handler(pid).unwrap_or_else(|e| { - println!("Failed to get process handler: {}", e); + println!("Failed to get process handler: {e}"); 0 }); let base_info = windows::query_basic_process_info(handler); @@ -178,7 +178,7 @@ impl Process { Err(e) => { process_full_path = PathBuf::default(); cmd = UNDEFINED.to_string(); - println!("Failed to query basic process info: {}", e); + println!("Failed to query basic process info: {e}"); } } } diff --git a/proxy_agent/src/proxy/authorization_rules.rs b/proxy_agent/src/proxy/authorization_rules.rs index 6d4805b6..27ef84fa 100644 --- a/proxy_agent/src/proxy/authorization_rules.rs +++ b/proxy_agent/src/proxy/authorization_rules.rs @@ -52,7 +52,7 @@ impl std::str::FromStr for AuthorizationMode { "disabled" => Ok(AuthorizationMode::Disabled), "audit" => Ok(AuthorizationMode::Audit), "enforce" => Ok(AuthorizationMode::Enforce), - _ => Err(format!("Invalid AuthorizationMode: {}", s)), + _ => Err(format!("Invalid AuthorizationMode: {s}")), } } } @@ -84,7 +84,7 @@ impl ComputedAuthorizationItem { Ok(mode) => mode, Err(err) => { // This should not happen, log the error and set the mode to disabled - logger::write_error(format!("Failed to parse authorization mode: {}", err)); + logger::write_error(format!("Failed to parse authorization mode: {err}")); AuthorizationMode::Disabled } }; @@ -184,7 +184,7 @@ impl ComputedAuthorizationItem { any_privilege_matched = true; logger.write( LoggerLevel::Trace, - format!("Request matched privilege '{}'.", privilege_name), + format!("Request matched privilege '{privilege_name}'."), ); if let Some(assignments) = self.privilegeAssignments.get(privilege_name) { @@ -195,8 +195,7 @@ impl ComputedAuthorizationItem { logger.write( LoggerLevel::Trace, format!( - "Request matched privilege '{}' and identity '{}'.", - privilege_name, identity_name + "Request matched privilege '{privilege_name}' and identity '{identity_name}'." ), ); return true; @@ -206,23 +205,21 @@ impl ComputedAuthorizationItem { logger.write( LoggerLevel::Trace, format!( - "Request matched privilege '{}' but no identity matched.", - privilege_name + "Request matched privilege '{privilege_name}' but no identity matched." ), ); } else { logger.write( LoggerLevel::Trace, format!( - "Request matched privilege '{}' but no identity assigned.", - privilege_name + "Request matched privilege '{privilege_name}' but no identity assigned." ), ); } } else { logger.write( LoggerLevel::Trace, - format!("Request does not match privilege '{}'.", privilege_name), + format!("Request does not match privilege '{privilege_name}'."), ); } } diff --git a/proxy_agent/src/proxy/proxy_authorizer.rs b/proxy_agent/src/proxy/proxy_authorizer.rs index 8e113616..cbe575f7 100644 --- a/proxy_agent/src/proxy/proxy_authorizer.rs +++ b/proxy_agent/src/proxy/proxy_authorizer.rs @@ -66,7 +66,7 @@ impl Authorizer for WireServer { } else { if rules.mode == AuthorizationMode::Audit { logger.write( - LoggerLevel::Info, format!("WireServer request {} denied in audit mode, continue forward the request", request_url)); + LoggerLevel::Info, format!("WireServer request {request_url} denied in audit mode, continue forward the request")); return AuthorizeResult::OkWithAudit; } return AuthorizeResult::Forbidden; @@ -104,8 +104,7 @@ impl Authorizer for Imds { logger.write( LoggerLevel::Info, format!( - "IMDS request {} denied in audit mode, continue forward the request", - request_url + "IMDS request {request_url} denied in audit mode, continue forward the request" ), ); return AuthorizeResult::OkWithAudit; @@ -143,7 +142,7 @@ impl Authorizer for GAPlugin { } else { if rules.mode == AuthorizationMode::Audit { logger.write( - LoggerLevel::Info, format!("HostGAPlugin request {} denied in audit mode, continue forward the request", request_url)); + LoggerLevel::Info, format!("HostGAPlugin request {request_url} denied in audit mode, continue forward the request")); return AuthorizeResult::OkWithAudit; } return AuthorizeResult::Forbidden; diff --git a/proxy_agent/src/proxy/proxy_connection.rs b/proxy_agent/src/proxy/proxy_connection.rs index e037bb8b..806057cf 100644 --- a/proxy_agent/src/proxy/proxy_connection.rs +++ b/proxy_agent/src/proxy/proxy_connection.rs @@ -39,7 +39,7 @@ impl Client { let full_url = req.uri().to_string(); self.sender.send_request(req).await.map_err(|e| { Error::Hyper(HyperErrorType::Custom( - format!("Failed to send request to {}", full_url), + format!("Failed to send request to {full_url}"), e, )) }) @@ -91,7 +91,7 @@ impl TcpConnectionContext { Err(e) => { logger.write( LoggerLevel::Error, - format!("Failed to get claims from audit entry: {}", e), + format!("Failed to get claims from audit entry: {e}"), ); // return None for claims None @@ -154,22 +154,20 @@ impl TcpConnectionContext { logger.write( LoggerLevel::Trace, format!( - "Found audit entry with client_source_port '{}' successfully", - client_source_port + "Found audit entry with client_source_port '{client_source_port}' successfully" ), ); match redirector::remove_audit(client_source_port, redirector_shared_state).await { Ok(_) => logger.write( LoggerLevel::Trace, format!( - "Removed audit entry with client_source_port '{}' successfully", - client_source_port + "Removed audit entry with client_source_port '{client_source_port}' successfully" ), ), Err(e) => { logger.write( LoggerLevel::Warn, - format!("Failed to remove audit entry: {}", e), + format!("Failed to remove audit entry: {e}"), ); } } @@ -178,8 +176,7 @@ impl TcpConnectionContext { } Err(e) => { let message = format!( - "Failed to find audit entry with client_source_port '{}' with error: {}", - client_source_port, e + "Failed to find audit entry with client_source_port '{client_source_port}' with error: {e}" ); logger.write(LoggerLevel::Warn, message.clone()); @@ -206,7 +203,7 @@ impl TcpConnectionContext { Err(e) => { logger.write( LoggerLevel::Warn, - format!("Failed to get lookup_audit_from_stream with error: {}", e), + format!("Failed to get lookup_audit_from_stream with error: {e}"), ); Err(Error::FindAuditEntryError(message)) } diff --git a/proxy_agent/src/proxy/proxy_server.rs b/proxy_agent/src/proxy/proxy_server.rs index 968773b6..1fe378bc 100644 --- a/proxy_agent/src/proxy/proxy_server.rs +++ b/proxy_agent/src/proxy/proxy_server.rs @@ -111,10 +111,7 @@ impl ProxyServer { } _ => { // other error, return it - return Err(Error::Io( - format!("Failed to bind TcpListener '{}'", addr), - e, - )); + return Err(Error::Io(format!("Failed to bind TcpListener '{addr}'"), e)); } }, } @@ -123,7 +120,7 @@ impl ProxyServer { // one more effort try bind to the addr TcpListener::bind(addr) .await - .map_err(|e| Error::Io(format!("Failed to bind TcpListener '{}'", addr), e)) + .map_err(|e| Error::Io(format!("Failed to bind TcpListener '{addr}'"), e)) } pub async fn start(&self) { @@ -145,14 +142,14 @@ impl ProxyServer { .set_module_status_message(message.to_string(), AgentStatusModule::ProxyServer) .await { - logger::write_warning(format!("Failed to set module status message: {}", e)); + logger::write_warning(format!("Failed to set module status message: {e}")); } if let Err(e) = self .agent_status_shared_state .set_module_state(ModuleState::STOPPED, AgentStatusModule::ProxyServer) .await { - logger::write_warning(format!("Failed to set module state: {}", e)); + logger::write_warning(format!("Failed to set module state: {e}")); } // send this critical error to event logger @@ -179,14 +176,14 @@ impl ProxyServer { .set_module_status_message(message.to_string(), AgentStatusModule::ProxyServer) .await { - logger::write_warning(format!("Failed to set module status message: {}", e)); + logger::write_warning(format!("Failed to set module status message: {e}")); } if let Err(e) = self .agent_status_shared_state .set_module_state(ModuleState::RUNNING, AgentStatusModule::ProxyServer) .await { - logger::write_warning(format!("Failed to set module state: {}", e)); + logger::write_warning(format!("Failed to set module state: {e}")); } provision::listener_started( self.cancellation_token.clone(), @@ -213,7 +210,7 @@ impl ProxyServer { self.handle_new_tcp_connection(stream, client_addr).await; }, Err(e) => { - logger::write_error(format!("Failed to accept connection: {}", e)); + logger::write_error(format!("Failed to accept connection: {e}")); } } } @@ -235,7 +232,7 @@ impl ProxyServer { Err(e) => { ConnectionLogger::new(0, 0).write( LoggerLevel::Error, - format!("Failed to increase tcp connection count: {}", e), + format!("Failed to increase tcp connection count: {e}"), ); return; } @@ -243,7 +240,7 @@ impl ProxyServer { let mut tcp_connection_logger = ConnectionLogger::new(tcp_connection_id, 0); tcp_connection_logger.write( LoggerLevel::Trace, - format!("Accepted new tcp connection [{}].", tcp_connection_id), + format!("Accepted new tcp connection [{tcp_connection_id}]."), ); tokio::spawn({ @@ -255,7 +252,7 @@ impl ProxyServer { Err(e) => { tcp_connection_logger.write( LoggerLevel::Error, - format!("Failed to set stream read timeout: {}", e), + format!("Failed to set stream read timeout: {e}"), ); return; } @@ -312,7 +309,7 @@ impl ProxyServer { { tcp_connection_logger.write( LoggerLevel::Warn, - format!("ProxyListener serve_connection error: {}", e), + format!("ProxyListener serve_connection error: {e}"), ); } } @@ -342,7 +339,7 @@ impl ProxyServer { if let Err(e) = std_stream.set_read_timeout(Some(std::time::Duration::from_secs(10))) { connection_logger.write( LoggerLevel::Warn, - format!("Failed to set read timeout: {}", e), + format!("Failed to set read timeout: {e}"), ); } @@ -376,7 +373,7 @@ impl ProxyServer { Err(e) => { tcp_connection_context.log( LoggerLevel::Error, - format!("Failed to increase connection count: {}", e), + format!("Failed to increase connection count: {e}"), ); return Ok(Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR)); } @@ -455,7 +452,7 @@ impl ProxyServer { &mut http_connection_context, StatusCode::MISDIRECTED_REQUEST, false, - format!("Failed to get claims json string: {}", e), + format!("Failed to get claims json string: {e}"), ) .await; return Ok(Self::empty_response(StatusCode::MISDIRECTED_REQUEST)); @@ -477,7 +474,7 @@ impl ProxyServer { &mut http_connection_context, StatusCode::INTERNAL_SERVER_ERROR, false, - format!("Failed to get access control rules: {}", e), + format!("Failed to get access control rules: {e}"), ) .await; return Ok(Self::empty_response(StatusCode::INTERNAL_SERVER_ERROR)); @@ -505,7 +502,7 @@ impl ProxyServer { &mut http_connection_context, StatusCode::FORBIDDEN, false, - format!("Block unauthorized request: {}", claim_details), + format!("Block unauthorized request: {claim_details}"), ) .await; return Ok(Self::empty_response(StatusCode::FORBIDDEN)); @@ -528,10 +525,7 @@ impl ProxyServer { Err(e) => { http_connection_context.log( LoggerLevel::Error, - format!( - "Failed to add claims header: {} with error: {}", - host_claims, e - ), + format!("Failed to add claims header: {host_claims} with error: {e}"), ); return Ok(Self::empty_response(StatusCode::BAD_GATEWAY)); } @@ -544,7 +538,7 @@ impl ProxyServer { Err(e) => { http_connection_context.log( LoggerLevel::Error, - format!("Failed to add date header with error: {}", e), + format!("Failed to add date header with error: {e}"), ); return Ok(Self::empty_response(StatusCode::BAD_GATEWAY)); } @@ -571,7 +565,7 @@ impl ProxyServer { Err(e) => { http_connection_context.log( LoggerLevel::Error, - format!("Failed to convert request: {}", e), + format!("Failed to convert request: {e}"), ); return Ok(Self::empty_response(StatusCode::BAD_REQUEST)); } @@ -624,7 +618,7 @@ impl ProxyServer { Err(e) => { logger.write( LoggerLevel::Warn, - format!("Failed to parse time_tick header: {}", e), + format!("Failed to parse time_tick header: {e}"), ); 0 } @@ -652,7 +646,7 @@ impl ProxyServer { if let Err(e) = self.key_keeper_shared_state.notify().await { logger.write( LoggerLevel::Warn, - format!("Failed to notify key_keeper: {}", e), + format!("Failed to notify key_keeper: {e}"), ); } } @@ -663,7 +657,7 @@ impl ProxyServer { ); match serde_json::to_string(&provision_state) { Ok(json) => { - logger.write(LoggerLevel::Info, format!("Provision state: {}", json)); + logger.write(LoggerLevel::Info, format!("Provision state: {json}")); let mut response = Response::new(hyper_client::full_body(json.as_bytes().to_vec())); response.headers_mut().insert( hyper::header::CONTENT_TYPE, @@ -672,7 +666,7 @@ impl ProxyServer { Ok(response) } Err(e) => { - let error = format!("Failed to get provision state: {}", e); + let error = format!("Failed to get provision state: {e}"); logger.write(LoggerLevel::Warn, error.to_string()); let mut response = Response::new(hyper_client::full_body(error.as_bytes().to_vec())); @@ -698,7 +692,7 @@ impl ProxyServer { &mut http_connection_context, http_status_code, false, - format!("Failed to send request to host: {}", e), + format!("Failed to send request to host: {e}"), ) .await; return Ok(Self::empty_response(http_status_code)); @@ -713,7 +707,7 @@ impl ProxyServer { Err(e) => { logger.write( LoggerLevel::Error, - format!("Failed to get frame data: {:?}", e), + format!("Failed to get frame data: {e:?}"), ); Bytes::new() } @@ -810,7 +804,7 @@ impl ProxyServer { { http_connection_context.log( LoggerLevel::Warn, - format!("Failed to add failed connection summary: {}", e), + format!("Failed to add failed connection summary: {e}"), ); } } else if let Err(e) = self @@ -820,7 +814,7 @@ impl ProxyServer { { http_connection_context.log( LoggerLevel::Warn, - format!("Failed to add connection summary: {}", e), + format!("Failed to add connection summary: {e}"), ); } } @@ -845,7 +839,7 @@ impl ProxyServer { Err(e) => { http_connection_context.log( LoggerLevel::Error, - format!("Failed to receive the request body: {}", e), + format!("Failed to receive the request body: {e}"), ); return Ok(Self::empty_response(StatusCode::BAD_REQUEST)); } @@ -890,8 +884,7 @@ impl ProxyServer { http_connection_context.log( LoggerLevel::Error, format!( - "Failed to add authorization header: {} with error: {}", - authorization_value, e + "Failed to add authorization header: {authorization_value} with error: {e}" ), ); return Ok(Self::empty_response(StatusCode::BAD_GATEWAY)); @@ -901,13 +894,13 @@ impl ProxyServer { http_connection_context.log( LoggerLevel::Trace, - format!("Added authorization header {}", authorization_value), + format!("Added authorization header {authorization_value}"), ) } Err(e) => { http_connection_context.log( LoggerLevel::Error, - format!("compute_signature failed with error: {}", e), + format!("compute_signature failed with error: {e}"), ); } } diff --git a/proxy_agent/src/proxy/windows.rs b/proxy_agent/src/proxy/windows.rs index c75869d4..74085f59 100644 --- a/proxy_agent/src/proxy/windows.rs +++ b/proxy_agent/src/proxy/windows.rs @@ -41,8 +41,8 @@ fn load_netapi32_dll() -> Library { match unsafe { Library::new(dll_name) } { Ok(lib) => lib, Err(e) => { - logger::write_error(format!("Loading {} failed with error: {}.", dll_name, e)); - panic!("Loading {} failed with error: {}", dll_name, e); + logger::write_error(format!("Loading {dll_name} failed with error: {e}.")); + panic!("Loading {dll_name} failed with error: {e}"); } } } @@ -115,7 +115,7 @@ pub fn get_user(logon_id: u64) -> Result<(String, Vec)> { if status != 0 { let e = std::io::Error::from_raw_os_error(status as i32); return Err(Error::WindowsApi( - WindowsApiErrorType::LsaGetLogonSessionData(format!("failed with os error: {}", e)), + WindowsApiErrorType::LsaGetLogonSessionData(format!("failed with os error: {e}")), )); } @@ -127,8 +127,7 @@ pub fn get_user(logon_id: u64) -> Result<(String, Vec)> { // but finding that SECURITY_LOGON_SESSION_DATA->UserName.Length is 0, // it typically means that the logon session exists but does not have an associated username. logger::write_warning(format!( - "LsaGetLogonSessionData with login'{}' success, but user name is empty.", - logon_id + "LsaGetLogonSessionData with logon id '{logon_id}' success, but user name is empty." )); // return OK with UNDEFINED user name and empty groups return Ok((super::UNDEFINED.to_string(), Vec::new())); @@ -171,8 +170,7 @@ pub fn get_user(logon_id: u64) -> Result<(String, Vec)> { } else { let e = std::io::Error::from_raw_os_error(status as i32); logger::write_warning(format!( - "NetUserGetLocalGroups '{}' failed ({}) with os error: {}", - domain_user_name, status, e + "NetUserGetLocalGroups '{domain_user_name}' failed ({status}) with os error: {e}" )); } @@ -296,7 +294,7 @@ pub fn get_process_cmd(handler: isize) -> Result { std::io::Error::from_raw_os_error(status), ))); } - println!("return_length: {}", return_length); + println!("return_length: {return_length}"); let buf_len = (return_length as usize) / 2; let mut buffer: Vec = vec![0; buf_len + 1]; @@ -310,7 +308,7 @@ pub fn get_process_cmd(handler: isize) -> Result { &mut return_length as *mut _, ); if status < 0 { - eprintln!("NtQueryInformationProcess failed with status: {}", status); + eprintln!("NtQueryInformationProcess failed with status: {status}"); return Err(Error::WindowsApi(WindowsApiErrorType::WindowsOsError( std::io::Error::from_raw_os_error(status), ))); diff --git a/proxy_agent/src/proxy_agent_status.rs b/proxy_agent/src/proxy_agent_status.rs index 6496b308..777c1620 100644 --- a/proxy_agent/src/proxy_agent_status.rs +++ b/proxy_agent/src/proxy_agent_status.rs @@ -92,7 +92,7 @@ impl ProxyAgentStatusTask { .set_module_status_message(status_message, AgentStatusModule::ProxyAgentStatus) .await { - logger::write_error(format!("Error updating agent status message: {}", e)); + logger::write_error(format!("Error updating agent status message: {e}")); } } @@ -104,7 +104,7 @@ impl ProxyAgentStatusTask { { Ok(message) => message, Err(e) => { - let message = format!("Error getting agent status message: {}", e); + let message = format!("Error getting agent status message: {e}"); logger::write_error(message.clone()); message } @@ -131,7 +131,7 @@ impl ProxyAgentStatusTask { if status_report_time.elapsed() >= status_report_duration { let status = match serde_json::to_string(&aggregate_status.proxyAgentStatus) { Ok(status) => status, - Err(e) => format!("Error serializing proxy agent status: {}", e), + Err(e) => format!("Error serializing proxy agent status: {e}"), }; event_logger::write_event( LoggerLevel::Info, @@ -152,7 +152,7 @@ impl ProxyAgentStatusTask { .to_string(), ); if let Err(e) = self.agent_status_shared_state.clear_all_summary().await { - logger::write_error(format!("Error clearing the connection summary map and failed authenticate summary map: {}", e)); + logger::write_error(format!("Error clearing the connection summary map and failed authenticate summary map: {e}")); } start_time = Instant::now(); } @@ -249,7 +249,7 @@ impl ProxyAgentStatusTask { { Ok(count) => count, Err(e) => { - logger::write_error(format!("Error getting connection count: {}", e)); + logger::write_error(format!("Error getting connection count: {e}")); 0 } }, @@ -267,7 +267,7 @@ impl ProxyAgentStatusTask { { Ok(summary) => summary, Err(e) => { - logger::write_error(format!("Error getting connection summary: {}", e)); + logger::write_error(format!("Error getting connection summary: {e}")); vec![] } }, @@ -278,7 +278,7 @@ impl ProxyAgentStatusTask { { Ok(summary) => summary, Err(e) => { - logger::write_error(format!("Error getting failed connection summary: {}", e)); + logger::write_error(format!("Error getting failed connection summary: {e}")); vec![] } }, @@ -289,8 +289,7 @@ impl ProxyAgentStatusTask { let full_file_path = self.status_dir.join("status.json"); if let Err(e) = misc_helpers::json_write_to_file(&status, &full_file_path) { self.update_agent_status_message(format!( - "Error writing aggregate status to status file: {}", - e + "Error writing aggregate status to status file: {e}" )) .await; } else { diff --git a/proxy_agent/src/redirector.rs b/proxy_agent/src/redirector.rs index 6b71fa47..07a33433 100644 --- a/proxy_agent/src/redirector.rs +++ b/proxy_agent/src/redirector.rs @@ -138,8 +138,7 @@ impl Redirector { .await { logger::write_error(format!( - "Failed to set error status '{}' for redirector: {}", - message, e + "Failed to set error status '{message}' for redirector: {e}" )); } @@ -299,8 +298,7 @@ impl Redirector { .await { logger::write_error(format!( - "Failed to set error status '{}' for redirector: {}", - message, e + "Failed to set error status '{message}' for redirector: {e}" )); } } @@ -339,7 +337,7 @@ pub fn ip_to_string(ip: u32) -> String { pub fn string_to_ip(ip_str: &str) -> u32 { let ip_str_seg: Vec<&str> = ip_str.split('.').collect(); if ip_str_seg.len() != 4 { - logger::write_warning(format!("string_to_ip:: ip_str {} is invalid", ip_str)); + logger::write_warning(format!("string_to_ip:: ip_str {ip_str} is invalid")); return 0; } @@ -353,8 +351,7 @@ pub fn string_to_ip(ip_str: &str) -> u32 { } Err(e) => { logger::write_warning(format!( - "string_to_ip:: error parsing ip segment {} with error: {}", - ip_str, e + "string_to_ip:: error parsing ip segment {ip_str} with error: {e}" )); return 0; } diff --git a/proxy_agent/src/redirector/linux.rs b/proxy_agent/src/redirector/linux.rs index 6676ba39..f973428e 100644 --- a/proxy_agent/src/redirector/linux.rs +++ b/proxy_agent/src/redirector/linux.rs @@ -66,11 +66,11 @@ impl BpfObject { let key = sock_addr_skip_process_entry::from_pid(pid); let value = sock_addr_skip_process_entry::from_pid(pid); match skip_process_map.insert(key.to_array(), value.to_array(), 0) { - Ok(_) => logger::write(format!("skip_process_map updated with {}", pid)), + Ok(_) => logger::write(format!("skip_process_map updated with {pid}")), Err(err) => { return Err(Error::Bpf(BpfErrorType::UpdateBpfMapHashMap( skip_process_map_name.to_string(), - format!("insert pid: {}", pid), + format!("insert pid: {pid}"), err.to_string(), ))); } @@ -156,8 +156,7 @@ impl BpfObject { match program.attach(cgroup, CgroupAttachMode::Single) { Ok(link_id) => { logger::write(format!( - "connect4 program attached with id {:?}.", - link_id + "connect4 program attached with id {link_id:?}." )); } Err(err) => { @@ -211,8 +210,7 @@ impl BpfObject { match program.attach("tcp_connect", 0) { Ok(link_id) => { logger::write(format!( - "tcp_v4_connect program attached with id {:?}.", - link_id + "tcp_v4_connect program attached with id {link_id:?}." )); } Err(err) => { @@ -340,8 +338,7 @@ impl BpfObject { } Err(err) => { logger::write(format!( - "Failed to load HashMap 'policy_map' with error: {}", - err + "Failed to load HashMap 'policy_map' with error: {err}" )); } }, @@ -360,7 +357,7 @@ impl BpfObject { audit_map.remove(&key.to_array()).map_err(|err| { Error::Bpf(BpfErrorType::MapDeleteElem( source_port.to_string(), - format!("Error: {}", err), + format!("Error: {err}"), )) })?; } @@ -402,7 +399,7 @@ impl super::Redirector { Err(e) => { event_logger::write_event( LoggerLevel::Warn, - format!("Failed to get the cgroup2 mount path {}, fallback to use the cgroup2 path from config file.", e), + format!("Failed to get the cgroup2 mount path {e}, fallback to use the cgroup2 path from config file."), "start", "redirector/linux", logger::AGENT_LOGGER_KEY, @@ -411,7 +408,7 @@ impl super::Redirector { } }; if let Err(e) = bpf_object.attach_cgroup_program(cgroup2_path) { - let message = format!("Failed to attach cgroup program for redirection. {}", e); + let message = format!("Failed to attach cgroup program for redirection. {e}"); event_logger::write_event( LoggerLevel::Warn, message.to_string(), diff --git a/proxy_agent/src/redirector/windows.rs b/proxy_agent/src/redirector/windows.rs index 7daf8092..cf23a3b8 100644 --- a/proxy_agent/src/redirector/windows.rs +++ b/proxy_agent/src/redirector/windows.rs @@ -122,8 +122,7 @@ pub fn get_audit_from_redirect_context(raw_socket_id: usize) -> Result Result bool { if let Err(e) = EBPF_API.set(ebpf_api) { event_logger::write_event( LoggerLevel::Error, - format!("{}", e), + format!("{e}"), "try_load_ebpf_api", "redirector", logger::AGENT_LOGGER_KEY, @@ -61,7 +61,7 @@ fn init_ebpf_lib() -> Option { if let Err(e) = EBPF_API_VERSION.set(v) { event_logger::write_event( LoggerLevel::Error, - format!("{}", e), + format!("{e}"), "EBPF_API_VERSION.set", "redirector", logger::AGENT_LOGGER_KEY, @@ -71,7 +71,7 @@ fn init_ebpf_lib() -> Option { Err(e) => { event_logger::write_event( LoggerLevel::Warn, - format!("{}", e), + format!("{e}"), "get_file_product_version", "redirector", logger::AGENT_LOGGER_KEY, @@ -85,7 +85,7 @@ fn init_ebpf_lib() -> Option { Err(e) => { event_logger::write_event( LoggerLevel::Warn, - format!("{}", e), + format!("{e}"), "load_ebpf_api", "redirector", logger::AGENT_LOGGER_KEY, @@ -101,7 +101,7 @@ fn init_ebpf_lib() -> Option { Err(e) => { event_logger::write_event( LoggerLevel::Warn, - format!("{}", e), + format!("{e}"), "load_ebpf_api", "redirector", logger::AGENT_LOGGER_KEY, diff --git a/proxy_agent/src/redirector/windows/bpf_prog.rs b/proxy_agent/src/redirector/windows/bpf_prog.rs index 27b6c8f8..71e51968 100644 --- a/proxy_agent/src/redirector/windows/bpf_prog.rs +++ b/proxy_agent/src/redirector/windows/bpf_prog.rs @@ -60,10 +60,7 @@ impl BpfObject { let error_code = libbpf_get_error()?; return Err(Error::Bpf(BpfErrorType::OpenBpfObject( bpf_file_path.display().to_string(), - format!( - "bpf_object__open return null pointer with error code '{}'", - error_code - ), + format!("bpf_object__open return null pointer with error code '{error_code}'",), ))); } @@ -84,7 +81,7 @@ impl BpfObject { } else { return Err(Error::Bpf(BpfErrorType::LoadBpfObject( bpf_file_path.display().to_string(), - format!("bpf_object__load return with error code '{}'", result), + format!("bpf_object__load return with error code '{result}'"), ))); } @@ -109,7 +106,7 @@ impl BpfObject { let program_name = "authorize_connect4"; let connect4_program = match bpf_object__find_program_by_name(self.0, program_name) { Ok(p) => { - logger::write_information(format!("Found {} program.", program_name)); + logger::write_information(format!("Found {program_name} program.")); p } Err(e) => { @@ -141,7 +138,7 @@ impl BpfObject { if r != 0 { return Err(Error::Bpf(BpfErrorType::AttachBpfProgram( program_name.to_string(), - format!("ebpf_prog_attach return with error code '{}'", r), + format!("ebpf_prog_attach return with error code '{r}'"), ))); } logger::write_information( @@ -157,7 +154,7 @@ impl BpfObject { if r != 0 { return Err(Error::Bpf(BpfErrorType::AttachBpfProgram( program_name.to_string(), - format!("bpf_link_destroy return with error code '{}'", r), + format!("bpf_link_destroy return with error code '{r}'"), ))); } logger::write_information("Success destroyed link.".to_string()); @@ -165,7 +162,7 @@ impl BpfObject { Err(e) => { return Err(Error::Bpf(BpfErrorType::AttachBpfProgram( program_name.to_string(), - format!("bpf_link_destroy return with error '{}'", e), + format!("bpf_link_destroy return with error '{e}'"), ))); } } @@ -173,7 +170,7 @@ impl BpfObject { Err(e) => { return Err(Error::Bpf(BpfErrorType::AttachBpfProgram( program_name.to_string(), - format!("bpf_link_disconnect return with error '{}'", e), + format!("bpf_link_disconnect return with error '{e}'"), ))); } } @@ -181,7 +178,7 @@ impl BpfObject { Err(e) => { return Err(Error::Bpf(BpfErrorType::AttachBpfProgram( program_name.to_string(), - format!("ebpf_prog_attach return with error '{}'", e), + format!("ebpf_prog_attach return with error '{e}'"), ))); } } @@ -231,14 +228,14 @@ impl BpfObject { Error::Bpf(BpfErrorType::UpdateBpfMapHashMap( map_name.to_string(), endpoint_name.to_string(), - format!("bpf_map_update_elem returned error {}", e), + format!("bpf_map_update_elem returned error {e}"), )) })?; if result != 0 { return Err(Error::Bpf(BpfErrorType::UpdateBpfMapHashMap( map_name.to_string(), endpoint_name.to_string(), - format!("bpf_map_update_elem returned error code {}", result), + format!("bpf_map_update_elem returned error code {result}"), ))); } @@ -260,7 +257,7 @@ impl BpfObject { return; } if let Err(e) = bpf_object__close(self.0) { - logger::write_error(format!("bpf_object__close with error: {}", e)); + logger::write_error(format!("bpf_object__close with error: {e}")); } self.0 = std::ptr::null::().cast_mut(); @@ -297,14 +294,14 @@ impl BpfObject { .map_err(|e| { Error::Bpf(BpfErrorType::MapLookupElem( source_port.to_string(), - format!("Error: {}", e), + format!("Error: {e}"), )) })?; if result != 0 { return Err(Error::Bpf(BpfErrorType::MapLookupElem( source_port.to_string(), - format!("Result: {}", result), + format!("Result: {result}"), ))); } @@ -341,15 +338,15 @@ impl BpfObject { .map_err(|e| { Error::Bpf(BpfErrorType::UpdateBpfMapHashMap( map_name.to_string(), - format!("insert pid: {}", pid), - format!("bpf_map_update_elem returned error {}", e), + format!("insert pid: {pid}"), + format!("bpf_map_update_elem returned error {e}"), )) })?; if result != 0 { return Err(Error::Bpf(BpfErrorType::UpdateBpfMapHashMap( map_name.to_string(), - format!("insert pid: {}", pid), - format!("bpf_map_update_elem returned error code {}", result), + format!("insert pid: {pid}"), + format!("bpf_map_update_elem returned error code {result}"), ))); } @@ -374,14 +371,14 @@ impl BpfObject { bpf_map_delete_elem(map_fd, &key as *const destination_entry_t as *const c_void) .map_err(|e| { Error::Bpf(BpfErrorType::MapDeleteElem( - format!("dest_ipv4: {}, dest_port: {}", dest_ipv4, dest_port), - format!("Error: {}", e), + format!("dest_ipv4: {dest_ipv4}, dest_port: {dest_port}"), + format!("Error: {e}"), )) })?; if result != 0 { return Err(Error::Bpf(BpfErrorType::MapDeleteElem( - format!("dest_ipv4: {}, dest_port: {}", dest_ipv4, dest_port), - format!("Result: {}", result), + format!("dest_ipv4: {dest_ipv4}, dest_port: {dest_port}"), + format!("Result: {result}"), ))); } @@ -400,14 +397,14 @@ impl BpfObject { .map_err(|e| { Error::Bpf(BpfErrorType::MapDeleteElem( source_port.to_string(), - format!("Error: {}", e), + format!("Error: {e}"), )) })?; if result != 0 { return Err(Error::Bpf(BpfErrorType::MapDeleteElem( source_port.to_string(), - format!("Result: {}", result), + format!("Result: {result}"), ))); } diff --git a/proxy_agent/src/service/windows.rs b/proxy_agent/src/service/windows.rs index 1a44323b..d62170c3 100644 --- a/proxy_agent/src/service/windows.rs +++ b/proxy_agent/src/service/windows.rs @@ -40,8 +40,7 @@ pub async fn run_service() -> Result<()> { }; if let Err(e) = status_handle.set_service_status(stop_state) { logger::write_error(format!( - "Failed to set service status to Stopped: {}", - e + "Failed to set service status to Stopped: {e}" )); } } else { diff --git a/proxy_agent/src/shared_state/agent_status_wrapper.rs b/proxy_agent/src/shared_state/agent_status_wrapper.rs index bfffaab0..f540c4e5 100644 --- a/proxy_agent/src/shared_state/agent_status_wrapper.rs +++ b/proxy_agent/src/shared_state/agent_status_wrapper.rs @@ -207,7 +207,7 @@ impl AgentStatusSharedState { } } if response.send(updated).is_err() { - logger::write_warning(format!("Failed to send response to AgentStatusAction::SetStatusMessage for module {:?}", module)); + logger::write_warning(format!("Failed to send response to AgentStatusAction::SetStatusMessage for module {module:?}")); } } AgentStatusAction::GetStatusMessage { module, response } => { @@ -227,8 +227,7 @@ impl AgentStatusSharedState { }; if let Err(message) = response.send(message) { logger::write_warning(format!( - "Failed to send response to AgentStatusAction::GetStatusMessage for module '{:?}' with message '{:?}'", - module,message + "Failed to send response to AgentStatusAction::GetStatusMessage for module '{module:?}' with message '{message:?}'" )); } } @@ -258,7 +257,7 @@ impl AgentStatusSharedState { } } if let Err(state) = response.send(state) { - logger::write_warning(format!("Failed to send response to AgentStatusAction::SetState '{:?}' for module '{:?}'", state, module)); + logger::write_warning(format!("Failed to send response to AgentStatusAction::SetState '{state:?}' for module '{module:?}'")); } } AgentStatusAction::GetState { module, response } => { @@ -272,8 +271,7 @@ impl AgentStatusSharedState { }; if let Err(state) = response.send(state) { logger::write_warning(format!( - "Failed to send response to AgentStatusAction::GetState for module '{:?}' with state '{:?}'", - module,state + "Failed to send response to AgentStatusAction::GetState for module '{module:?}' with state '{state:?}'" )); } } @@ -342,8 +340,7 @@ impl AgentStatusSharedState { AgentStatusAction::GetConnectionCount { response } => { if let Err(count) = response.send(http_connection_count) { logger::write_warning(format!( - "Failed to send response to AgentStatusAction::GetConnectionCount with count '{:?}'", - count + "Failed to send response to AgentStatusAction::GetConnectionCount with count '{count:?}'" )); } } @@ -352,8 +349,7 @@ impl AgentStatusSharedState { http_connection_count = http_connection_count.overflowing_add(1).0; if let Err(count) = response.send(http_connection_count) { logger::write_warning(format!( - "Failed to send response to AgentStatusAction::IncreaseConnectionCount with count '{:?}'", - count + "Failed to send response to AgentStatusAction::IncreaseConnectionCount with count '{count:?}'" )); } } @@ -362,8 +358,7 @@ impl AgentStatusSharedState { tcp_connection_count = tcp_connection_count.overflowing_add(1).0; if let Err(count) = response.send(tcp_connection_count) { logger::write_warning(format!( - "Failed to send response to AgentStatusAction::IncreaseTcpConnectionCount with count '{:?}'", - count + "Failed to send response to AgentStatusAction::IncreaseTcpConnectionCount with count '{count:?}'" )); } } @@ -483,13 +478,13 @@ impl AgentStatusSharedState { .await .map_err(|e| { Error::SendError( - format!("AgentStatusAction::GetState ({:?})", module), + format!("AgentStatusAction::GetState ({module:?})"), e.to_string(), ) })?; response_rx .await - .map_err(|e| Error::RecvError(format!("AgentStatusAction::GetState ({:?})", module), e)) + .map_err(|e| Error::RecvError(format!("AgentStatusAction::GetState ({module:?})"), e)) } pub async fn set_module_state( @@ -507,13 +502,13 @@ impl AgentStatusSharedState { .await .map_err(|e| { Error::SendError( - format!("AgentStatusAction::SetState ({:?})", module), + format!("AgentStatusAction::SetState ({module:?})"), e.to_string(), ) })?; response_rx .await - .map_err(|e| Error::RecvError(format!("AgentStatusAction::SetState ({:?})", module), e)) + .map_err(|e| Error::RecvError(format!("AgentStatusAction::SetState ({module:?})"), e)) } pub async fn get_module_status_message(&self, module: AgentStatusModule) -> Result { @@ -526,13 +521,13 @@ impl AgentStatusSharedState { .await .map_err(|e| { Error::SendError( - format!("AgentStatusAction::GetStatusMessage ({:?})", module), + format!("AgentStatusAction::GetStatusMessage ({module:?})"), e.to_string(), ) })?; response_rx.await.map_err(|e| { Error::RecvError( - format!("AgentStatusAction::GetStatusMessage ({:?})", module), + format!("AgentStatusAction::GetStatusMessage ({module:?})"), e, ) }) @@ -560,13 +555,13 @@ impl AgentStatusSharedState { .await .map_err(|e| { Error::SendError( - format!("AgentStatusAction::SetStatusMessage ({:?})", module), + format!("AgentStatusAction::SetStatusMessage ({module:?})"), e.to_string(), ) })?; let update = response_rx.await.map_err(|e| { Error::RecvError( - format!("AgentStatusAction::SetStatusMessage ({:?})", module), + format!("AgentStatusAction::SetStatusMessage ({module:?})"), e, ) })?; @@ -577,7 +572,7 @@ impl AgentStatusSharedState { LoggerLevel::Warn, message, "set_module_status_message", - &format!("{:?}", module), + &format!("{module:?}"), logger::AGENT_LOGGER_KEY, ); } @@ -588,7 +583,7 @@ impl AgentStatusSharedState { let state = match self.get_module_state(module.clone()).await { Ok(state) => state, Err(e) => { - logger::write_warning(format!("Error getting module '{:?}' status: {}", module, e)); + logger::write_warning(format!("Error getting module '{module:?}' status: {e}")); ModuleState::UNKNOWN } }; @@ -596,8 +591,7 @@ impl AgentStatusSharedState { Ok(message) => message, Err(e) => { logger::write_warning(format!( - "Error getting module '{:?}' status message: {}", - module, e + "Error getting module '{module:?}' status message: {e}" )); super::UNKNOWN_STATUS_MESSAGE.to_string() } @@ -606,11 +600,10 @@ impl AgentStatusSharedState { event_logger::write_event( LoggerLevel::Warn, format!( - "Status message is too long, truncating to {} characters. Message: {}", - MAX_STATUS_MESSAGE_LENGTH, message + "Status message is too long, truncating to {MAX_STATUS_MESSAGE_LENGTH} characters. Message: {message}" ), "get_status", - &format!("{:?}", module), + &format!("{state:?}"), logger::AGENT_LOGGER_KEY, ); message = format!("{}...", &message[0..MAX_STATUS_MESSAGE_LENGTH]); diff --git a/proxy_agent/src/shared_state/key_keeper_wrapper.rs b/proxy_agent/src/shared_state/key_keeper_wrapper.rs index c7eed7e9..649b15e6 100644 --- a/proxy_agent/src/shared_state/key_keeper_wrapper.rs +++ b/proxy_agent/src/shared_state/key_keeper_wrapper.rs @@ -160,16 +160,14 @@ impl KeyKeeperSharedState { current_secure_channel_state = state.to_string(); if response.send(()).is_err() { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::SetSecureChannelState '{}' ", - state + "Failed to send response to KeyKeeperAction::SetSecureChannelState '{state}' " )); } } Some(KeyKeeperAction::GetSecureChannelState { response }) => { if let Err(state) = response.send(current_secure_channel_state.clone()) { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::GetSecureChannelState '{}'", - state + "Failed to send response to KeyKeeperAction::GetSecureChannelState '{state}'" )); } } @@ -177,16 +175,14 @@ impl KeyKeeperSharedState { wireserver_rule_id = rule_id.to_string(); if response.send(()).is_err() { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::SetWireServerRuleId '{}'", - rule_id + "Failed to send response to KeyKeeperAction::SetWireServerRuleId '{rule_id}'" )); } } Some(KeyKeeperAction::GetWireServerRuleId { response }) => { if let Err(rule_id) = response.send(wireserver_rule_id.clone()) { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::GetWireServerRuleId '{}'", - rule_id + "Failed to send response to KeyKeeperAction::GetWireServerRuleId '{rule_id}'" )); } } @@ -194,24 +190,21 @@ impl KeyKeeperSharedState { imds_rule_id = rule_id.to_string(); if response.send(()).is_err() { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::SetImdsRuleId '{}'", - rule_id + "Failed to send response to KeyKeeperAction::SetImdsRuleId '{rule_id}'" )); } } Some(KeyKeeperAction::GetImdsRuleId { response }) => { if let Err(rule_id) = response.send(imds_rule_id.clone()) { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::GetImdsRuleId '{}'", - rule_id + "Failed to send response to KeyKeeperAction::GetImdsRuleId '{rule_id}'" )); } } Some(KeyKeeperAction::GetHostGARuleId { response }) => { if let Err(rule_id) = response.send(hostga_rule_id.clone()) { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::GetHostGARuleId '{}'", - rule_id + "Failed to send response to KeyKeeperAction::GetHostGARuleId '{rule_id}'" )); } } @@ -219,8 +212,7 @@ impl KeyKeeperSharedState { hostga_rule_id = rule_id.to_string(); if response.send(()).is_err() { logger::write_warning(format!( - "Failed to send response to KeyKeeperAction::SetHostGARuleId '{}'", - rule_id + "Failed to send response to KeyKeeperAction::SetHostGARuleId '{rule_id}'" )); } } diff --git a/proxy_agent/src/shared_state/provision_wrapper.rs b/proxy_agent/src/shared_state/provision_wrapper.rs index e3cc1696..e9e92609 100644 --- a/proxy_agent/src/shared_state/provision_wrapper.rs +++ b/proxy_agent/src/shared_state/provision_wrapper.rs @@ -81,8 +81,7 @@ impl ProvisionSharedState { provision_state |= state; if let Err(new_state) = response.send(provision_state.clone()) { logger::write_warning(format!( - "Failed to send response to ProvisionAction::UpdateState with new state '{:?}'", - new_state + "Failed to send response to ProvisionAction::UpdateState with new state '{new_state:?}'" )); } } @@ -90,16 +89,14 @@ impl ProvisionSharedState { provision_state &= !state; if let Err(new_state) = response.send(provision_state.clone()) { logger::write_warning(format!( - "Failed to send response to ProvisionAction::ResetState with new state '{:?}'", - new_state + "Failed to send response to ProvisionAction::ResetState with new state '{new_state:?}'" )); } } ProvisionAction::GetState { response } => { if let Err(state) = response.send(provision_state.clone()) { logger::write_warning(format!( - "Failed to send response to ProvisionAction::GetState with state '{:?}'", - state + "Failed to send response to ProvisionAction::GetState with state '{state:?}'" )); } } @@ -114,8 +111,7 @@ impl ProvisionSharedState { response.send(provision_event_log_threads_initialized) { logger::write_warning(format!( - "Failed to send response to ProvisionAction::GetEventLogsThreadsInitialized with initialized '{:?}'", - initialized + "Failed to send response to ProvisionAction::GetEventLogsThreadsInitialized with initialized '{initialized:?}'" )); } } @@ -135,8 +131,7 @@ impl ProvisionSharedState { ProvisionAction::GetProvisionFinished { response } => { if let Err(finished) = response.send(provision_finished_time_tick) { logger::write_warning(format!( - "Failed to send response to ProvisionAction::GetProvisionFinished with finished '{:?}'", - finished + "Failed to send response to ProvisionAction::GetProvisionFinished with finished '{finished:?}'" )); } } diff --git a/proxy_agent/src/shared_state/proxy_server_wrapper.rs b/proxy_agent/src/shared_state/proxy_server_wrapper.rs index ce50c452..e9ef02a2 100644 --- a/proxy_agent/src/shared_state/proxy_server_wrapper.rs +++ b/proxy_agent/src/shared_state/proxy_server_wrapper.rs @@ -55,13 +55,13 @@ impl ProxyServerSharedState { let id = user.logon_id; users.insert(id, user); if response.send(()).is_err() { - logger::write_warning(format!("Failed to send response to ProxyServerAction::AddUser with id '{}'", id)); + logger::write_warning(format!("Failed to send response to ProxyServerAction::AddUser with id '{id}'")); } } ProxyServerAction::GetUser { user_id, response } => { let user = users.get(&user_id).cloned(); if response.send(user).is_err() { - logger::write_warning(format!("Failed to send response to ProxyServerAction::GetUser with id '{}'", user_id)); + logger::write_warning(format!("Failed to send response to ProxyServerAction::GetUser with id '{user_id}'")); } } #[cfg(test)] diff --git a/proxy_agent/src/shared_state/redirector_wrapper.rs b/proxy_agent/src/shared_state/redirector_wrapper.rs index 0f63d9b2..a1e9d2dd 100644 --- a/proxy_agent/src/shared_state/redirector_wrapper.rs +++ b/proxy_agent/src/shared_state/redirector_wrapper.rs @@ -61,16 +61,14 @@ impl RedirectorSharedState { local_port = new_local_port; if response.send(()).is_err() { logger::write_warning(format!( - "Failed to send response to RedirectorAction::SetLocalPort '{}'", - new_local_port + "Failed to send response to RedirectorAction::SetLocalPort '{new_local_port}'" )); } } RedirectorAction::GetLocalPort { response } => { if let Err(port) = response.send(local_port) { logger::write_warning(format!( - "Failed to send response to RedirectorAction::GetLocalPort '{}'", - port + "Failed to send response to RedirectorAction::GetLocalPort '{port}'" )); } } diff --git a/proxy_agent/src/shared_state/telemetry_wrapper.rs b/proxy_agent/src/shared_state/telemetry_wrapper.rs index c18211ac..f386de37 100644 --- a/proxy_agent/src/shared_state/telemetry_wrapper.rs +++ b/proxy_agent/src/shared_state/telemetry_wrapper.rs @@ -46,16 +46,14 @@ impl TelemetrySharedState { vm_meta_data = meta_data.clone(); if response.send(()).is_err() { logger::write_warning(format!( - "Failed to send response to TelemetryAction::SetVmMetaData '{:?}'", - meta_data, + "Failed to send response to TelemetryAction::SetVmMetaData '{meta_data:?}'" )); } } Some(TelemetryAction::GetVmMetaData { response }) => { if let Err(meta_data) = response.send(vm_meta_data.clone()) { logger::write_warning(format!( - "Failed to send response to TelemetryAction::GetVmMetaData '{:?}'", - meta_data, + "Failed to send response to TelemetryAction::GetVmMetaData '{meta_data:?}'" )); } } diff --git a/proxy_agent/src/telemetry/event_reader.rs b/proxy_agent/src/telemetry/event_reader.rs index 5d1dbc2d..06baadc7 100644 --- a/proxy_agent/src/telemetry/event_reader.rs +++ b/proxy_agent/src/telemetry/event_reader.rs @@ -171,7 +171,7 @@ impl EventReader { logger::write("success updated the vm metadata.".to_string()); } Err(e) => { - logger::write_warning(format!("Failed to read vm metadata with error {}.", e)); + logger::write_warning(format!("Failed to read vm metadata with error {e}.")); } } @@ -198,8 +198,7 @@ impl EventReader { .process_events_and_clean(files, wire_server_client, vm_meta_data) .await; let message = format!( - "Telemetry event reader sent {} events from {} files", - event_count, file_count + "Telemetry event reader sent {event_count} events from {file_count} files" ); logger::write(message); } @@ -248,7 +247,7 @@ impl EventReader { .set_vm_meta_data(Some(vm_meta_data.clone())) .await?; - logger::write(format!("Updated VM Metadata: {:?}", vm_meta_data)); + logger::write(format!("Updated VM Metadata: {vm_meta_data:?}")); Ok(()) } @@ -301,9 +300,8 @@ impl EventReader { match serde_json::to_string(&event) { Ok(json) => { logger::write_warning(format!( - "Event data too large. Not sending to wire-server. Event: {}.", - json - )); + "Event data too large. Not sending to wire-server. Event: {json}.", + )); } Err(_) => { logger::write_warning( @@ -345,8 +343,7 @@ impl EventReader { } Err(e) => { logger::write_warning(format!( - "Failed to send telemetry data to host with error: {}", - e + "Failed to send telemetry data to host with error: {e}" )); // wait 15 seconds and retry tokio::time::sleep(Duration::from_secs(15)).await; diff --git a/proxy_agent_extension/src/common.rs b/proxy_agent_extension/src/common.rs index cf50129c..fea6c0b5 100644 --- a/proxy_agent_extension/src/common.rs +++ b/proxy_agent_extension/src/common.rs @@ -61,7 +61,7 @@ pub fn report_heartbeat(heartbeat_file_path: PathBuf, heartbeat_obj: structs::He )); } Err(e) => { - logger::write(format!("Error in creating HeartBeat file: {:?}", e)); + logger::write(format!("Error in creating HeartBeat file: {e:?}")); } } } @@ -69,7 +69,7 @@ pub fn report_heartbeat(heartbeat_file_path: PathBuf, heartbeat_obj: structs::He pub fn get_file_path(status_folder: PathBuf, config_seq_no: &str, file_extension: &str) -> PathBuf { let mut file: PathBuf = status_folder; if let Err(e) = misc_helpers::try_create_folder(&file) { - logger::write(format!("Error in creating folder: {:?}", e)); + logger::write(format!("Error in creating folder: {e:?}")); } file.push(config_seq_no); file.set_extension(file_extension); @@ -107,10 +107,10 @@ pub fn report_status( // TODO: retry if write failed match fs::write(&status_file, root_status) { Ok(_) => { - logger::write(format!("Status file created: {:?}", status_file)); + logger::write(format!("Status file created: {status_file:?}")); } Err(e) => { - logger::write(format!("Error in creating status file: {:?}", e)); + logger::write(format!("Error in creating status file: {e:?}")); } } } @@ -128,12 +128,9 @@ pub fn update_current_seq_no(config_seq_no: &str, exe_path: &Path) -> Result { if seq_no != *config_seq_no { - logger::write(format!( - "updating seq no from {} to {}", - seq_no, config_seq_no - )); + logger::write(format!("updating seq no from {seq_no} to {config_seq_no}")); if let Err(e) = fs::write(¤t_seq_no_stored_file, config_seq_no) { - logger::write(format!("Error in writing seq no to file: {:?}", e)); + logger::write(format!("Error in writing seq no to file: {e:?}")); return Err(Error::Io(e)); } } else { @@ -148,7 +145,7 @@ pub fn update_current_seq_no(config_seq_no: &str, exe_path: &Path) -> Result String { let current_seq_no_stored_file: PathBuf = exe_path.join(constants::CURRENT_SEQ_NO_FILE); match fs::read_to_string(current_seq_no_stored_file) { Ok(seq_no) => { - logger::write(format!("Current seq no: {}", seq_no)); + logger::write(format!("Current seq no: {seq_no}")); seq_no } Err(e) => { - logger::write(format!("Error reading current seq no file: {:?}", e)); + logger::write(format!("Error reading current seq no file: {e:?}")); "".to_string() } } @@ -242,8 +239,7 @@ pub async fn start_event_logger() { // Check if the events folder exists if !event_folder.exists() { logger::write(format!( - "Events folder does not exist: {:?}. Skipping event logger start.", - event_folder + "Events folder does not exist: {event_folder:?}. Skipping event logger start." )); return; } diff --git a/proxy_agent_extension/src/handler_main.rs b/proxy_agent_extension/src/handler_main.rs index afa375a1..57918166 100644 --- a/proxy_agent_extension/src/handler_main.rs +++ b/proxy_agent_extension/src/handler_main.rs @@ -58,7 +58,7 @@ pub async fn program_start(command: ExtensionCommand, config_seq_no: String) { fn check_windows_os_version(version: Version) -> bool { match version.build { Some(build) => { - logger::write(format!("OS build version: {}", build)); + logger::write(format!("OS build version: {build}")); build >= constants::MIN_SUPPORTED_OS_BUILD } None => false, @@ -144,12 +144,11 @@ fn get_update_tag_file() -> PathBuf { fn update_tag_file_exists() -> bool { let update_tag_file = get_update_tag_file(); if update_tag_file.exists() { - logger::write(format!("update tag file exists: {:?}", update_tag_file)); + logger::write(format!("update tag file exists: {update_tag_file:?}")); true } else { logger::write(format!( - "update tag file does not exist: {:?}", - update_tag_file + "update tag file does not exist: {update_tag_file:?}" )); false } @@ -165,12 +164,12 @@ fn get_exe_parent() -> PathBuf { Path::new("") } }; - logger::write(format!("exe parent: {:?}", exe_parent)); + logger::write(format!("exe parent: {exe_parent:?}")); exe_parent.to_path_buf() } async fn handle_command(command: ExtensionCommand, config_seq_no: String) { - logger::write(format!("entering handle command: {:?}", command)); + logger::write(format!("entering handle command: {command:?}")); let status_folder = HANDLER_ENVIRONMENT.statusFolder.to_string(); let status_folder_path: PathBuf = PathBuf::from(&status_folder); match command { @@ -200,28 +199,26 @@ fn uninstall_handler() { match str::from_utf8(&output.stdout) { Ok(output_string) => { logger::write(format!( - "uninstalling GuestProxyAgent, output: {}", - output_string + "uninstalling GuestProxyAgent, output: {output_string}" )); } Err(e) => { - logger::write(format!("error in uninstalling GuestProxyAgent: {:?}", e)); + logger::write(format!("error in uninstalling GuestProxyAgent: {e:?}")); } } match str::from_utf8(&output.stderr) { Ok(output_string) => { logger::write(format!( - "output stderr for uninstall GuestProxyAgent: {}", - output_string + "output stderr for uninstall GuestProxyAgent: {output_string}" )); } Err(e) => { - logger::write(format!("error in uninstalling GuestProxyAgent: {:?}", e)); + logger::write(format!("error in uninstalling GuestProxyAgent: {e:?}")); } } } Err(e) => { - logger::write(format!("error in uninstalling GuestProxyAgent: {:?}", e)); + logger::write(format!("error in uninstalling GuestProxyAgent: {e:?}")); } } } @@ -240,7 +237,7 @@ async fn enable_handler(status_folder: PathBuf, config_seq_no: String) { } } Err(e) => { - logger::write(format!("error in updating current seq no: {:?}", e)); + logger::write(format!("error in updating current seq no: {e:?}")); process::exit(constants::EXIT_CODE_WRITE_CURRENT_SEQ_NO_ERROR); } } @@ -273,13 +270,12 @@ async fn enable_handler(status_folder: PathBuf, config_seq_no: String) { Ok(child) => { let pid = child.id(); logger::write(format!( - "ProxyAgentExt started with pid: {}, do not start new one.", - pid + "ProxyAgentExt started with pid: {pid}, do not start new one." )); break; } Err(e) => { - logger::write(format!("error in starting ProxyAgentExt: {:?}", e)); + logger::write(format!("error in starting ProxyAgentExt: {e:?}")); } } } @@ -294,7 +290,7 @@ async fn enable_handler(status_folder: PathBuf, config_seq_no: String) { "update tag file removed: {:?}", update_tag_file.to_path_buf() )), - Err(e) => logger::write(format!("error in removing update tag file: {:?}", e)), + Err(e) => logger::write(format!("error in removing update tag file: {e:?}")), } } } @@ -312,7 +308,7 @@ fn get_linux_extension_long_running_process() -> Option { for p in system.processes_by_exact_name(constants::EXTENSION_PROCESS_NAME) { let cmd = p.cmd(); - logger::write(format!("cmd: {:?}", cmd)); + logger::write(format!("cmd: {cmd:?}")); if cmd.len() == 1 { logger::write(format!("ProxyAgentExt running with pid: {}", p.pid())); return Some(p.pid().as_u32() as i32); @@ -334,10 +330,10 @@ async fn disable_handler() { let p = NixPid::from_raw(pid); match kill(p, SIGKILL) { Ok(_) => { - logger::write(format!("ProxyAgentExt process with pid: {} killed", pid)); + logger::write(format!("ProxyAgentExt process with pid: {pid} killed")); } Err(e) => { - logger::write(format!("error in killing ProxyAgentExt process: {:?}", e)); + logger::write(format!("error in killing ProxyAgentExt process: {e:?}")); } } } @@ -357,14 +353,14 @@ fn reset_handler() { "update tag file removed: {:?}", update_tag_file.to_path_buf() )), - Err(e) => logger::write(format!("error in removing update tag file: {:?}", e)), + Err(e) => logger::write(format!("error in removing update tag file: {e:?}")), } match fs::remove_file(&seq_no_file) { Ok(_) => logger::write(format!( "seq no file removed: {:?}", seq_no_file.to_path_buf() )), - Err(e) => logger::write(format!("error in removing seq no file: {:?}", e)), + Err(e) => logger::write(format!("error in removing seq no file: {e:?}")), } } @@ -374,7 +370,7 @@ async fn update_handler() { let version = match std::env::var("VERSION") { Ok(ver) => ver, Err(e) => { - logger::write(format!("error in getting VERSION from env::var: {:?}", e)); + logger::write(format!("error in getting VERSION from env::var: {e:?}")); process::exit(constants::EXIT_CODE_UPDATE_TO_VERSION_ENV_VAR_NOTFOUND); } }; @@ -403,7 +399,7 @@ async fn update_handler() { break; } Err(e) => { - logger::write(format!("error in creating update tag file: {:?}", e)); + logger::write(format!("error in creating update tag file: {e:?}")); } } } diff --git a/proxy_agent_extension/src/logger.rs b/proxy_agent_extension/src/logger.rs index 70c71c70..f12cec8e 100644 --- a/proxy_agent_extension/src/logger.rs +++ b/proxy_agent_extension/src/logger.rs @@ -23,7 +23,7 @@ pub fn init_logger(log_folder: String, log_name: &str) { if !LOGGER_KEY.initialized() { if let Err(e) = LOGGER_KEY.set(log_name.to_string()) { - eprintln!("Failed to set logger key: {}", e); + eprintln!("Failed to set logger key: {e}"); }; } } diff --git a/proxy_agent_extension/src/main.rs b/proxy_agent_extension/src/main.rs index d51bc835..0093e49b 100644 --- a/proxy_agent_extension/src/main.rs +++ b/proxy_agent_extension/src/main.rs @@ -86,7 +86,7 @@ async fn main() { #[cfg(windows)] { if let Err(e) = service_dispatcher::start(constants::PLUGIN_NAME, ffi_service_main) { - logger::write(format!("Failed to start the service: {}", e)); + logger::write(format!("Failed to start the service: {e}")); } } #[cfg(not(windows))] @@ -104,7 +104,7 @@ fn proxy_agent_extension_windows_service_main(args: Vec) { .expect("You must provide the Tokio runtime handle before this function is called"); handle.block_on(async { if let Err(e) = service_main::windows_main::run_service(args).await { - logger::write(format!("Failed to start the service: {}", e)); + logger::write(format!("Failed to start the service: {e}")); } }); } diff --git a/proxy_agent_extension/src/service_main.rs b/proxy_agent_extension/src/service_main.rs index 7bfe1763..2a28c9cb 100644 --- a/proxy_agent_extension/src/service_main.rs +++ b/proxy_agent_extension/src/service_main.rs @@ -99,8 +99,7 @@ async fn monitor_thread() { telemetry::event_logger::write_event( LoggerLevel::Info, format!( - "Current seq_no: {} does not match cached seq no {}", - current_seq_no, cache_seq_no + "Current seq_no: {current_seq_no} does not match cached seq no {cache_seq_no}" ), "monitor_thread", "service_main", @@ -125,9 +124,8 @@ async fn monitor_thread() { // Call setup tool to install or update proxy agent service telemetry::event_logger::write_event( LoggerLevel::Info, - format!("Version mismatch between file versions. ProxyAgentService File Version: {}, ProxyAgent in Extension File Version: {}", - proxyagent_service_file_version, - proxyagent_file_version_in_extension), + format!("Version mismatch between file versions. ProxyAgentService File Version: {proxyagent_service_file_version}, ProxyAgent in Extension File Version: {proxyagent_file_version_in_extension}" + ), "monitor_thread", "service_main", logger_key, @@ -301,7 +299,7 @@ fn backup_proxyagent(setup_tool: &String) { Err(e) => { telemetry::event_logger::write_event( LoggerLevel::Info, - format!("Error in running Backup Proxy Agent command: {}", e), + format!("Error in running Backup Proxy Agent command: {e}"), "backup_proxyagent", "service_main", &logger::get_logger_key(), @@ -345,8 +343,7 @@ fn report_proxy_agent_aggregate_status( ); } Err(e) => { - let error_message = - format!("Error in reading proxy agent aggregate status file: {}", e); + let error_message = format!("Error in reading proxy agent aggregate status file: {e}"); write_state_event( constants::STATE_KEY_READ_PROXY_AGENT_STATUS_FILE, constants::ERROR_STATUS, @@ -409,7 +406,7 @@ fn extension_substatus( proxy_agent_aggregate_status_obj.version.to_string(); if proxy_agent_aggregate_status_file_version != *proxyagent_file_version_in_extension { status.status = status_state_obj.update_state(false); - let version_mismatch_message = format!("Proxy agent aggregate status file version {} does not match proxy agent file version in extension {}", proxy_agent_aggregate_status_file_version, proxyagent_file_version_in_extension); + let version_mismatch_message = format!("Proxy agent aggregate status file version {proxy_agent_aggregate_status_file_version} does not match proxy agent file version in extension {proxyagent_file_version_in_extension}"); write_state_event( constants::STATE_KEY_FILE_VERSION, constants::ERROR_STATUS, @@ -459,7 +456,7 @@ fn extension_substatus( Ok(proxy_agent_aggregate_status) => proxy_agent_aggregate_status, Err(e) => { let error_message = - format!("Error in serializing proxy agent aggregate status: {}", e); + format!("Error in serializing proxy agent aggregate status: {e}"); logger::write(error_message.to_string()); error_message } @@ -482,8 +479,7 @@ fn extension_substatus( } Err(e) => { let error_message = format!( - "Error in serializing proxy agent aggregate connection status: {}", - e + "Error in serializing proxy agent aggregate connection status: {e}" ); logger::write(error_message.to_string()); substatus_proxy_agent_connection_message = error_message; @@ -511,8 +507,7 @@ fn extension_substatus( } Err(e) => { let error_message = format!( - "Error in serializing proxy agent aggregate failed auth status: {}", - e + "Error in serializing proxy agent aggregate failed auth status: {e}" ); logger::write(error_message.to_string()); substatus_failed_auth_message = error_message; @@ -631,7 +626,7 @@ fn restore_purge_proxyagent(status: &mut StatusObj) -> bool { Err(e) => { telemetry::event_logger::write_event( LoggerLevel::Info, - format!("Error in running Restore Proxy Agent command: {}", e), + format!("Error in running Restore Proxy Agent command: {e}"), "restore_purge_proxyagent", "service_main", &logger::get_logger_key(), @@ -663,7 +658,7 @@ fn restore_purge_proxyagent(status: &mut StatusObj) -> bool { Err(e) => { telemetry::event_logger::write_event( LoggerLevel::Info, - format!("Error in running Purge Proxy Agent command: {}", e), + format!("Error in running Purge Proxy Agent command: {e}"), "restore_purge_proxyagent", "service_main", &logger::get_logger_key(), @@ -724,7 +719,7 @@ fn report_proxy_agent_service_status( Err(e) => { telemetry::event_logger::write_event( LoggerLevel::Info, - format!("Error in running Update Proxy Agent command: {}", e), + format!("Error in running Update Proxy Agent command: {e}"), "report_proxy_agent_service_status", "service_main", &logger::get_logger_key(), @@ -734,7 +729,7 @@ fn report_proxy_agent_service_status( status.code = constants::STATUS_CODE_NOT_OK; status.status = status_state_obj.update_state(false); status.formattedMessage.message = - format!("Update Proxy Agent command failed with error: {}", e); + format!("Update Proxy Agent command failed with error: {e}"); status.substatus = Default::default(); common::report_status(status_folder, seq_no, status); } diff --git a/proxy_agent_extension/src/service_main/windows_main.rs b/proxy_agent_extension/src/service_main/windows_main.rs index 9441eb6a..a793cf72 100644 --- a/proxy_agent_extension/src/service_main/windows_main.rs +++ b/proxy_agent_extension/src/service_main/windows_main.rs @@ -36,7 +36,7 @@ pub async fn run_service(_args: Vec) -> Result<()> { process_id: None, }; if let Err(e) = status_handle.set_service_status(stop_state) { - logger::write(format!("Failed to set service status to Stopped: {}", e)); + logger::write(format!("Failed to set service status to Stopped: {e}")); } } else { // workaround to stop the service by exiting the process diff --git a/proxy_agent_setup/src/args.rs b/proxy_agent_setup/src/args.rs index 8ab2a66c..16cdfcce 100644 --- a/proxy_agent_setup/src/args.rs +++ b/proxy_agent_setup/src/args.rs @@ -48,9 +48,9 @@ impl Display for Command { match self { Command::Backup => write!(f, "backup"), Command::Restore { delete_backup } => { - write!(f, "restore delete_backup={}", delete_backup) + write!(f, "restore delete_backup={delete_backup}") } - Command::Uninstall { uninstall_mode } => write!(f, "uninstall {}", uninstall_mode), + Command::Uninstall { uninstall_mode } => write!(f, "uninstall {uninstall_mode}"), Command::Install => write!(f, "install"), Command::Purge => write!(f, "purge"), } diff --git a/proxy_agent_setup/src/linux.rs b/proxy_agent_setup/src/linux.rs index ea71de3d..70921167 100644 --- a/proxy_agent_setup/src/linux.rs +++ b/proxy_agent_setup/src/linux.rs @@ -17,7 +17,7 @@ pub fn setup_service(service_name: &str, service_file_dir: PathBuf) -> Result Result { - let service_config_name = format!("{}.service", service_name); + let service_config_name = format!("{service_name}.service"); let src_config_file_path = service_file_dir.join(&service_config_name); let dst_config_file_path = PathBuf::from(proxy_agent_shared::linux::SERVICE_CONFIG_FOLDER_PATH) .join(&service_config_name); @@ -33,14 +33,12 @@ fn backup_service_config_file(backup_folder: PathBuf) { ) { Ok(_) => { logger::write(format!( - "Copied service config file to {:?}", - backup_service_file + "Copied service config file to {backup_service_file:?}" )); } Err(e) => { logger::write(format!( - "Failed to copy service config file to {:?}, error: {:?}", - backup_service_file, e + "Failed to copy service config file to {backup_service_file:?}, error: {e:?}" )); } } @@ -49,17 +47,16 @@ fn backup_service_config_file(backup_folder: PathBuf) { fn copy_file(src_file: PathBuf, dst_file: PathBuf) { if let Some(p) = dst_file.parent() { if let Err(e) = misc_helpers::try_create_folder(p) { - logger::write(format!("Failed to create folder {:?}, error: {:?}", p, e)); + logger::write(format!("Failed to create folder {p:?}, error: {e:?}")); } } match fs::copy(&src_file, &dst_file) { Ok(_) => { - logger::write(format!("Copied file {:?} to {:?}", src_file, dst_file)); + logger::write(format!("Copied file {src_file:?} to {dst_file:?}")); } Err(e) => { logger::write(format!( - "Failed to copy file {:?} to {:?}, error: {:?}", - src_file, dst_file, e + "Failed to copy file {src_file:?} to {dst_file:?}, error: {e:?}" )); } } @@ -68,12 +65,11 @@ fn copy_file(src_file: PathBuf, dst_file: PathBuf) { fn delete_file(file_to_be_delete: PathBuf) { match fs::remove_file(&file_to_be_delete) { Ok(_) => { - logger::write(format!("Deleted file {:?}", file_to_be_delete)); + logger::write(format!("Deleted file {file_to_be_delete:?}")); } Err(e) => { logger::write(format!( - "Failed to delete file {:?}, error: {:?}", - file_to_be_delete, e + "Failed to delete file {file_to_be_delete:?}, error: {e:?}" )); } } diff --git a/proxy_agent_setup/src/logger.rs b/proxy_agent_setup/src/logger.rs index 11b7404c..7c870ec6 100644 --- a/proxy_agent_setup/src/logger.rs +++ b/proxy_agent_setup/src/logger.rs @@ -19,6 +19,6 @@ fn force_init_logger(log_folder: PathBuf, log_name: &str) { } pub fn write(message: String) { - println!("{}", message); + println!("{message}"); logger_manager::log(LOGGER_KEY.to_string(), LoggerLevel::Info, message); } diff --git a/proxy_agent_setup/src/main.rs b/proxy_agent_setup/src/main.rs index 02707190..17cdac12 100644 --- a/proxy_agent_setup/src/main.rs +++ b/proxy_agent_setup/src/main.rs @@ -127,8 +127,7 @@ fn copy_proxy_agent_files(src_folder: PathBuf, dst_folder: PathBuf) { Ok(_) => {} Err(e) => { logger::write(format!( - "Failed to create folder {:?}, error: {:?}", - dst_folder, e + "Failed to create folder {dst_folder:?}, error: {e:?}" )); } } @@ -139,12 +138,11 @@ fn copy_proxy_agent_files(src_folder: PathBuf, dst_folder: PathBuf) { let dst_file = dst_folder.join(&file_name); match fs::copy(&file, &dst_file) { Ok(_) => { - logger::write(format!("Copied {:?} to {:?}", file, dst_file)); + logger::write(format!("Copied {file:?} to {dst_file:?}")); } Err(e) => { logger::write(format!( - "Failed to copy {:?} to {:?}, error: {:?}", - file, dst_file, e + "Failed to copy {file:?} to {dst_file:?}, error: {e:?}" )); } } @@ -152,8 +150,7 @@ fn copy_proxy_agent_files(src_folder: PathBuf, dst_folder: PathBuf) { } Err(e) => { logger::write(format!( - "Failed to get files from {:?}, error: {:?}", - src_folder, e + "Failed to get files from {src_folder:?}, error: {e:?}" )); } } @@ -162,12 +159,11 @@ fn copy_proxy_agent_files(src_folder: PathBuf, dst_folder: PathBuf) { async fn stop_service() { match service::stop_service(SERVICE_NAME).await { Ok(_) => { - logger::write(format!("Stopped service {} successfully", SERVICE_NAME)); + logger::write(format!("Stopped service {SERVICE_NAME} successfully")); } Err(e) => { logger::write(format!( - "Stopped service {} failed, error: {:?}", - SERVICE_NAME, e + "Stopped service {SERVICE_NAME} failed, error: {e:?}" )); } } @@ -188,13 +184,10 @@ async fn setup_service(proxy_agent_target_folder: PathBuf, _service_config_folde { match linux::setup_service(SERVICE_NAME, _service_config_folder_path) { Ok(_) => { - logger::write(format!("Setup service {} successfully", SERVICE_NAME)); + logger::write(format!("Setup service {SERVICE_NAME} successfully")); } Err(e) => { - logger::write(format!( - "Setup service {} failed, error: {:?}", - SERVICE_NAME, e - )); + logger::write(format!("Setup service {SERVICE_NAME} failed, error: {e:?}")); process::exit(1); } } @@ -207,12 +200,11 @@ async fn setup_service(proxy_agent_target_folder: PathBuf, _service_config_folde setup::proxy_agent_exe_path(&proxy_agent_target_folder), ) { Ok(_) => { - logger::write(format!("Install service {} successfully", SERVICE_NAME)); + logger::write(format!("Install service {SERVICE_NAME} successfully")); } Err(e) => { logger::write(format!( - "Install service {} failed, error: {:?}", - SERVICE_NAME, e + "Install service {SERVICE_NAME} failed, error: {e:?}", )); process::exit(1); } @@ -243,8 +235,7 @@ async fn setup_service(proxy_agent_target_folder: PathBuf, _service_config_folde } Err(e) => { logger::write(format!( - "ebpf_setup: failed to invoke script file '{}', error: '{:?}'.", - setup_script_file_str, e + "ebpf_setup: failed to invoke script file '{setup_script_file_str}', error: '{e:?}'." )); } } @@ -253,25 +244,21 @@ async fn setup_service(proxy_agent_target_folder: PathBuf, _service_config_folde match service::start_service(SERVICE_NAME, 5, Duration::from_secs(15)).await { Ok(_) => { - logger::write(format!("Service {} start successfully", SERVICE_NAME)); + logger::write(format!("Service {SERVICE_NAME} start successfully")); } Err(e) => { - logger::write(format!( - "Service {} start failed, error: {:?}", - SERVICE_NAME, e - )); + logger::write(format!("Service {SERVICE_NAME} start failed, error: {e:?}")); process::exit(1); } } - logger::write(format!("Service {} start successfully", SERVICE_NAME)); + logger::write(format!("Service {SERVICE_NAME} start successfully")); } fn check_backup_exists() -> bool { let proxy_agent_exe = setup::proxy_agent_exe_path(&backup::proxy_agent_backup_package_folder()); if !proxy_agent_exe.exists() { logger::write(format!( - "GuestProxyAgent ({:?}) does not exists.", - proxy_agent_exe + "GuestProxyAgent ({proxy_agent_exe:?}) does not exists." )); return false; } @@ -284,12 +271,11 @@ async fn uninstall_service() -> PathBuf { match service::stop_and_delete_service(SERVICE_NAME).await { Ok(_) => { - logger::write(format!("Uninstall service {} successfully", SERVICE_NAME)); + logger::write(format!("Uninstall service {SERVICE_NAME} successfully")); } Err(e) => { logger::write(format!( - "Uninstall service {} failed, error: {:?}", - SERVICE_NAME, e + "Uninstall service {SERVICE_NAME} failed, error: {e:?}" )); process::exit(1); } @@ -312,12 +298,11 @@ fn delete_package(_proxy_agent_running_folder: PathBuf) { fn delete_folder(folder_to_be_delete: PathBuf) { match fs::remove_dir_all(&folder_to_be_delete) { Ok(_) => { - logger::write(format!("Deleted folder {:?}", folder_to_be_delete)); + logger::write(format!("Deleted folder {folder_to_be_delete:?}")); } Err(e) => { logger::write(format!( - "Failed to delete folder {:?}, error: {:?}", - folder_to_be_delete, e + "Failed to delete folder {folder_to_be_delete:?}, error: {e:?}" )); } } diff --git a/proxy_agent_setup/src/running.rs b/proxy_agent_setup/src/running.rs index ee0ca188..93905cb8 100644 --- a/proxy_agent_setup/src/running.rs +++ b/proxy_agent_setup/src/running.rs @@ -41,18 +41,15 @@ pub fn proxy_agent_version_target_folder(proxy_agent_exe: &Path) -> PathBuf { Ok(v) => v, Err(e) => { // This should not happen, if failed to get version, we should not proceed - logger::write(format!( - "Failed to get proxy agent version with error: {}", - e - )); - panic!("Failed to get proxy agent version with error: {}", e); + logger::write(format!("Failed to get proxy agent version with error: {e}")); + panic!("Failed to get proxy agent version with error: {e}"); } }; logger::write(format!("Proxy agent version: {}", &proxy_agent_version)); #[cfg(windows)] { let path = proxy_agent_parent_folder(); - path.join(format!("Package_{}", proxy_agent_version)) + path.join(format!("Package_{proxy_agent_version}")) } #[cfg(not(windows))] { diff --git a/proxy_agent_shared/src/etw/application.rs b/proxy_agent_shared/src/etw/application.rs index 22221e7d..364e4ff7 100644 --- a/proxy_agent_shared/src/etw/application.rs +++ b/proxy_agent_shared/src/etw/application.rs @@ -58,10 +58,8 @@ impl ApplicationEventWritter { // register event source in the Windows Registry // `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\{source_name}` - let key_name = format!( - r"SYSTEM\CurrentControlSet\Services\EventLog\Application\{}", - source_name - ); + let key_name = + format!(r"SYSTEM\CurrentControlSet\Services\EventLog\Application\{source_name}"); let value = crate::misc_helpers::resolve_env_variables( r"%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll", )?; @@ -326,6 +324,10 @@ mod tests { if event.system.provider.name == Some(self.source_name.clone()) { // Check if the event is within the specified time range let time_created = event.system.time_created.system_time.clone(); + println!( + "Event '{}' Time Created: {:?}", + self.source_name, time_created + ); if let Some(start_time) = self.start_time { match time_created.clone() { Some(time) => { @@ -380,7 +382,9 @@ mod tests { use super::ApplicationEventWritter; use crate::logger::LoggerLevel; - let start_time = chrono::Utc::now(); + // According to the test log, it indicates that Windows Container may have few milliseconds difference against its current host time. + // Therefore, we set the start time to 1 second before the current time. + let start_time = chrono::Utc::now() - chrono::Duration::seconds(1); let end_time = start_time + chrono::Duration::seconds(60); let source_name = "GuestProxyAgent_TestApplication"; diff --git a/proxy_agent_shared/src/linux.rs b/proxy_agent_shared/src/linux.rs index ac75187e..138d8782 100644 --- a/proxy_agent_shared/src/linux.rs +++ b/proxy_agent_shared/src/linux.rs @@ -47,8 +47,7 @@ pub fn get_os_version() -> String { } Err(e) => { let message = format!( - "Failed to read os-release file in get_os_version(): {} with error: {}", - OS_RELEASE_PATH, e + "Failed to read os-release file in get_os_version(): {OS_RELEASE_PATH} with error: {e}", ); logger_manager::write_warn(message); return "Unknown".to_string(); @@ -78,8 +77,7 @@ pub fn get_os_type() -> String { } Err(e) => { let message = format!( - "Failed to read os-release file in get_os_type(): {} with error: {}", - OS_RELEASE_PATH, e + "Failed to read os-release file in get_os_type(): {OS_RELEASE_PATH} with error: {e}", ); logger_manager::write_warn(message); return "Unknown".to_string(); diff --git a/proxy_agent_shared/src/logger/logger_manager.rs b/proxy_agent_shared/src/logger/logger_manager.rs index 61dff8bb..a989a4a6 100644 --- a/proxy_agent_shared/src/logger/logger_manager.rs +++ b/proxy_agent_shared/src/logger/logger_manager.rs @@ -40,7 +40,7 @@ pub fn set_loggers( if let Err(e) = MAX_LOG_LEVEL.set(max_log_level) { write_system_log( LoggerLevel::Error, - format!("Failed to set logger level: {}", e), + format!("Failed to set logger level: {e}"), ); } } @@ -55,12 +55,12 @@ pub fn set_loggers( // set the loggers once if let Err(e) = LOGGERS.set(loggers) { - write_system_log(LoggerLevel::Error, format!("Failed to set loggers: {}", e)); + write_system_log(LoggerLevel::Error, format!("Failed to set loggers: {e}")); }; if let Err(e) = DEFAULT_LOGGER_KEY.set(default_logger_key) { write_system_log( LoggerLevel::Error, - format!("Failed to set default logger key: {}", e), + format!("Failed to set default logger key: {e}"), ); } } @@ -74,14 +74,14 @@ pub fn set_system_logger(max_log_level: LoggerLevel, _service_name: &str) { if let Err(e) = WINDOWS_ETW_APPLICATION_LOGGER.set(logger) { write_system_log( LoggerLevel::Error, - format!("Failed to set Windows Application ETW logger: {}", e), + format!("Failed to set Windows Application ETW logger: {e}"), ); } } Err(e) => { write_system_log( LoggerLevel::Error, - format!("Failed to create Windows Application ETW logger: {}", e), + format!("Failed to create Windows Application ETW logger: {e}"), ); } } @@ -92,7 +92,7 @@ pub fn set_system_logger(max_log_level: LoggerLevel, _service_name: &str) { if let Err(e) = MAX_SYSTEM_LOG_LEVEL.set(max_log_level) { write_system_log( LoggerLevel::Error, - format!("Failed to set system logger level: {}", e), + format!("Failed to set system logger level: {e}"), ); } } @@ -128,7 +128,7 @@ fn internal_log(logger_key: Option, log_level: LoggerLevel, message: Str if let Some(logger) = get_logger(logger_key) { if let Err(e) = logger.write(log_level, message) { - eprintln!("Error writing to log: {}", e); + eprintln!("Error writing to log: {e}"); } } } @@ -156,7 +156,7 @@ pub fn write_err(message: String) { pub fn write_many(logger_key: Option, messages: Vec) { if let Some(logger) = get_logger(logger_key) { if let Err(e) = logger.write_many(messages) { - eprintln!("Error writing to log: {}", e); + eprintln!("Error writing to log: {e}"); } } } @@ -168,9 +168,9 @@ fn write_system_log(log_level: LoggerLevel, message: String) { // Linux automatically captures console logs to syslog. if log_level == LoggerLevel::Error { - eprintln!("{}", message); + eprintln!("{message}",); } else { - println!("{}", message); + println!("{message}",); } #[cfg(windows)] diff --git a/proxy_agent_shared/src/misc_helpers.rs b/proxy_agent_shared/src/misc_helpers.rs index fd304656..149b2188 100644 --- a/proxy_agent_shared/src/misc_helpers.rs +++ b/proxy_agent_shared/src/misc_helpers.rs @@ -268,13 +268,13 @@ pub fn get_proxy_agent_version(proxy_agent_exe: &Path) -> Result { if !proxy_agent_exe.exists() { return Err(Error::Io(std::io::Error::new( std::io::ErrorKind::NotFound, - format!("File '{}' does not found", proxy_agent_exe_str), + format!("File '{proxy_agent_exe_str}' does not found"), ))); } if !proxy_agent_exe.is_file() { return Err(Error::Io(std::io::Error::new( std::io::ErrorKind::InvalidInput, - format!("'{}' is not a file", proxy_agent_exe_str), + format!("'{proxy_agent_exe_str}' is not a file"), ))); } diff --git a/proxy_agent_shared/src/service.rs b/proxy_agent_shared/src/service.rs index 0cd0f1b1..5ca4b892 100644 --- a/proxy_agent_shared/src/service.rs +++ b/proxy_agent_shared/src/service.rs @@ -99,18 +99,14 @@ pub fn query_service_executable_path(_service_name: &str) -> PathBuf { { match windows_service::query_service_config(_service_name) { Ok(service_config) => { - logger_manager::write_info(format!( - "Service {} successfully queried", - _service_name - )); + logger_manager::write_info( + format!("Service {_service_name} successfully queried",), + ); service_config.executable_path.to_path_buf() } Err(e) => { - logger_manager::write_info(format!( - "Service {} query failed: {}", - _service_name, e - )); - eprintln!("Service {} query failed: {}", _service_name, e); + logger_manager::write_info(format!("Service {_service_name} query failed: {e}",)); + eprintln!("Service {_service_name} query failed: {e}"); PathBuf::new() } } @@ -129,14 +125,13 @@ pub fn check_service_installed(_service_name: &str) -> (bool, String) { match windows_service::query_service_config(_service_name) { Ok(_service_config) => { message = format!( - "check_service_installed: Ebpf Driver: {} successfully queried.", - _service_name + "check_service_installed: Ebpf Driver: {_service_name} successfully queried.", ); (true, message) } Err(e) => { message = format!( - "check_service_installed: Ebpf Driver: {} unsuccessfully queried with error: {}.", _service_name, e + "check_service_installed: Ebpf Driver: {_service_name} unsuccessfully queried with error: {e}" ); (false, message) } diff --git a/proxy_agent_shared/src/service/linux_service.rs b/proxy_agent_shared/src/service/linux_service.rs index a27144b1..84efd3e8 100644 --- a/proxy_agent_shared/src/service/linux_service.rs +++ b/proxy_agent_shared/src/service/linux_service.rs @@ -79,7 +79,7 @@ fn enable_service(service_name: &str) -> Result<()> { fn delete_service_config_file(service_name: &str) -> Result<()> { let config_file_path = - PathBuf::from(linux::SERVICE_CONFIG_FOLDER_PATH).join(format!("{}.service", service_name)); + PathBuf::from(linux::SERVICE_CONFIG_FOLDER_PATH).join(format!("{service_name}.service")); match fs::remove_file(&config_file_path) { Ok(_) => { reload_systemd_daemon()?; diff --git a/proxy_agent_shared/src/service/windows_service.rs b/proxy_agent_shared/src/service/windows_service.rs index fcdef742..975e7803 100644 --- a/proxy_agent_shared/src/service/windows_service.rs +++ b/proxy_agent_shared/src/service/windows_service.rs @@ -21,14 +21,13 @@ pub async fn start_service_with_retry( duration: std::time::Duration, ) -> Result<()> { for i in 0..retry_count { - logger_manager::write_info(format!("Starting service {} attempt {}", service_name, i)); + logger_manager::write_info(format!("Starting service '{service_name}' attempt {i}")); match start_service_once(service_name).await { Ok(service) => { if service.current_state == ServiceState::Running { logger_manager::write_info(format!( - "Service {} is at Running state", - service_name + "Service '{service_name}' is at Running state" )); return Ok(()); } @@ -43,19 +42,13 @@ pub async fn start_service_with_retry( } Err(e) => { logger_manager::write_warn( - format!( - "Extension service {} start failed with error: {}", - service_name, e - ) - .to_string(), + format!("Extension service '{service_name}' start failed with error: {e}") + .to_string(), ); if (i + 1) == retry_count { logger_manager::write_err( - format!( - "Service {} failed to start after {} attempts", - service_name, i - ) - .to_string(), + format!("Service '{service_name}' failed to start after {i} attempts") + .to_string(), ); return Err(e); } @@ -70,10 +63,10 @@ async fn start_service_once(service_name: &str) -> Result { // Start service if it already isn't running let service = query_service_status(service_name)?; if service.current_state == ServiceState::Running { - logger_manager::write_info(format!("Service '{}' is already running", service_name)); + logger_manager::write_info(format!("Service '{service_name}' is already running")); Ok(service) } else { - logger_manager::write_info(format!("Starting service '{}'", service_name)); + logger_manager::write_info(format!("Starting service '{service_name}'")); let service_manager: ServiceManager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT) .map_err(|e| Error::WindowsService(e, std::io::Error::last_os_error()))?; @@ -122,8 +115,7 @@ pub async fn stop_service(service_name: &str) -> Result { } Err(e) => { logger_manager::write_info(format!( - "Stopped service {} failed, error: {:?}", - service_name, e + "Stopped service {service_name} failed, error: {e:?}" )); } } diff --git a/proxy_agent_shared/src/telemetry/event_logger.rs b/proxy_agent_shared/src/telemetry/event_logger.rs index 3af4d8ef..6d7ea3a9 100644 --- a/proxy_agent_shared/src/telemetry/event_logger.rs +++ b/proxy_agent_shared/src/telemetry/event_logger.rs @@ -33,7 +33,7 @@ pub async fn start( logger_manager::write_log(Level::Info, message.to_string()); if let Err(e) = misc_helpers::try_create_folder(&event_dir) { - let message = format!("Failed to create event folder with error: {}", e); + let message = format!("Failed to create event folder with error: {e}"); set_status_fn(message.to_string()); } @@ -75,9 +75,8 @@ pub async fn start( match misc_helpers::get_files(&event_dir) { Ok(files) => { if files.len() >= max_event_file_count { - logger_manager::write_log( Level::Warn,format!( - "Event files exceed the max file count {}, drop and skip the write to disk.", - max_event_file_count + logger_manager::write_log(Level::Warn, format!( + "Event files exceed the max file count {max_event_file_count}, drop and skip the write to disk." )); continue; } @@ -85,7 +84,7 @@ pub async fn start( Err(e) => { logger_manager::write_log( Level::Warn, - format!("Failed to get event files with error: {}", e), + format!("Failed to get event files with error: {e}"), ); } } @@ -150,7 +149,7 @@ pub fn write_event_only(level: Level, message: String, method_name: &str, module Err(e) => { logger_manager::write_log( Level::Warn, - format!("Failed to push event to the queue with error: {}", e), + format!("Failed to push event to the queue with error: {e}"), ); } }; diff --git a/proxy_agent_shared/src/version.rs b/proxy_agent_shared/src/version.rs index 2d543116..f01c5388 100644 --- a/proxy_agent_shared/src/version.rs +++ b/proxy_agent_shared/src/version.rs @@ -85,14 +85,14 @@ impl Display for Version { let mut ver = format!("{}.{}", self.major, self.minor); if let Some(b) = self.build { - ver = format!("{}.{}", ver, b); + ver = format!("{ver}.{b}"); if let Some(r) = self.revision { - ver = format!("{}.{}", ver, r); + ver = format!("{ver}.{r}"); } } - write!(f, "{}", ver) + write!(f, "{ver}") } } diff --git a/proxy_agent_shared/src/windows.rs b/proxy_agent_shared/src/windows.rs index aa35ede6..83eb9171 100644 --- a/proxy_agent_shared/src/windows.rs +++ b/proxy_agent_shared/src/windows.rs @@ -26,11 +26,11 @@ fn read_reg_int(key_name: &str, value_name: &str, default_value: Option) -> Ok(key) => match key.get_value(value_name) { Ok(val) => return Some(val), Err(e) => { - print!("{}", e); + print!("{e}"); } }, Err(e) => { - print!("{}", e); + print!("{e}"); } } @@ -87,7 +87,7 @@ pub fn get_os_version() -> Result { Ok(u) => major = u, Err(_) => { return Err(Error::ParseVersion(ParseVersionErrorType::MajorBuild( - format!("{} ({})", major_str, CURRENT_MAJOR_VERSION_NUMBER_STRING), + format!("{major_str} ({CURRENT_MAJOR_VERSION_NUMBER_STRING})"), ))); } } @@ -111,7 +111,7 @@ pub fn get_os_version() -> Result { Ok(u) => minor = u, Err(_) => { return Err(Error::ParseVersion(ParseVersionErrorType::MinorBuild( - format!("{} ({})", major_str, CURRENT_MINOR_VERSION_NUMBER_STRING), + format!("{major_str} ({CURRENT_MINOR_VERSION_NUMBER_STRING})"), ))); } } @@ -315,10 +315,7 @@ pub fn get_file_product_version(file_path: &Path) -> Result { } if fixed_file_info_size != std::mem::size_of::() as u32 { return Err(Error::ParseVersion(ParseVersionErrorType::InvalidString( - format!( - "Invalid VS_FIXEDFILEINFO size '{}' returned", - fixed_file_info_size - ), + format!("Invalid VS_FIXEDFILEINFO size '{fixed_file_info_size}' returned"), ))); }