From 47071b8f8a37bda564697fbfebd867e75de16810 Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 13 Apr 2021 21:30:28 +0800 Subject: [PATCH] outbound/select: persists selector state --- leaf/Cargo.toml | 1 + leaf/build.rs | 6 + leaf/src/app/outbound/manager.rs | 18 +- leaf/src/app/outbound/mod.rs | 1 + leaf/src/app/outbound/selector.rs | 45 ++++- leaf/src/app/outbound/selector_cache.proto | 5 + leaf/src/app/outbound/selector_cache.rs | 197 +++++++++++++++++++++ 7 files changed, 266 insertions(+), 7 deletions(-) create mode 100644 leaf/src/app/outbound/selector_cache.proto create mode 100644 leaf/src/app/outbound/selector_cache.rs diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index 04bb426..180644f 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -130,6 +130,7 @@ bytes = "1" lazy_static = "1.4.0" anyhow = "1.0" rand = "0.8" +directories = "3.0" # config-json serde_json = { version = "1.0", features = ["raw_value"], optional = true } diff --git a/leaf/build.rs b/leaf/build.rs index 01dc74c..718d7eb 100644 --- a/leaf/build.rs +++ b/leaf/build.rs @@ -172,5 +172,11 @@ fn main() { .inputs(&["src/config/geosite.proto"]) .run() .expect("protoc"); + + protoc_rust::Codegen::new() + .out_dir("src/app/outbound") + .inputs(&["src/app/outbound/selector_cache.proto"]) + .run() + .expect("protoc"); } } diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index adc1ca0..ea8cab2 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -709,7 +709,7 @@ impl OutboundManager { fn load_selectors( outbounds: &protobuf::RepeatedField, handlers: &mut HashMap>, - ) -> super::Selectors { + ) -> Result { let mut selectors: super::Selectors = HashMap::new(); // FIXME a better way to find outbound deps? @@ -738,9 +738,15 @@ impl OutboundManager { if actors.is_empty() { continue; } - let mut selector = OutboundSelector::new(actors); - selector.set_selected(&settings.actors[0]); + + let mut selector = OutboundSelector::new(tag.clone(), actors); + if let Ok(Some(selected)) = super::selector::get_selected_from_cache(&tag) { + selector.set_selected(&selected)?; + } else { + selector.set_selected(&settings.actors[0])?; + } let selector = Arc::new(RwLock::new(selector)); + let tcp = Box::new(select::TcpHandler { selector: selector.clone(), }); @@ -766,7 +772,7 @@ impl OutboundManager { } } - selectors + Ok(selectors) } // TODO make this non-async? @@ -789,7 +795,7 @@ impl OutboundManager { abort_handle.abort(); } - let mut selectors = Self::load_selectors(outbounds, &mut handlers); + let mut selectors = Self::load_selectors(outbounds, &mut handlers)?; // Restore selected outbounds. for (k, v) in selected_outbounds.iter() { @@ -815,7 +821,7 @@ impl OutboundManager { ) -> Result { let (mut handlers, default_handler, abort_handles) = Self::load_handlers(outbounds, dns_client); - let selectors = Self::load_selectors(outbounds, &mut handlers); + let selectors = Self::load_selectors(outbounds, &mut handlers)?; Ok(OutboundManager { handlers, selectors: Arc::new(selectors), diff --git a/leaf/src/app/outbound/mod.rs b/leaf/src/app/outbound/mod.rs index 2006fbc..6d19057 100644 --- a/leaf/src/app/outbound/mod.rs +++ b/leaf/src/app/outbound/mod.rs @@ -5,5 +5,6 @@ use tokio::sync::RwLock; pub mod manager; pub mod selector; +pub mod selector_cache; pub type Selectors = HashMap>>; diff --git a/leaf/src/app/outbound/selector.rs b/leaf/src/app/outbound/selector.rs index 5c53bab..5b9bf38 100644 --- a/leaf/src/app/outbound/selector.rs +++ b/leaf/src/app/outbound/selector.rs @@ -1,18 +1,58 @@ use std::collections::HashMap; use std::sync::Arc; +use protobuf::Message; + use crate::proxy::OutboundHandler; use anyhow::{anyhow, Result}; +pub fn get_selected_from_cache(id: &str) -> Result> { + let proj_dirs = if let Some(d) = directories::ProjectDirs::from("com", "github", "leaf") { + d + } else { + return Err(anyhow!("no home directory")); + }; + let cache_loc = proj_dirs.cache_dir(); + let cache_file = cache_loc.join("selector.cache"); + let content = std::fs::read(&cache_file)?; + let cache = super::selector_cache::SelectorCache::parse_from_bytes(&content)?; + Ok(cache.items.get(id).map(Clone::clone)) +} + +pub fn persist_selected_to_cache(id: String, selected: String) -> Result<()> { + let proj_dirs = if let Some(d) = directories::ProjectDirs::from("com", "github", "leaf") { + d + } else { + return Err(anyhow!("no home directory")); + }; + let cache_loc = proj_dirs.cache_dir(); + if !cache_loc.exists() { + std::fs::create_dir_all(&cache_loc)?; + } + let cache_file = cache_loc.join("selector.cache"); + let mut cache = if cache_file.exists() { + let content = std::fs::read(&cache_file)?; + super::selector_cache::SelectorCache::parse_from_bytes(&content)? + } else { + super::selector_cache::SelectorCache::new() + }; + cache.items.insert(id.clone(), selected.clone()); + let content = cache.write_to_bytes()?; + std::fs::write(&cache_file, content)?; + Ok(()) +} + /// OutboundSelector typically associates to a `select` outbound. pub struct OutboundSelector { + id: String, handlers: HashMap>, selected: Option, } impl OutboundSelector { - pub fn new(handlers: HashMap>) -> Self { + pub fn new(id: String, handlers: HashMap>) -> Self { Self { + id, handlers, selected: None, } @@ -37,6 +77,9 @@ impl OutboundSelector { pub fn set_selected(&mut self, tag: &str) -> Result<()> { if self.handlers.contains_key(tag) { self.selected.replace(tag.to_string()); + if let Err(e) = persist_selected_to_cache(self.id.clone(), tag.to_string()) { + log::warn!("persist selector state failed: {}", e); + } Ok(()) } else { Err(anyhow!("handler not exists")) diff --git a/leaf/src/app/outbound/selector_cache.proto b/leaf/src/app/outbound/selector_cache.proto new file mode 100644 index 0000000..ca36da9 --- /dev/null +++ b/leaf/src/app/outbound/selector_cache.proto @@ -0,0 +1,5 @@ +syntax = "proto3"; + +message SelectorCache { + map items = 1; +} diff --git a/leaf/src/app/outbound/selector_cache.rs b/leaf/src/app/outbound/selector_cache.rs new file mode 100644 index 0000000..f935a2e --- /dev/null +++ b/leaf/src/app/outbound/selector_cache.rs @@ -0,0 +1,197 @@ +// This file is generated by rust-protobuf 2.22.1. Do not edit +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_imports)] +#![allow(unused_results)] +//! Generated file from `src/app/outbound/selector_cache.proto` + +/// Generated files are compatible only with the same version +/// of protobuf runtime. +// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_22_1; + +#[derive(PartialEq,Clone,Default)] +pub struct SelectorCache { + // message fields + pub items: ::std::collections::HashMap<::std::string::String, ::std::string::String>, + // special fields + pub unknown_fields: ::protobuf::UnknownFields, + pub cached_size: ::protobuf::CachedSize, +} + +impl<'a> ::std::default::Default for &'a SelectorCache { + fn default() -> &'a SelectorCache { + ::default_instance() + } +} + +impl SelectorCache { + pub fn new() -> SelectorCache { + ::std::default::Default::default() + } + + // repeated .SelectorCache.ItemsEntry items = 1; + + + pub fn get_items(&self) -> &::std::collections::HashMap<::std::string::String, ::std::string::String> { + &self.items + } + pub fn clear_items(&mut self) { + self.items.clear(); + } + + // Param is passed by value, moved + pub fn set_items(&mut self, v: ::std::collections::HashMap<::std::string::String, ::std::string::String>) { + self.items = v; + } + + // Mutable pointer to the field. + pub fn mut_items(&mut self) -> &mut ::std::collections::HashMap<::std::string::String, ::std::string::String> { + &mut self.items + } + + // Take field + pub fn take_items(&mut self) -> ::std::collections::HashMap<::std::string::String, ::std::string::String> { + ::std::mem::replace(&mut self.items, ::std::collections::HashMap::new()) + } +} + +impl ::protobuf::Message for SelectorCache { + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { + while !is.eof()? { + let (field_number, wire_type) = is.read_tag_unpack()?; + match field_number { + 1 => { + ::protobuf::rt::read_map_into::<::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>(wire_type, is, &mut self.items)?; + }, + _ => { + ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u32 { + let mut my_size = 0; + my_size += ::protobuf::rt::compute_map_size::<::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>(1, &self.items); + my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); + self.cached_size.set(my_size); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { + ::protobuf::rt::write_map_with_cached_sizes::<::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>(1, &self.items, os)?; + os.write_unknown_fields(self.get_unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn get_cached_size(&self) -> u32 { + self.cached_size.get() + } + + fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { + &self.unknown_fields + } + + fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { + &mut self.unknown_fields + } + + fn as_any(&self) -> &dyn (::std::any::Any) { + self as &dyn (::std::any::Any) + } + fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { + self as &mut dyn (::std::any::Any) + } + fn into_any(self: ::std::boxed::Box) -> ::std::boxed::Box { + self + } + + fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { + Self::descriptor_static() + } + + fn new() -> SelectorCache { + SelectorCache::new() + } + + fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { + static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; + descriptor.get(|| { + let mut fields = ::std::vec::Vec::new(); + fields.push(::protobuf::reflect::accessor::make_map_accessor::<_, ::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>( + "items", + |m: &SelectorCache| { &m.items }, + |m: &mut SelectorCache| { &mut m.items }, + )); + ::protobuf::reflect::MessageDescriptor::new_pb_name::( + "SelectorCache", + fields, + file_descriptor_proto() + ) + }) + } + + fn default_instance() -> &'static SelectorCache { + static instance: ::protobuf::rt::LazyV2 = ::protobuf::rt::LazyV2::INIT; + instance.get(SelectorCache::new) + } +} + +impl ::protobuf::Clear for SelectorCache { + fn clear(&mut self) { + self.items.clear(); + self.unknown_fields.clear(); + } +} + +impl ::std::fmt::Debug for SelectorCache { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::protobuf::text_format::fmt(self, f) + } +} + +impl ::protobuf::reflect::ProtobufValue for SelectorCache { + fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { + ::protobuf::reflect::ReflectValueRef::Message(self) + } +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n%src/app/outbound/selector_cache.proto\"z\n\rSelectorCache\x12/\n\x05i\ + tems\x18\x01\x20\x03(\x0b2\x19.SelectorCache.ItemsEntryR\x05items\x1a8\n\ + \nItemsEntry\x12\x10\n\x03key\x18\x01\x20\x01(\tR\x03key\x12\x14\n\x05va\ + lue\x18\x02\x20\x01(\tR\x05value:\x028\x01b\x06proto3\ +"; + +static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; + +fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { + ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +} + +pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { + file_descriptor_proto_lazy.get(|| { + parse_descriptor_proto() + }) +}