outbound/select: persists selector state

This commit is contained in:
eric committed 2021-04-13 21:33:03 +08:00
1 parent 2d9fee3c07
commit 47071b8f8a
7 files changed
+266 -7

No files matched your search

+1
View File
@@ -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 }
+6
View File
@@ -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");
}
}
+12 -6
View File
@@ -709,7 +709,7 @@ impl OutboundManager {
fn load_selectors(
outbounds: &protobuf::RepeatedField<Outbound>,
handlers: &mut HashMap<String, Arc<dyn OutboundHandler>>,
) -> super::Selectors {
) -> Result<super::Selectors> {
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<Self> {
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),
+1
View File
@@ -5,5 +5,6 @@ use tokio::sync::RwLock;
pub mod manager;
pub mod selector;
pub mod selector_cache;
pub type Selectors = HashMap<String, Arc<RwLock<selector::OutboundSelector>>>;
+44 -1
View File
@@ -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<Option<String>> {
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<String, Arc<dyn OutboundHandler>>,
selected: Option<String>,
}
impl OutboundSelector {
pub fn new(handlers: HashMap<String, Arc<dyn OutboundHandler>>) -> Self {
pub fn new(id: String, handlers: HashMap<String, Arc<dyn OutboundHandler>>) -> 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"))
@@ -0,0 +1,5 @@
syntax = "proto3";
message SelectorCache {
map<string, string> items = 1;
}
+197
View File
@@ -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 {
<SelectorCache as ::protobuf::Message>::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<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
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>(
"SelectorCache",
fields,
file_descriptor_proto()
)
})
}
fn default_instance() -> &'static SelectorCache {
static instance: ::protobuf::rt::LazyV2<SelectorCache> = ::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()
})
}