mirror of
https://github.com/sadoyan/aralez.git
synced 2026-05-30 03:44:06 +08:00
Cleanup. Making clippy happy.
This commit is contained in:
@@ -153,9 +153,9 @@ impl AuthValidator for ForwardAuth<'_> {
|
||||
impl AuthValidator for BasicAuth<'_> {
|
||||
async fn validate(&self, session: &mut Session) -> bool {
|
||||
if let Some(header) = session.get_header("authorization") {
|
||||
if let Some(h) = header.to_str().ok() {
|
||||
if let Ok(h) = header.to_str() {
|
||||
if let Some((_, val)) = h.split_once(' ') {
|
||||
if let Some(decoded) = STANDARD.decode(val).ok() {
|
||||
if let Ok(decoded) = STANDARD.decode(val) {
|
||||
if decoded.as_slice().ct_eq(self.0.as_bytes()).into() {
|
||||
return true;
|
||||
}
|
||||
@@ -171,7 +171,7 @@ impl AuthValidator for BasicAuth<'_> {
|
||||
impl AuthValidator for ApiKeyAuth<'_> {
|
||||
async fn validate(&self, session: &mut Session) -> bool {
|
||||
if let Some(header) = session.get_header("x-api-key") {
|
||||
if let Some(h) = header.to_str().ok() {
|
||||
if let Ok(h) = header.to_str() {
|
||||
return h.as_bytes().ct_eq(self.0.as_bytes()).into();
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,7 @@ pub fn get_query_param(session: &mut Session, key: &str) -> Option<String> {
|
||||
params.get(key).and_then(|v| decode(v).ok()).map(|s| s.to_string())
|
||||
}
|
||||
|
||||
#[allow(clippy::needless_return)]
|
||||
fn split_host_port(addr: &str, tls: bool) -> Option<(&str, u16, bool, &str)> {
|
||||
match addr.split_once(':') {
|
||||
Some((h, p)) => match p.parse::<u16>() {
|
||||
|
||||
@@ -37,17 +37,12 @@ pub async fn start(fp: String, mut toreturn: Sender<Configuration>) {
|
||||
match event {
|
||||
Ok(e) => match e.kind {
|
||||
EventKind::Modify(ModifyKind::Data(_)) | EventKind::Create(..) | EventKind::Remove(..) => {
|
||||
if e.paths[0].to_str().unwrap().ends_with("yaml") {
|
||||
if start.elapsed() > Duration::from_secs(2) {
|
||||
start = Instant::now();
|
||||
// info!("Config File changed :=> {:?}", e);
|
||||
let snd = load_configuration(file_path, "filepath").await.0;
|
||||
match snd {
|
||||
Some(snd) => {
|
||||
toreturn.send(snd).await.unwrap();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if e.paths[0].to_str().unwrap().ends_with("yaml") && start.elapsed() > Duration::from_secs(2) {
|
||||
start = Instant::now();
|
||||
// info!("Config File changed :=> {:?}", e);
|
||||
let snd = load_configuration(file_path, "filepath").await.0;
|
||||
if let Some(snd) = snd {
|
||||
toreturn.send(snd).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,8 +52,8 @@ async fn build_upstreams(fullist: &UpstreamsDashMap, method: &str, client: &Clie
|
||||
let path = path_entry.key();
|
||||
let mut innervec = Vec::new();
|
||||
|
||||
for (_, upstream) in path_entry.value().0.iter().enumerate() {
|
||||
let tls = detect_tls(&upstream.address.to_string(), &upstream.port, &client).await;
|
||||
for upstream in path_entry.value().0.iter() {
|
||||
let tls = detect_tls(upstream.address.as_ref(), &upstream.port, client).await;
|
||||
let is_h2 = matches!(tls.1, Some(Version::HTTP_2));
|
||||
|
||||
let link = if tls.0 {
|
||||
@@ -75,7 +75,7 @@ async fn build_upstreams(fullist: &UpstreamsDashMap, method: &str, client: &Clie
|
||||
};
|
||||
|
||||
if scheme.healthcheck.unwrap_or(true) {
|
||||
let resp = http_request(&link, method, "", &client).await;
|
||||
let resp = http_request(&link, method, "", client).await;
|
||||
if resp.0 {
|
||||
if resp.1 {
|
||||
scheme.is_http2 = is_h2; // could be adjusted further
|
||||
@@ -109,12 +109,12 @@ async fn http_request(url: &str, method: &str, payload: &str, client: &Client) -
|
||||
}
|
||||
}
|
||||
|
||||
match send_request(&client, method, url, payload).await {
|
||||
match send_request(client, method, url, payload).await {
|
||||
Some(response) => {
|
||||
let status = response.status().as_u16();
|
||||
((99..499).contains(&status), false)
|
||||
}
|
||||
None => (ping_grpc(&url).await, true),
|
||||
None => (ping_grpc(url).await, true),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,12 +128,8 @@ pub async fn ping_grpc(addr: &str) -> bool {
|
||||
|
||||
async fn detect_tls(ip: &str, port: &u16, client: &Client) -> (bool, Option<Version>) {
|
||||
let https_url = format!("https://{}:{}", ip, port);
|
||||
match client.get(&https_url).send().await {
|
||||
Ok(response) => {
|
||||
// println!("{} => {:?} (HTTPS)", https_url, response.version());
|
||||
return (true, Some(response.version()));
|
||||
}
|
||||
_ => {}
|
||||
if let Ok(response) = client.get(&https_url).send().await {
|
||||
return (true, Some(response.version()));
|
||||
}
|
||||
let http_url = format!("http://{}:{}", ip, port);
|
||||
match client.get(&http_url).send().await {
|
||||
|
||||
@@ -23,11 +23,8 @@ pub async fn for_consul(url: String, token: Option<String>, conf: &GlobalService
|
||||
let upstreams: DashMap<Arc<str>, (Vec<Arc<InnerMap>>, AtomicUsize)> = DashMap::new();
|
||||
let endpoints: Vec<ConsulService> = resp.json().await.ok()?;
|
||||
for subsets in endpoints {
|
||||
// let addr = subsets.tagged_addresses.get("lan_ipv4").unwrap().address.clone();
|
||||
// let prt = subsets.tagged_addresses.get("lan_ipv4").unwrap().port.clone();
|
||||
let addr = subsets.tagged_addresses.get("lan_ipv4").unwrap().address.clone();
|
||||
let prt = subsets.tagged_addresses.get("lan_ipv4").unwrap().port.clone();
|
||||
// let redirect_link = conf.redirect_to.as_ref().map(|www| Arc::from(www.as_str()));
|
||||
let prt = subsets.tagged_addresses.get("lan_ipv4").unwrap().port;
|
||||
let to_add = Arc::from(InnerMap {
|
||||
address: Arc::from(&*addr),
|
||||
port: prt,
|
||||
@@ -41,7 +38,7 @@ pub async fn for_consul(url: String, token: Option<String>, conf: &GlobalService
|
||||
});
|
||||
inner_vec.push(to_add);
|
||||
}
|
||||
match_path(&conf, &upstreams, inner_vec.clone());
|
||||
match_path(conf, &upstreams, inner_vec);
|
||||
Some(upstreams)
|
||||
}
|
||||
|
||||
@@ -66,7 +63,7 @@ pub async fn for_kuber(url: &str, token: &str, conf: &GlobalServiceMapping) -> O
|
||||
// let redirect_link = conf.redirect_to.as_ref().map(|www| Arc::from(www.as_str()));
|
||||
let to_add = Arc::from(InnerMap {
|
||||
address: Arc::from(addr.ip.clone()),
|
||||
port: port.port.clone(),
|
||||
port: port.port,
|
||||
is_ssl: false,
|
||||
is_http2: false,
|
||||
to_https: conf.to_https.unwrap_or(false),
|
||||
@@ -78,7 +75,7 @@ pub async fn for_kuber(url: &str, token: &str, conf: &GlobalServiceMapping) -> O
|
||||
inner_vec.push(to_add);
|
||||
}
|
||||
}
|
||||
match_path(&conf, &upstreams, inner_vec.clone());
|
||||
match_path(conf, &upstreams, inner_vec.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,12 +52,13 @@ pub struct ConsulTaggedAddress {
|
||||
#[serde(rename = "Port")]
|
||||
pub port: u16,
|
||||
}
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn list_to_upstreams(lt: Option<DashMap<Arc<str>, (Vec<Arc<InnerMap>>, AtomicUsize)>>, upstreams: &UpstreamsDashMap, i: &GlobalServiceMapping) {
|
||||
if let Some(list) = lt {
|
||||
match upstreams.get(&*i.hostname.clone()) {
|
||||
Some(upstr) => {
|
||||
for (k, v) in list {
|
||||
upstr.value().insert(Arc::from(k.to_owned()), v);
|
||||
upstr.value().insert(k.to_owned(), v);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -134,7 +135,7 @@ impl ServiceDiscovery for KubernetesDiscovery {
|
||||
}
|
||||
let url = format!("https://{}/api/v1/namespaces/{}/endpoints/{}", server, namespace, service.hostname);
|
||||
// let url = format!("https://{}/api/v1/namespaces/{}/endpoints?labelSelector=app", server, namespace);
|
||||
let list = httpclient::for_kuber(&*url, &*token, &service).await;
|
||||
let list = httpclient::for_kuber(&url, &token, &service).await;
|
||||
// println!("{:?}", list);
|
||||
list_to_upstreams(list, &upstreams, &service);
|
||||
}
|
||||
@@ -209,7 +210,7 @@ impl ServiceDiscovery for ConsulDiscovery {
|
||||
}
|
||||
}
|
||||
async fn clone_compare(upstreams: &UpstreamsDashMap, prev_upstreams: &UpstreamsDashMap, config: &Arc<Configuration>) -> Option<Configuration> {
|
||||
if !compare_dashmaps(&upstreams, &prev_upstreams) {
|
||||
if !compare_dashmaps(upstreams, prev_upstreams) {
|
||||
let tosend: Configuration = Configuration {
|
||||
upstreams: Default::default(),
|
||||
client_headers: config.client_headers.clone(),
|
||||
@@ -219,8 +220,8 @@ async fn clone_compare(upstreams: &UpstreamsDashMap, prev_upstreams: &UpstreamsD
|
||||
typecfg: config.typecfg.clone(),
|
||||
extraparams: config.extraparams.clone(),
|
||||
};
|
||||
clone_dashmap_into(&upstreams, &prev_upstreams);
|
||||
clone_dashmap_into(&upstreams, &tosend.upstreams);
|
||||
clone_dashmap_into(upstreams, prev_upstreams);
|
||||
clone_dashmap_into(upstreams, &tosend.upstreams);
|
||||
print_upstreams(&tosend.upstreams);
|
||||
return Some(tosend);
|
||||
};
|
||||
|
||||
@@ -52,11 +52,11 @@ pub fn calc_metrics(metric_types: &MetricTypes) {
|
||||
let timer = REQUEST_LATENCY.start_timer();
|
||||
timer.observe_duration();
|
||||
|
||||
let version_str = match &metric_types.version {
|
||||
&Version::HTTP_11 => "HTTP/1.1",
|
||||
&Version::HTTP_2 => "HTTP/2.0",
|
||||
&Version::HTTP_3 => "HTTP/3.0",
|
||||
&Version::HTTP_10 => "HTTP/1.0",
|
||||
let version_str = match metric_types.version {
|
||||
Version::HTTP_11 => "HTTP/1.1",
|
||||
Version::HTTP_2 => "HTTP/2.0",
|
||||
Version::HTTP_3 => "HTTP/3.0",
|
||||
Version::HTTP_10 => "HTTP/1.0",
|
||||
_ => "Unknown",
|
||||
};
|
||||
REQUESTS_BY_VERSION.with_label_values(&[&version_str]).inc();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::{env, fs};
|
||||
|
||||
pub static DOMAINS: LazyLock<DashMap<String, bool>> = LazyLock::new(|| DashMap::new());
|
||||
pub static DOMAINS: LazyLock<DashMap<String, bool>> = LazyLock::new(DashMap::new);
|
||||
|
||||
pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>, String) {
|
||||
let mut conf_files = Vec::new();
|
||||
@@ -21,7 +21,7 @@ pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>,
|
||||
let mut autocfg = Path::new(d).parent().unwrap().to_path_buf();
|
||||
|
||||
autocfg.push("autoconfigs");
|
||||
if !fs::metadata(autocfg.clone()).is_ok() {
|
||||
if fs::metadata(autocfg.clone()).is_err() {
|
||||
fs::create_dir_all(autocfg.clone()).ok();
|
||||
}
|
||||
autocfg.push("domains.json");
|
||||
@@ -228,8 +228,8 @@ async fn populate_file_upstreams(config: &mut Configuration, parsed: &Config) {
|
||||
pub fn parce_main_config(path: &str) -> AppConfig {
|
||||
let data = fs::read_to_string(path).unwrap();
|
||||
let reply = DashMap::new();
|
||||
let cfg: HashMap<String, String> = serde_yml::from_str(&*data).expect("Failed to parse main config file");
|
||||
let mut cfo: AppConfig = serde_yml::from_str(&*data).expect("Failed to parse main config file");
|
||||
let cfg: HashMap<String, String> = serde_yml::from_str(&data).expect("Failed to parse main config file");
|
||||
let mut cfo: AppConfig = serde_yml::from_str(&data).expect("Failed to parse main config file");
|
||||
log_builder(&cfo);
|
||||
cfo.hc_method = cfo.hc_method.to_uppercase();
|
||||
for (k, v) in cfg {
|
||||
|
||||
@@ -150,7 +150,7 @@ pub fn merge_headers(target: &DashMap<Arc<str>, Vec<(String, Arc<str>)>>, source
|
||||
for entry in source.iter() {
|
||||
let global_key = entry.key().clone();
|
||||
let global_values = entry.value().clone();
|
||||
let mut target_entry = target.entry(global_key).or_insert_with(Vec::new);
|
||||
let mut target_entry = target.entry(global_key).or_default();
|
||||
target_entry.extend(global_values);
|
||||
}
|
||||
}
|
||||
@@ -198,7 +198,7 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
|
||||
authorization: None,
|
||||
};
|
||||
cloned.insert(id, Arc::from(to_add));
|
||||
cloned.insert(hh, Arc::from(x.to_owned()));
|
||||
cloned.insert(hh, x.to_owned());
|
||||
// println!("CLONNED :===========> {:?}", cloned);
|
||||
}
|
||||
new_inner_map.insert(path.clone(), new_vec);
|
||||
@@ -268,14 +268,14 @@ pub fn drop_priv(user: String, group: String, http_addr: String, tls_addr: Optio
|
||||
thread::sleep(time::Duration::from_millis(10));
|
||||
loop {
|
||||
thread::sleep(time::Duration::from_millis(10));
|
||||
if port_is_available(http_addr.clone()) {
|
||||
if TcpListener::bind(&http_addr).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(tls_addr) = tls_addr {
|
||||
loop {
|
||||
thread::sleep(time::Duration::from_millis(10));
|
||||
if port_is_available(tls_addr.clone()) {
|
||||
if TcpListener::bind(&tls_addr).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -287,24 +287,14 @@ pub fn drop_priv(user: String, group: String, http_addr: String, tls_addr: Optio
|
||||
}
|
||||
}
|
||||
|
||||
fn port_is_available(addr: String) -> bool {
|
||||
match TcpListener::bind(addr) {
|
||||
Ok(_) => false,
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_priv(addr: &str) {
|
||||
let port = SocketAddr::from_str(addr).map(|sa| sa.port()).unwrap();
|
||||
match port < 1024 {
|
||||
true => {
|
||||
let meta = std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap();
|
||||
if meta != 0 {
|
||||
error!("Running on privileged port requires to start as ROOT");
|
||||
process::exit(1)
|
||||
}
|
||||
if port < 1024 {
|
||||
let meta = std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap();
|
||||
if meta != 0 {
|
||||
error!("Running on privileged port requires to start as ROOT");
|
||||
process::exit(1)
|
||||
}
|
||||
false => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,7 +387,7 @@ pub fn prepend(prefix: &str, val: &Option<Arc<str>>, uri: &str, port: &str) -> O
|
||||
let mut buf = String::with_capacity(32);
|
||||
buf.push_str(prefix);
|
||||
buf.push_str(s);
|
||||
buf.push_str(":");
|
||||
buf.push(':');
|
||||
buf.push_str(port);
|
||||
buf.push_str(uri);
|
||||
buf
|
||||
|
||||
Reference in New Issue
Block a user