diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index a3f14ff..1e41b6d 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -72,7 +72,7 @@ outbound-tls = [] outbound-ws = ["tungstenite", "tokio-tungstenite", "url"] outbound-h2 = ["h2", "http", "url"] outbound-vless = ["uuid"] -outbound-failover = [] +outbound-failover = ["lru_time_cache"] outbound-random = [] outbound-tryall = [] outbound-chain = [] @@ -176,6 +176,9 @@ sha-1 = { version = "0.9", optional = true } sha2 = { version = "0.9", optional = true } hex = { version = "0.4", optional = true } +# Failover +lru_time_cache = { version = "0.11", optional = true } + # TUN [target.'cfg(any(target_os = "ios", target_os = "macos", target_os = "linux"))'.dependencies] tun = { git = "https://github.com/eycorsican/rust-tun.git", branch = "fix", features = ["async"], optional = true } diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index 12e5e79..c6df10f 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -546,6 +546,9 @@ impl OutboundManager { settings.health_check, settings.check_interval, settings.failover, + settings.fallback_cache, + settings.cache_size as usize, + settings.cache_timeout as u64, )); let udp = Box::new(failover::UdpHandler::new( actors, diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index 697d1fd..1884ed1 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -90,6 +90,9 @@ pub struct ProxyGroup { pub check_interval: Option, pub fail_timeout: Option, pub failover: Option, + pub fallback_cache: Option, + pub cache_size: Option, + pub cache_timeout: Option, // tryall pub delay_base: Option, @@ -105,6 +108,9 @@ impl Default for ProxyGroup { check_interval: Some(300), fail_timeout: Some(4), failover: Some(true), + fallback_cache: Some(false), + cache_size: Some(256), + cache_timeout: Some(60), delay_base: Some(0), } } @@ -447,6 +453,25 @@ pub fn from_lines(lines: Vec>) -> Result { "failover" => { group.failover = if v == "true" { Some(true) } else { Some(false) }; } + "fallback-cache" => { + group.fallback_cache = if v == "true" { Some(true) } else { Some(false) }; + } + "cache-size" => { + let i = if let Ok(i) = v.parse::() { + Some(i) + } else { + None + }; + group.cache_size = i; + } + "cache-timeout" => { + let i = if let Ok(i) = v.parse::() { + Some(i) + } else { + None + }; + group.cache_timeout = i; + } "delay-base" => { let i = if let Ok(i) = v.parse::() { Some(i) @@ -951,6 +976,21 @@ pub fn to_internal(conf: Config) -> Result { } else { settings.failover = true; } + if let Some(ext_fallback_cache) = ext_proxy_group.fallback_cache { + settings.fallback_cache = ext_fallback_cache; + } else { + settings.fallback_cache = false; + } + if let Some(ext_cache_size) = ext_proxy_group.cache_size { + settings.cache_size = ext_cache_size as u32; + } else { + settings.cache_size = 256; + } + if let Some(ext_cache_timeout) = ext_proxy_group.cache_timeout { + settings.cache_timeout = ext_cache_timeout as u32; + } else { + settings.cache_timeout = 60; // in minutes + } 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 d19fe60..47fd84d 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -126,6 +126,9 @@ message FailOverOutboundSettings { bool health_check = 3; uint32 check_interval = 4; bool failover = 5; + bool fallback_cache = 6; + uint32 cache_size = 7; + uint32 cache_timeout = 8; } message Outbound { diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index ebb74b7..0b94144 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -4279,6 +4279,9 @@ pub struct FailOverOutboundSettings { pub health_check: bool, pub check_interval: u32, pub failover: bool, + pub fallback_cache: bool, + pub cache_size: u32, + pub cache_timeout: u32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, @@ -4379,6 +4382,51 @@ impl FailOverOutboundSettings { pub fn set_failover(&mut self, v: bool) { self.failover = v; } + + // bool fallback_cache = 6; + + + pub fn get_fallback_cache(&self) -> bool { + self.fallback_cache + } + pub fn clear_fallback_cache(&mut self) { + self.fallback_cache = false; + } + + // Param is passed by value, moved + pub fn set_fallback_cache(&mut self, v: bool) { + self.fallback_cache = v; + } + + // uint32 cache_size = 7; + + + pub fn get_cache_size(&self) -> u32 { + self.cache_size + } + pub fn clear_cache_size(&mut self) { + self.cache_size = 0; + } + + // Param is passed by value, moved + pub fn set_cache_size(&mut self, v: u32) { + self.cache_size = v; + } + + // uint32 cache_timeout = 8; + + + pub fn get_cache_timeout(&self) -> u32 { + self.cache_timeout + } + pub fn clear_cache_timeout(&mut self) { + self.cache_timeout = 0; + } + + // Param is passed by value, moved + pub fn set_cache_timeout(&mut self, v: u32) { + self.cache_timeout = v; + } } impl ::protobuf::Message for FailOverOutboundSettings { @@ -4421,6 +4469,27 @@ impl ::protobuf::Message for FailOverOutboundSettings { let tmp = is.read_bool()?; self.failover = tmp; }, + 6 => { + if wire_type != ::protobuf::wire_format::WireTypeVarint { + return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); + } + let tmp = is.read_bool()?; + self.fallback_cache = tmp; + }, + 7 => { + if wire_type != ::protobuf::wire_format::WireTypeVarint { + return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); + } + let tmp = is.read_uint32()?; + self.cache_size = tmp; + }, + 8 => { + if wire_type != ::protobuf::wire_format::WireTypeVarint { + return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); + } + let tmp = is.read_uint32()?; + self.cache_timeout = tmp; + }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, @@ -4448,6 +4517,15 @@ impl ::protobuf::Message for FailOverOutboundSettings { if self.failover != false { my_size += 2; } + if self.fallback_cache != false { + my_size += 2; + } + if self.cache_size != 0 { + my_size += ::protobuf::rt::value_size(7, self.cache_size, ::protobuf::wire_format::WireTypeVarint); + } + if self.cache_timeout != 0 { + my_size += ::protobuf::rt::value_size(8, self.cache_timeout, ::protobuf::wire_format::WireTypeVarint); + } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size @@ -4469,6 +4547,15 @@ impl ::protobuf::Message for FailOverOutboundSettings { if self.failover != false { os.write_bool(5, self.failover)?; } + if self.fallback_cache != false { + os.write_bool(6, self.fallback_cache)?; + } + if self.cache_size != 0 { + os.write_uint32(7, self.cache_size)?; + } + if self.cache_timeout != 0 { + os.write_uint32(8, self.cache_timeout)?; + } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } @@ -4532,6 +4619,21 @@ impl ::protobuf::Message for FailOverOutboundSettings { |m: &FailOverOutboundSettings| { &m.failover }, |m: &mut FailOverOutboundSettings| { &mut m.failover }, )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBool>( + "fallback_cache", + |m: &FailOverOutboundSettings| { &m.fallback_cache }, + |m: &mut FailOverOutboundSettings| { &mut m.fallback_cache }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( + "cache_size", + |m: &FailOverOutboundSettings| { &m.cache_size }, + |m: &mut FailOverOutboundSettings| { &mut m.cache_size }, + )); + fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( + "cache_timeout", + |m: &FailOverOutboundSettings| { &m.cache_timeout }, + |m: &mut FailOverOutboundSettings| { &mut m.cache_timeout }, + )); ::protobuf::reflect::MessageDescriptor::new_pb_name::( "FailOverOutboundSettings", fields, @@ -4553,6 +4655,9 @@ impl ::protobuf::Clear for FailOverOutboundSettings { self.health_check = false; self.check_interval = 0; self.failover = false; + self.fallback_cache = false; + self.cache_size = 0; + self.cache_timeout = 0; self.unknown_fields.clear(); } } @@ -6020,29 +6125,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ tings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\x12\x1d\n\ndelay\ _base\x18\x02\x20\x01(\rR\tdelayBase\"0\n\x16RandomOutboundSettings\x12\ \x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"/\n\x15ChainOutboundSett\ - ings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"\xbb\x01\n\x18Fa\ + ings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\"\xa6\x02\n\x18Fa\ ilOverOutboundSettings\x12\x16\n\x06actors\x18\x01\x20\x03(\tR\x06actors\ \x12!\n\x0cfail_timeout\x18\x02\x20\x01(\rR\x0bfailTimeout\x12!\n\x0chea\ lth_check\x18\x03\x20\x01(\x08R\x0bhealthCheck\x12%\n\x0echeck_interval\ \x18\x04\x20\x01(\rR\rcheckInterval\x12\x1a\n\x08failover\x18\x05\x20\ - \x01(\x08R\x08failover\"h\n\x08Outbound\x12\x10\n\x03tag\x18\x01\x20\x01\ - (\tR\x03tag\x12\x1a\n\x08protocol\x18\x02\x20\x01(\tR\x08protocol\x12\ - \x12\n\x04bind\x18\x03\x20\x01(\tR\x04bind\x12\x1a\n\x08settings\x18\x04\ - \x20\x01(\x0cR\x08settings\"\xd5\x02\n\x0bRoutingRule\x12\x1d\n\ntarget_\ - tag\x18\x01\x20\x01(\tR\ttargetTag\x12-\n\x07domains\x18\x02\x20\x03(\ - \x0b2\x13.RoutingRule.DomainR\x07domains\x12\x19\n\x08ip_cidrs\x18\x03\ - \x20\x03(\tR\x07ipCidrs\x12'\n\x05mmdbs\x18\x04\x20\x03(\x0b2\x11.Routin\ - gRule.MmdbR\x05mmdbs\x1au\n\x06Domain\x12,\n\x04type\x18\x01\x20\x01(\ - \x0e2\x18.RoutingRule.Domain.TypeR\x04type\x12\x14\n\x05value\x18\x02\ - \x20\x01(\tR\x05value\"'\n\x04Type\x12\t\n\x05PLAIN\x10\0\x12\n\n\x06DOM\ - AIN\x10\x01\x12\x08\n\x04FULL\x10\x02\x1a=\n\x04Mmdb\x12\x12\n\x04file\ - \x18\x01\x20\x01(\tR\x04file\x12!\n\x0ccountry_code\x18\x02\x20\x01(\tR\ - \x0bcountryCode\"\xba\x01\n\x06Config\x12\x16\n\x03log\x18\x01\x20\x01(\ - \x0b2\x04.LogR\x03log\x12$\n\x08inbounds\x18\x02\x20\x03(\x0b2\x08.Inbou\ - ndR\x08inbounds\x12'\n\toutbounds\x18\x03\x20\x03(\x0b2\t.OutboundR\tout\ - bounds\x121\n\rrouting_rules\x18\x04\x20\x03(\x0b2\x0c.RoutingRuleR\x0cr\ - outingRules\x12\x16\n\x03dns\x18\x05\x20\x01(\x0b2\x04.DNSR\x03dnsb\x06p\ - roto3\ + \x01(\x08R\x08failover\x12%\n\x0efallback_cache\x18\x06\x20\x01(\x08R\rf\ + allbackCache\x12\x1d\n\ncache_size\x18\x07\x20\x01(\rR\tcacheSize\x12#\n\ + \rcache_timeout\x18\x08\x20\x01(\rR\x0ccacheTimeout\"h\n\x08Outbound\x12\ + \x10\n\x03tag\x18\x01\x20\x01(\tR\x03tag\x12\x1a\n\x08protocol\x18\x02\ + \x20\x01(\tR\x08protocol\x12\x12\n\x04bind\x18\x03\x20\x01(\tR\x04bind\ + \x12\x1a\n\x08settings\x18\x04\x20\x01(\x0cR\x08settings\"\xd5\x02\n\x0b\ + RoutingRule\x12\x1d\n\ntarget_tag\x18\x01\x20\x01(\tR\ttargetTag\x12-\n\ + \x07domains\x18\x02\x20\x03(\x0b2\x13.RoutingRule.DomainR\x07domains\x12\ + \x19\n\x08ip_cidrs\x18\x03\x20\x03(\tR\x07ipCidrs\x12'\n\x05mmdbs\x18\ + \x04\x20\x03(\x0b2\x11.RoutingRule.MmdbR\x05mmdbs\x1au\n\x06Domain\x12,\ + \n\x04type\x18\x01\x20\x01(\x0e2\x18.RoutingRule.Domain.TypeR\x04type\ + \x12\x14\n\x05value\x18\x02\x20\x01(\tR\x05value\"'\n\x04Type\x12\t\n\ + \x05PLAIN\x10\0\x12\n\n\x06DOMAIN\x10\x01\x12\x08\n\x04FULL\x10\x02\x1a=\ + \n\x04Mmdb\x12\x12\n\x04file\x18\x01\x20\x01(\tR\x04file\x12!\n\x0ccount\ + ry_code\x18\x02\x20\x01(\tR\x0bcountryCode\"\xba\x01\n\x06Config\x12\x16\ + \n\x03log\x18\x01\x20\x01(\x0b2\x04.LogR\x03log\x12$\n\x08inbounds\x18\ + \x02\x20\x03(\x0b2\x08.InboundR\x08inbounds\x12'\n\toutbounds\x18\x03\ + \x20\x03(\x0b2\t.OutboundR\toutbounds\x121\n\rrouting_rules\x18\x04\x20\ + \x03(\x0b2\x0c.RoutingRuleR\x0croutingRules\x12\x16\n\x03dns\x18\x05\x20\ + \x01(\x0b2\x04.DNSR\x03dnsb\x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; diff --git a/leaf/src/config/json/config.rs b/leaf/src/config/json/config.rs index 79c82e3..88b8844 100644 --- a/leaf/src/config/json/config.rs +++ b/leaf/src/config/json/config.rs @@ -146,6 +146,12 @@ pub struct FailOverOutboundSettings { #[serde(rename = "checkInterval")] pub check_interval: Option, pub failover: Option, + #[serde(rename = "fallbackCache")] + pub fallback_cache: Option, + #[serde(rename = "cacheSize")] + pub cache_size: Option, + #[serde(rename = "cacheTimeout")] + pub cache_timeout: Option, } #[derive(Serialize, Deserialize, Debug)] @@ -605,6 +611,21 @@ pub fn to_internal(json: Config) -> Result { } else { settings.failover = true; } + if let Some(ext_fallback_cache) = ext_settings.fallback_cache { + settings.fallback_cache = ext_fallback_cache; + } else { + settings.fallback_cache = false; + } + if let Some(ext_cache_size) = ext_settings.cache_size { + settings.cache_size = ext_cache_size; + } else { + settings.cache_size = 256; + } + if let Some(ext_cache_timeout) = ext_settings.cache_timeout { + settings.cache_timeout = ext_cache_timeout; + } else { + settings.cache_timeout = 60; // in minutes + } let settings = settings.write_to_bytes().unwrap(); outbound.settings = settings; outbounds.push(outbound); diff --git a/leaf/src/proxy/failover/tcp.rs b/leaf/src/proxy/failover/tcp.rs index f51e1a2..6e64edd 100644 --- a/leaf/src/proxy/failover/tcp.rs +++ b/leaf/src/proxy/failover/tcp.rs @@ -4,6 +4,7 @@ use std::{io, sync::Arc, time}; use async_trait::async_trait; use futures::future::BoxFuture; use log::*; +use lru_time_cache::LruCache; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::Mutex as TokioMutex; use tokio::time::timeout; @@ -18,6 +19,7 @@ pub struct Handler { pub fail_timeout: u32, pub schedule: Arc>>, pub health_check_task: TokioMutex>>, + pub cache: Option>>>, } #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] @@ -26,10 +28,13 @@ struct Measure(usize, u128); // (index, duration in millis) impl Handler { pub fn new( actors: Vec>, - fail_timeout: u32, + fail_timeout: u32, // in secs health_check: bool, - check_interval: u32, + check_interval: u32, // in secs failover: bool, + fallback_cache: bool, + cache_size: usize, + cache_timeout: u64, // in minutes ) -> Self { let mut schedule = Vec::new(); for i in 0..actors.len() { @@ -126,11 +131,23 @@ impl Handler { None }; + let cache = if fallback_cache { + Some(Arc::new(TokioMutex::new( + LruCache::with_expiry_duration_and_capacity( + time::Duration::from_secs(cache_timeout * 60), + cache_size, + ), + ))) + } else { + None + }; + Handler { actors, fail_timeout, schedule, health_check_task: TokioMutex::new(task), + cache, } } } @@ -156,32 +173,68 @@ impl TcpOutboundHandler for Handler { } } + if let Some(cache) = &self.cache { + // Try the cached actor first if exists. + let cache_key = sess.destination.to_string(); + if let Some(idx) = cache.lock().await.get(&cache_key) { + debug!( + "failover handles tcp [{}] to cached [{}]", + sess.destination, + self.actors[*idx].tag() + ); + // TODO Remove the entry immediately if timeout or fail? + match timeout( + time::Duration::from_secs(self.fail_timeout as u64), + (&self.actors[*idx]).handle_tcp(sess, None), + ) + .await + { + Ok(t) => match t { + Ok(v) => return Ok(v), + Err(_) => (), + }, + Err(_) => (), + } + }; + } + let schedule = self.schedule.lock().await.clone(); - for i in schedule { - if i >= self.actors.len() { + for (sche_idx, actor_idx) in schedule.into_iter().enumerate() { + if actor_idx >= self.actors.len() { return Err(io::Error::new(io::ErrorKind::Other, "invalid actor index")); } debug!( "failover handles tcp [{}] to [{}]", sess.destination, - self.actors[i].tag() + self.actors[actor_idx].tag() ); match timeout( time::Duration::from_secs(self.fail_timeout as u64), - (&self.actors[i]).handle_tcp(sess, None), + (&self.actors[actor_idx]).handle_tcp(sess, None), ) .await { // return before timeout Ok(t) => match t { - // return ok - Ok(v) => return Ok(v), - // return err + Ok(v) => { + // Only cache for fallback actors. + if let Some(cache) = &self.cache { + if sche_idx > 0 { + let cache_key = sess.destination.to_string(); + trace!( + "failover inserts {} -> {} to cache", + cache_key, + self.actors[actor_idx].tag() + ); + cache.lock().await.insert(cache_key, actor_idx); + } + } + return Ok(v); + } Err(_) => continue, }, - // after timeout Err(_) => continue, } }