diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index fdb1c33..14fe6f5 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -464,6 +464,7 @@ impl OutboundManager { settings.health_check_active, settings.health_check_prefers.clone(), settings.health_check_on_start, + settings.health_check_wait, dns_client.clone(), ); let (datagram, mut datagram_abort_handles) = failover::DatagramHandler::new( @@ -478,6 +479,7 @@ impl OutboundManager { settings.health_check_active, settings.health_check_prefers, settings.health_check_on_start, + settings.health_check_wait, dns_client.clone(), ); let handler = HandlerBuilder::default() diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index 3e43ab1..fc09fb6 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -134,6 +134,7 @@ pub struct ProxyGroup { pub health_check_active: Option, pub health_check_prefers: Option>, pub health_check_on_start: Option, + pub health_check_wait: Option, // tryall pub delay_base: Option, @@ -161,6 +162,7 @@ impl Default for ProxyGroup { health_check_active: None, health_check_prefers: None, health_check_on_start: None, + health_check_wait: None, delay_base: None, method: None, } @@ -620,6 +622,10 @@ pub fn from_lines(lines: Vec>) -> Result { group.health_check_on_start = if v == "true" { Some(true) } else { Some(false) }; } + "health-check-wait" => { + group.health_check_wait = + if v == "true" { Some(true) } else { Some(false) }; + } "delay-base" => { let i = if let Ok(i) = v.parse() { Some(i) } else { None }; group.delay_base = i; @@ -1310,6 +1316,7 @@ pub fn to_internal(conf: &mut Config) -> Result { } settings.health_check_on_start = ext_proxy_group.health_check_on_start.unwrap_or(false); + settings.health_check_wait = ext_proxy_group.health_check_wait.unwrap_or(false); let settings = settings.write_to_bytes().unwrap(); outbound.settings = settings; outbounds.push(outbound); diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index a01406a..6abb20f 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -201,6 +201,9 @@ message FailOverOutboundSettings { // Health check would run on start if this is true, by default health check would // start to run when the first request comes in. Default is false. bool health_check_on_start = 14; + // Hold incomming connections, wait for the initial health check to be done. + // Default false. + bool health_check_wait = 15; } message SelectOutboundSettings { diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index 64b9b63..10059e3 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -3220,6 +3220,8 @@ pub struct FailOverOutboundSettings { pub health_check_prefers: ::std::vec::Vec<::std::string::String>, // @@protoc_insertion_point(field:FailOverOutboundSettings.health_check_on_start) pub health_check_on_start: bool, + // @@protoc_insertion_point(field:FailOverOutboundSettings.health_check_wait) + pub health_check_wait: bool, // special fields // @@protoc_insertion_point(special_field:FailOverOutboundSettings.special_fields) pub special_fields: ::protobuf::SpecialFields, @@ -3289,6 +3291,9 @@ impl ::protobuf::Message for FailOverOutboundSettings { 112 => { self.health_check_on_start = is.read_bool()?; }, + 120 => { + self.health_check_wait = is.read_bool()?; + }, tag => { ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, @@ -3343,6 +3348,9 @@ impl ::protobuf::Message for FailOverOutboundSettings { if self.health_check_on_start != false { my_size += 1 + 1; } + if self.health_check_wait != false { + my_size += 1 + 1; + } my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields()); self.special_fields.cached_size().set(my_size as u32); my_size @@ -3391,6 +3399,9 @@ impl ::protobuf::Message for FailOverOutboundSettings { if self.health_check_on_start != false { os.write_bool(14, self.health_check_on_start)?; } + if self.health_check_wait != false { + os.write_bool(15, self.health_check_wait)?; + } os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } @@ -3422,6 +3433,7 @@ impl ::protobuf::Message for FailOverOutboundSettings { self.health_check_active = 0; self.health_check_prefers.clear(); self.health_check_on_start = false; + self.health_check_wait = false; self.special_fields.clear(); } @@ -3441,6 +3453,7 @@ impl ::protobuf::Message for FailOverOutboundSettings { health_check_active: 0, health_check_prefers: ::std::vec::Vec::new(), health_check_on_start: false, + health_check_wait: false, special_fields: ::protobuf::SpecialFields::new(), }; &instance diff --git a/leaf/src/config/json/config.rs b/leaf/src/config/json/config.rs index 684452d..6f7a035 100644 --- a/leaf/src/config/json/config.rs +++ b/leaf/src/config/json/config.rs @@ -216,6 +216,8 @@ pub struct FailOverOutboundSettings { pub check_interval: Option, #[serde(rename = "healthCheckOnStart")] pub health_check_on_start: Option, + #[serde(rename = "healthCheckWait")] + pub health_check_wait: Option, pub failover: Option, #[serde(rename = "fallbackCache")] pub fallback_cache: Option, @@ -807,6 +809,7 @@ pub fn to_internal(json: &mut Config) -> Result { } settings.health_check_on_start = ext_settings.health_check_on_start.unwrap_or(false); + settings.health_check_wait = ext_settings.health_check_wait.unwrap_or(false); settings.check_interval = ext_settings.check_interval.unwrap_or(300); // 300 secs settings.failover = ext_settings.failover.unwrap_or(true); settings.fallback_cache = ext_settings.fallback_cache.unwrap_or(false); diff --git a/leaf/src/proxy/failover/datagram.rs b/leaf/src/proxy/failover/datagram.rs index 6307faa..6bb2ce8 100644 --- a/leaf/src/proxy/failover/datagram.rs +++ b/leaf/src/proxy/failover/datagram.rs @@ -1,10 +1,11 @@ +use std::sync::atomic::{AtomicBool, Ordering}; use std::{io, sync::Arc, time::Duration}; use async_trait::async_trait; use futures::future::BoxFuture; use futures::future::{abortable, AbortHandle}; use futures::FutureExt; -use tokio::sync::Mutex; +use tokio::sync::{Mutex, Notify}; use tokio::time::Instant; use tracing::{debug, trace}; @@ -18,6 +19,9 @@ pub struct Handler { last_resort: Option, dns_client: SyncDnsClient, last_active: Arc>, + health_check: bool, + is_first_health_check_done: Arc, + wait_for_health_check: Option>, } impl Handler { @@ -33,13 +37,20 @@ impl Handler { health_check_active: u32, health_check_prefers: Vec, health_check_on_start: bool, + health_check_wait: bool, dns_client: SyncDnsClient, ) -> (Self, Vec) { let mut abort_handles = Vec::new(); let schedule = Arc::new(Mutex::new((0..actors.len()).collect())); let last_active = Arc::new(Mutex::new(Instant::now())); + let is_first_health_check_done = Arc::new(AtomicBool::new(false)); - let health_check_task = if health_check { + let (health_check_task, wait_for_health_check) = if health_check { + let notify = if health_check_wait { + Some(Arc::new(Notify::new())) + } else { + None + }; let (abortable, abort_handle) = abortable(super::health_check_task( Network::Udp, schedule.clone(), @@ -53,17 +64,19 @@ impl Handler { health_check_active, health_check_prefers, last_active.clone(), + is_first_health_check_done.clone(), + notify.as_ref().cloned(), )); abort_handles.push(abort_handle); let task: BoxFuture<'static, ()> = Box::pin(abortable.map(|_| ())); if health_check_on_start { tokio::spawn(task); - Mutex::new(None) + (Mutex::new(None), notify) } else { - Mutex::new(Some(task)) + (Mutex::new(Some(task)), notify) } } else { - Mutex::new(None) + (Mutex::new(None), None) }; ( @@ -75,6 +88,9 @@ impl Handler { last_resort, dns_client, last_active, + health_check, + is_first_health_check_done, + wait_for_health_check, }, abort_handles, ) @@ -102,6 +118,14 @@ impl OutboundDatagramHandler for Handler { tokio::spawn(task); } + if self.health_check && !self.is_first_health_check_done.load(Ordering::Relaxed) { + if let Some(w) = self.wait_for_health_check.as_ref() { + debug!("holding {}", &sess.destination); + w.notified().await; + debug!("{} resumed", &sess.destination); + } + } + let schedule = self.schedule.lock().await.clone(); // Use the last resort outbound if all outbounds have failed in diff --git a/leaf/src/proxy/failover/mod.rs b/leaf/src/proxy/failover/mod.rs index 1bce92d..7298f6e 100644 --- a/leaf/src/proxy/failover/mod.rs +++ b/leaf/src/proxy/failover/mod.rs @@ -1,10 +1,11 @@ use std::str::FromStr; +use std::sync::atomic::{AtomicBool, Ordering}; use std::{sync::Arc, time::Duration}; use bytes::BytesMut; use rand::{rngs::StdRng, Rng, SeedableRng}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::sync::Mutex; +use tokio::sync::{Mutex, Notify}; use tokio::time::{timeout, Instant}; use tracing::{debug, trace, warn}; use trust_dns_proto::{ @@ -190,6 +191,8 @@ pub(self) async fn health_check_task( health_check_active: u32, health_check_prefers: Vec, last_active: Arc>, + is_first_health_check_done: Arc, + wait_for_health_check: Option>, ) { loop { let last_active = Instant::now() @@ -314,6 +317,14 @@ pub(self) async fn health_check_task( debug!("skip health check as no activities in {}s", last_active); } + if !is_first_health_check_done.swap(true, Ordering::Relaxed) { + debug!("initial health check done"); + if let Some(w) = wait_for_health_check.as_ref() { + debug!("notify holding connections"); + w.notify_waiters(); + } + } + tokio::time::sleep(Duration::from_secs(check_interval as u64)).await; } } diff --git a/leaf/src/proxy/failover/stream.rs b/leaf/src/proxy/failover/stream.rs index e4c03c0..8671b28 100644 --- a/leaf/src/proxy/failover/stream.rs +++ b/leaf/src/proxy/failover/stream.rs @@ -1,3 +1,4 @@ +use std::sync::atomic::{AtomicBool, Ordering}; use std::{io, sync::Arc, time::Duration}; use async_trait::async_trait; @@ -5,7 +6,7 @@ use futures::future::BoxFuture; use futures::future::{abortable, AbortHandle}; use futures::FutureExt; use lru_time_cache::LruCache; -use tokio::sync::Mutex; +use tokio::sync::{Mutex, Notify}; use tokio::time::Instant; use tracing::{debug, trace}; @@ -20,6 +21,9 @@ pub struct Handler { last_resort: Option, dns_client: SyncDnsClient, last_active: Arc>, + health_check: bool, + is_first_health_check_done: Arc, + wait_for_health_check: Option>, } impl Handler { @@ -39,13 +43,20 @@ impl Handler { health_check_active: u32, health_check_prefers: Vec, health_check_on_start: bool, + health_check_wait: bool, dns_client: SyncDnsClient, ) -> (Self, Vec) { let mut abort_handles = Vec::new(); let schedule = Arc::new(Mutex::new((0..actors.len()).collect())); let last_active = Arc::new(Mutex::new(Instant::now())); + let is_first_health_check_done = Arc::new(AtomicBool::new(false)); - let health_check_task = if health_check { + let (health_check_task, wait_for_health_check) = if health_check { + let notify = if health_check_wait { + Some(Arc::new(Notify::new())) + } else { + None + }; let (abortable, abort_handle) = abortable(super::health_check_task( Network::Tcp, schedule.clone(), @@ -59,17 +70,19 @@ impl Handler { health_check_active, health_check_prefers, last_active.clone(), + is_first_health_check_done.clone(), + notify.as_ref().cloned(), )); abort_handles.push(abort_handle); let task: BoxFuture<'static, ()> = Box::pin(abortable.map(|_| ())); if health_check_on_start { tokio::spawn(task); - Mutex::new(None) + (Mutex::new(None), notify) } else { - Mutex::new(Some(task)) + (Mutex::new(Some(task)), notify) } } else { - Mutex::new(None) + (Mutex::new(None), None) }; let cache = if fallback_cache { @@ -93,6 +106,9 @@ impl Handler { last_resort, dns_client, last_active, + health_check, + is_first_health_check_done, + wait_for_health_check, }, abort_handles, ) @@ -117,6 +133,14 @@ impl OutboundStreamHandler for Handler { tokio::spawn(task); } + if self.health_check && !self.is_first_health_check_done.load(Ordering::Relaxed) { + if let Some(w) = self.wait_for_health_check.as_ref() { + debug!("holding {}", &sess.destination); + w.notified().await; + debug!("{} resumed", &sess.destination); + } + } + if let Some(cache) = &self.cache { // Try the cached actor first if exists. let cache_key = sess.destination.to_string();