mirror of
https://github.com/sadoyan/aralez.git
synced 2026-04-30 23:08:40 +08:00
Move to RusTLS, Static binary build, performance improvements.
This commit is contained in:
1070
Cargo.lock
generated
1070
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
34
Cargo.toml
34
Cargo.toml
@@ -3,33 +3,39 @@ name = "gazan"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = true
|
||||||
|
codegen-units = 1
|
||||||
|
opt-level = 3
|
||||||
|
strip = "symbols"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tokio = { version = "1.44.2", features = ["full"] }
|
tokio = { version = "1.45.0", features = ["full"] }
|
||||||
pingora = { version = "0.4.0", features = ["lb", "openssl"] } # openssl, rustls, boringssl
|
pingora = { version = "0.5.0", features = ["lb", "rustls"] } # openssl, rustls, boringssl
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
dashmap = "7.0.0-rc2"
|
dashmap = "7.0.0-rc2"
|
||||||
pingora-core = "0.4.0"
|
pingora-core = "0.5.0"
|
||||||
pingora-proxy = "0.4.0"
|
pingora-proxy = "0.5.0"
|
||||||
pingora-http = "0.4.0"
|
pingora-http = "0.5.0"
|
||||||
async-trait = "0.1.88"
|
async-trait = "0.1.88"
|
||||||
env_logger = "0.11.8"
|
env_logger = "0.11.8"
|
||||||
log = "0.4.27"
|
log = "0.4.27"
|
||||||
futures = "0.3.31"
|
futures = "0.3.31"
|
||||||
notify = "8.0.0"
|
notify = "8.0.0"
|
||||||
axum = { version = "0.8.3" }
|
axum = { version = "0.8.4" }
|
||||||
reqwest = { version = "0.12.15", features = ["json"] }
|
#reqwest = { version = "0.12.15", features = ["json", "native-tls-alpn"] }
|
||||||
serde_yaml = "0.8.26"
|
#reqwest = { version = "0.12.15", features = ["json", "rustls-tls"] }
|
||||||
#hickory-client = "0.25.1"
|
reqwest = { version = "0.12.15", default-features = false, features = ["rustls-tls", "json"] }
|
||||||
|
|
||||||
|
serde_yaml = "0.9.34-deprecated"
|
||||||
rand = "0.9.0"
|
rand = "0.9.0"
|
||||||
base64 = "0.22.1"
|
base64 = "0.22.1"
|
||||||
jsonwebtoken = "9.3.1"
|
jsonwebtoken = "9.3.1"
|
||||||
#hmac = "0.12.1"
|
|
||||||
#sha2 = "0.10.8"
|
|
||||||
tonic = "0.13.0"
|
tonic = "0.13.0"
|
||||||
#uuid = { version = "1.16.0", features = ["v4"] }
|
sha2 = { version = "0.11.0-pre.5", default-features = false }
|
||||||
sha2 = { version = "0.10.8", default-features = false }
|
|
||||||
base16ct = { version = "0.2.0", features = ["alloc"] }
|
base16ct = { version = "0.2.0", features = ["alloc"] }
|
||||||
urlencoding = "2.1.3"
|
urlencoding = "2.1.3"
|
||||||
arc-swap = "1.7.1"
|
arc-swap = "1.7.1"
|
||||||
|
rustls = { version = "0.23.27", features = ["ring"] }
|
||||||
|
mimalloc = { version = "0.1.46", default-features = false }
|
||||||
|
|
||||||
|
|||||||
31
README.md
31
README.md
@@ -27,16 +27,16 @@ Built on Rust, on top of **Cloudflare’s Pingora engine**, **Gazan** delivers w
|
|||||||
|
|
||||||
## 🌍 Highlights
|
## 🌍 Highlights
|
||||||
|
|
||||||
- ⚙️ **Upstream Providers:** Supports `file`-based static upstreams, dynamic service discovery via `Consul`
|
- ⚙️ **Upstream Providers:** Supports `file`-based static upstreams, dynamic service discovery via `Consul`.
|
||||||
- 🔁 **Hot Reloading:** Modify upstreams on the fly via `upstreams.yaml` — no restart needed
|
- 🔁 **Hot Reloading:** Modify upstreams on the fly via `upstreams.yaml` — no restart needed.
|
||||||
- 🔮 **Automatic WebSocket Support:** Zero config — connection upgrades are handled seamlessly
|
- 🔮 **Automatic WebSocket Support:** Zero config — connection upgrades are handled seamlessly.
|
||||||
- 🔮 **Automatic GRPC Support:** Zero config, Requires `ssl` to proxy, gRPC is handled seamlessly
|
- 🔮 **Automatic GRPC Support:** Zero config, Requires `ssl` to proxy, gRPC is handled seamlessly.
|
||||||
- 🔮 **Upstreams Session Stickiness:** Enable/Disable Sticky session support with single parameter in config file
|
- 🔮 **Upstreams Session Stickiness:** Enable/Disable Sticky sessions.
|
||||||
- 🔐 **TLS Termination:** Fully supports TLS for incoming and upstream traffic
|
- 🔐 **TLS Termination:** Fully supports TLS for incoming and upstream traffic.
|
||||||
- 🛡️ **Built-in Authentication** Basic Auth, JWT, API key
|
- 🛡️ **Built-in Authentication** Basic Auth, JWT, API key.
|
||||||
- 🧠 **Header Injection:** Global and per-route header configuration
|
- 🧠 **Header Injection:** Global and per-route header configuration.
|
||||||
- 🧪 **Health Checks:** Pluggable health check methods for upstreams
|
- 🧪 **Health Checks:** Pluggable health check methods for upstreams.
|
||||||
- 🛰️ **Remote Config Push:** Lightweight HTTP API to update configs from CI/CD or other systems
|
- 🛰️ **Remote Config Push:** Lightweight HTTP API to update configs from CI/CD or other systems.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -82,7 +82,16 @@ Built on Rust, on top of **Cloudflare’s Pingora engine**, **Gazan** delivers w
|
|||||||
## 🛠 Installation
|
## 🛠 Installation
|
||||||
|
|
||||||
Download the prebuilt binary for your architecture from releases section of [GitHub](https://github.com/sadoyan/gazan/releases) repo
|
Download the prebuilt binary for your architecture from releases section of [GitHub](https://github.com/sadoyan/gazan/releases) repo
|
||||||
Make the binary executable `chmod 755 ./gazan` and run .
|
Make the binary executable `chmod 755 ./gazan-VERSION` and run.
|
||||||
|
|
||||||
|
File names:
|
||||||
|
|
||||||
|
| File Name | Description |
|
||||||
|
|--------------------------|---------------------------------------------------------------|
|
||||||
|
| `gazan-x86_64-musl.gz` | Static Linux x86_64 binary, without any system dependency |
|
||||||
|
| `gazan-x86_64-glibc.gz` | Dynamic Linux x86_64 binary, with minimal system dependencies |
|
||||||
|
| `gazan-aarch64-musl.gz` | Static Linux ARM64 binary, without any system dependency |
|
||||||
|
| `gazan-aarch64-glibc.gz` | Dynamic Linux ARM64 binary, with minimal system dependencies |
|
||||||
|
|
||||||
## 🔌 Running the Proxy
|
## 🔌 Running the Proxy
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# Main configuration file , applied on startup
|
# Main configuration file , applied on startup
|
||||||
threads: 8 # Nubber of daemon threads default setting
|
threads: 12 # Nubber of daemon threads default setting
|
||||||
#user: pastor # Username for running gazan after dropping root privileges, requires program to start as root
|
#user: pastor # Username for running gazan after dropping root privileges, requires program to start as root
|
||||||
#group: pastor # Group for running gazan after dropping root privileges, requires program to start as root
|
#group: pastor # Group for running gazan after dropping root privileges, requires program to start as root
|
||||||
daemon: false # Run in background
|
daemon: false # Run in background
|
||||||
|
|||||||
@@ -8,12 +8,12 @@ globals:
|
|||||||
- "Access-Control-Max-Age:86400"
|
- "Access-Control-Max-Age:86400"
|
||||||
- "X-Custom-Header:Something Special"
|
- "X-Custom-Header:Something Special"
|
||||||
# authorization: # Optional, only one of auth methods below can be active at a time
|
# authorization: # Optional, only one of auth methods below can be active at a time
|
||||||
# - "basic"
|
|
||||||
# - "gazan:Gazanpass1234"
|
|
||||||
# - "apikey"
|
|
||||||
# - "5a28cc4c-ce10-4ff1-824e-743c38835f5c"
|
|
||||||
# - "jwt"
|
# - "jwt"
|
||||||
# - "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
# - "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||||
|
# - "basic"
|
||||||
|
# - "zangag:Anhnazand1234"
|
||||||
|
# - "apikey"
|
||||||
|
# - "5a28cc4c-ce10-4ff1-824e-743c38835f5c"
|
||||||
consul: # If the provider is consul. Otherwise ignored
|
consul: # If the provider is consul. Otherwise ignored
|
||||||
servers:
|
servers:
|
||||||
- "http://master1:8500"
|
- "http://master1:8500"
|
||||||
@@ -68,11 +68,6 @@ upstreams: # If provider is files. Otherwise ignored
|
|||||||
servers:
|
servers:
|
||||||
- "192.168.1.10:8000"
|
- "192.168.1.10:8000"
|
||||||
- "192.168.1.1:8000"
|
- "192.168.1.1:8000"
|
||||||
apt.netangels.net:
|
|
||||||
paths:
|
|
||||||
"/":
|
|
||||||
servers:
|
|
||||||
- "apt.netangels.net:443"
|
|
||||||
test.netangels.net:
|
test.netangels.net:
|
||||||
paths:
|
paths:
|
||||||
"/":
|
"/":
|
||||||
@@ -93,3 +88,13 @@ upstreams: # If provider is files. Otherwise ignored
|
|||||||
"/":
|
"/":
|
||||||
servers:
|
servers:
|
||||||
- "127.0.0.1:9000"
|
- "127.0.0.1:9000"
|
||||||
|
ajbever.com:
|
||||||
|
paths:
|
||||||
|
"/":
|
||||||
|
servers:
|
||||||
|
- "ajbever.com:443"
|
||||||
|
apt.netangels.net:
|
||||||
|
paths:
|
||||||
|
"/":
|
||||||
|
servers:
|
||||||
|
- "85.17.24.1:443"
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
mod utils;
|
mod utils;
|
||||||
mod web;
|
mod web;
|
||||||
|
|
||||||
|
#[global_allocator]
|
||||||
|
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
web::start::run();
|
web::start::run();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ async fn consul_request(url: String, whitelist: Option<Vec<ServiceMapping>>, tok
|
|||||||
Some(upstreams)
|
Some(upstreams)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_by_http(url: String, token: Option<String>) -> Option<DashMap<String, (Vec<(String, u16, bool)>, AtomicUsize)>> {
|
async fn get_by_http(url: String, token: Option<String>) -> Option<DashMap<String, (Vec<(String, u16, bool, bool)>, AtomicUsize)>> {
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let mut headers = HeaderMap::new();
|
let mut headers = HeaderMap::new();
|
||||||
if let Some(token) = token {
|
if let Some(token) = token {
|
||||||
@@ -118,7 +118,7 @@ async fn get_by_http(url: String, token: Option<String>) -> Option<DashMap<Strin
|
|||||||
let to = Duration::from_secs(1);
|
let to = Duration::from_secs(1);
|
||||||
let u = client.get(url).timeout(to).send();
|
let u = client.get(url).timeout(to).send();
|
||||||
let mut values = Vec::new();
|
let mut values = Vec::new();
|
||||||
let upstreams: DashMap<String, (Vec<(String, u16, bool)>, AtomicUsize)> = DashMap::new();
|
let upstreams: DashMap<String, (Vec<(String, u16, bool, bool)>, AtomicUsize)> = DashMap::new();
|
||||||
match u.await {
|
match u.await {
|
||||||
Ok(r) => {
|
Ok(r) => {
|
||||||
let jason = r.json::<Vec<Service>>().await;
|
let jason = r.json::<Vec<Service>>().await;
|
||||||
@@ -127,7 +127,7 @@ async fn get_by_http(url: String, token: Option<String>) -> Option<DashMap<Strin
|
|||||||
for service in whitelist {
|
for service in whitelist {
|
||||||
let addr = service.tagged_addresses.get("lan_ipv4").unwrap().address.clone();
|
let addr = service.tagged_addresses.get("lan_ipv4").unwrap().address.clone();
|
||||||
let prt = service.tagged_addresses.get("lan_ipv4").unwrap().port.clone();
|
let prt = service.tagged_addresses.get("lan_ipv4").unwrap().port.clone();
|
||||||
let to_add = (addr, prt, false);
|
let to_add = (addr, prt, false, false);
|
||||||
values.push(to_add);
|
values.push(to_add);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use crate::utils::structs::{UpstreamsDashMap, UpstreamsIdMap};
|
|||||||
use crate::utils::tools::*;
|
use crate::utils::tools::*;
|
||||||
use dashmap::DashMap;
|
use dashmap::DashMap;
|
||||||
use log::{error, info, warn};
|
use log::{error, info, warn};
|
||||||
use reqwest::Client;
|
use reqwest::{Client, Version};
|
||||||
use std::sync::atomic::AtomicUsize;
|
use std::sync::atomic::AtomicUsize;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -20,32 +20,50 @@ pub async fn hc2(upslist: Arc<UpstreamsDashMap>, fullist: Arc<UpstreamsDashMap>,
|
|||||||
for val in fclone.iter() {
|
for val in fclone.iter() {
|
||||||
let host = val.key();
|
let host = val.key();
|
||||||
let inner = DashMap::new();
|
let inner = DashMap::new();
|
||||||
let mut _scheme: (String, u16, bool) = ("".to_string(), 0, false);
|
let mut _scheme: (String, u16, bool, bool) = ("".to_string(), 0, false, false);
|
||||||
for path_entry in val.value().iter() {
|
for path_entry in val.value().iter() {
|
||||||
// let inner = DashMap::new();
|
// let inner = DashMap::new();
|
||||||
let path = path_entry.key();
|
let path = path_entry.key();
|
||||||
let mut innervec= Vec::new();
|
let mut innervec= Vec::new();
|
||||||
for k in path_entry.value().0 .iter().enumerate() {
|
for k in path_entry.value().0 .iter().enumerate() {
|
||||||
let (ip, port, _ssl) = k.1;
|
let (ip, port, _ssl, _version) = k.1;
|
||||||
let mut _pref = "";
|
let mut _link = String::new();
|
||||||
let tls = detect_tls(ip, port).await;
|
let tls = detect_tls(ip, port).await;
|
||||||
match tls {
|
let mut is_h2 = false;
|
||||||
true => _pref = "https://",
|
|
||||||
false => _pref = "http://",
|
// if tls.1 == Some(Version::HTTP_11) {
|
||||||
|
// println!(" V1: ==> {:?}", tls.1)
|
||||||
|
// }else if tls.1 == Some(Version::HTTP_2) {
|
||||||
|
// is_h2 = true;
|
||||||
|
// println!(" V2: ==> {:?}", tls.1)
|
||||||
|
// }
|
||||||
|
|
||||||
|
if tls.1 == Some(Version::HTTP_2) {
|
||||||
|
is_h2 = true;
|
||||||
|
// println!(" V2: ==> {} ==> {:?}", tls.0, tls.1)
|
||||||
}
|
}
|
||||||
if _pref == "https://" {
|
|
||||||
_scheme = (ip.to_string(), *port, true);
|
match tls.0 {
|
||||||
}else {
|
true => _link = format!("https://{}:{}{}", ip, port, path),
|
||||||
_scheme = (ip.to_string(), *port, false);
|
false => _link = format!("http://{}:{}{}", ip, port, path),
|
||||||
}
|
}
|
||||||
let link = format!("{}{}:{}{}", _pref, ip, port, path);
|
// if _pref == "https://" {
|
||||||
let resp = http_request(link.as_str(), params.0, "").await;
|
// _scheme = (ip.to_string(), *port, true);
|
||||||
match resp {
|
// }else {
|
||||||
|
// _scheme = (ip.to_string(), *port, false);
|
||||||
|
// }
|
||||||
|
_scheme = (ip.to_string(), *port, tls.0, is_h2);
|
||||||
|
// let link = format!("{}{}:{}{}", _pref, ip, port, path);
|
||||||
|
let resp = http_request(_link.as_str(), params.0, "").await;
|
||||||
|
match resp.0 {
|
||||||
true => {
|
true => {
|
||||||
|
if resp.1 {
|
||||||
|
_scheme = (ip.to_string(), *port, tls.0, true);
|
||||||
|
}
|
||||||
innervec.push(_scheme.clone());
|
innervec.push(_scheme.clone());
|
||||||
}
|
}
|
||||||
false => {
|
false => {
|
||||||
warn!("Dead Upstream : {}", link);
|
warn!("Dead Upstream : {}", _link);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,12 +91,12 @@ pub async fn hc2(upslist: Arc<UpstreamsDashMap>, fullist: Arc<UpstreamsDashMap>,
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
async fn http_request(url: &str, method: &str, payload: &str) -> bool {
|
async fn http_request(url: &str, method: &str, payload: &str) -> (bool, bool) {
|
||||||
let client = Client::builder().danger_accept_invalid_certs(true).build().unwrap();
|
let client = Client::builder().danger_accept_invalid_certs(true).build().unwrap();
|
||||||
let timeout = Duration::from_secs(1);
|
let timeout = Duration::from_secs(1);
|
||||||
if !["POST", "GET", "HEAD"].contains(&method) {
|
if !["POST", "GET", "HEAD"].contains(&method) {
|
||||||
error!("Method {} not supported. Only GET|POST|HEAD are supported ", method);
|
error!("Method {} not supported. Only GET|POST|HEAD are supported ", method);
|
||||||
return false;
|
return (false, false);
|
||||||
}
|
}
|
||||||
async fn send_request(client: &Client, method: &str, url: &str, payload: &str, timeout: Duration) -> Option<reqwest::Response> {
|
async fn send_request(client: &Client, method: &str, url: &str, payload: &str, timeout: Duration) -> Option<reqwest::Response> {
|
||||||
match method {
|
match method {
|
||||||
@@ -92,11 +110,12 @@ async fn http_request(url: &str, method: &str, payload: &str) -> bool {
|
|||||||
match send_request(&client, method, url, payload, timeout).await {
|
match send_request(&client, method, url, payload, timeout).await {
|
||||||
Some(response) => {
|
Some(response) => {
|
||||||
let status = response.status().as_u16();
|
let status = response.status().as_u16();
|
||||||
(99..499).contains(&status)
|
((99..499).contains(&status), false)
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
let fallback_url = url.replace("https", "http");
|
// let fallback_url = url.replace("https", "http");
|
||||||
ping_grpc(&fallback_url).await
|
// ping_grpc(&fallback_url).await
|
||||||
|
(ping_grpc(&url).await, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,7 +127,10 @@ pub async fn ping_grpc(addr: &str) -> bool {
|
|||||||
let endpoint = endpoint.timeout(Duration::from_secs(2));
|
let endpoint = endpoint.timeout(Duration::from_secs(2));
|
||||||
|
|
||||||
match tokio::time::timeout(Duration::from_secs(3), endpoint.connect()).await {
|
match tokio::time::timeout(Duration::from_secs(3), endpoint.connect()).await {
|
||||||
Ok(Ok(_channel)) => true,
|
Ok(Ok(_channel)) => {
|
||||||
|
// println!("{:?} ==> {:?} ==> {}", endpoint, _channel, addr);
|
||||||
|
true
|
||||||
|
}
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -116,20 +138,17 @@ pub async fn ping_grpc(addr: &str) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn detect_tls(ip: &str, port: &u16) -> bool {
|
async fn detect_tls(ip: &str, port: &u16) -> (bool, Option<Version>) {
|
||||||
let url = format!("https://{}:{}", ip, port);
|
let url = format!("https://{}:{}", ip, port);
|
||||||
let client = Client::builder()
|
// let url = format!("{}:{}", ip, port);
|
||||||
.timeout(Duration::from_secs(2))
|
let client = Client::builder().timeout(Duration::from_secs(2)).danger_accept_invalid_certs(true).build().unwrap();
|
||||||
.danger_accept_invalid_certs(true) // skip cert validation for testing
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
match client.get(&url).send().await {
|
match client.get(&url).send().await {
|
||||||
Ok(_) => true,
|
Ok(response) => (true, Some(response.version())),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
if e.is_builder() || e.is_connect() || e.to_string().contains("tls") {
|
if e.is_builder() || e.is_connect() || e.to_string().contains("tls") {
|
||||||
false
|
(false, None)
|
||||||
} else {
|
} else {
|
||||||
false
|
(false, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
|||||||
if let Some((ip, port_str)) = server.split_once(':') {
|
if let Some((ip, port_str)) = server.split_once(':') {
|
||||||
if let Ok(port) = port_str.parse::<u16>() {
|
if let Ok(port) = port_str.parse::<u16>() {
|
||||||
// server_list.push((ip.to_string(), port, path_config.ssl));
|
// server_list.push((ip.to_string(), port, path_config.ssl));
|
||||||
server_list.push((ip.to_string(), port, true));
|
server_list.push((ip.to_string(), port, true, false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::atomic::AtomicUsize;
|
use std::sync::atomic::AtomicUsize;
|
||||||
|
|
||||||
pub type UpstreamsDashMap = DashMap<String, DashMap<String, (Vec<(String, u16, bool)>, AtomicUsize)>>;
|
pub type UpstreamsDashMap = DashMap<String, DashMap<String, (Vec<(String, u16, bool, bool)>, AtomicUsize)>>;
|
||||||
|
pub type UpstreamsIdMap = DashMap<String, (String, u16, bool, bool)>;
|
||||||
pub type Headers = DashMap<String, DashMap<String, Vec<(String, String)>>>;
|
pub type Headers = DashMap<String, DashMap<String, Vec<(String, String)>>>;
|
||||||
pub type UpstreamsIdMap = DashMap<String, (String, u16, bool)>;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ServiceMapping {
|
pub struct ServiceMapping {
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ pub fn print_upstreams(upstreams: &UpstreamsDashMap) {
|
|||||||
let path = path_entry.key();
|
let path = path_entry.key();
|
||||||
println!(" Path: {}", path);
|
println!(" Path: {}", path);
|
||||||
|
|
||||||
for (ip, port, ssl) in path_entry.value().0.clone() {
|
for (ip, port, ssl, vers) in path_entry.value().0.clone() {
|
||||||
println!(" ===> IP: {}, Port: {}, SSL: {}", ip, port, ssl);
|
println!(" ===> IP: {}, Port: {}, SSL: {}, H2: {}", ip, port, ssl, vers);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,7 +139,7 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
|
|||||||
let hash = hasher.finalize();
|
let hash = hasher.finalize();
|
||||||
let hex_hash = base16ct::lower::encode_string(&hash);
|
let hex_hash = base16ct::lower::encode_string(&hash);
|
||||||
let hh = hex_hash[0..50].to_string();
|
let hh = hex_hash[0..50].to_string();
|
||||||
cloned.insert(id, (hh.clone(), 0000, false));
|
cloned.insert(id, (hh.clone(), 0000, false, false));
|
||||||
cloned.insert(hh, x.to_owned());
|
cloned.insert(hh, x.to_owned());
|
||||||
}
|
}
|
||||||
new_inner_map.insert(path.clone(), new_vec);
|
new_inner_map.insert(path.clone(), new_vec);
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ use std::sync::atomic::Ordering;
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait GetHost {
|
pub trait GetHost {
|
||||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<(String, u16, bool)>;
|
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<(String, u16, bool, bool)>;
|
||||||
fn get_header(&self, peer: &str, path: &str) -> Option<Vec<(String, String)>>;
|
fn get_header(&self, peer: &str, path: &str) -> Option<Vec<(String, String)>>;
|
||||||
}
|
}
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl GetHost for LB {
|
impl GetHost for LB {
|
||||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<(String, u16, bool)> {
|
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<(String, u16, bool, bool)> {
|
||||||
if let Some(b) = backend_id {
|
if let Some(b) = backend_id {
|
||||||
if let Some(bb) = self.ump_byid.get(b) {
|
if let Some(bb) = self.ump_byid.get(b) {
|
||||||
// println!("BIB :===> {:?}", Some(bb.value()));
|
// println!("BIB :===> {:?}", Some(bb.value()));
|
||||||
@@ -19,7 +19,7 @@ impl GetHost for LB {
|
|||||||
|
|
||||||
let host_entry = self.ump_upst.get(peer)?;
|
let host_entry = self.ump_upst.get(peer)?;
|
||||||
let mut current_path = path.to_string();
|
let mut current_path = path.to_string();
|
||||||
let mut best_match: Option<(String, u16, bool)> = None;
|
let mut best_match: Option<(String, u16, bool, bool)> = None;
|
||||||
loop {
|
loop {
|
||||||
if let Some(entry) = host_entry.get(¤t_path) {
|
if let Some(entry) = host_entry.get(¤t_path) {
|
||||||
let (servers, index) = entry.value();
|
let (servers, index) = entry.value();
|
||||||
|
|||||||
@@ -33,52 +33,6 @@ impl ProxyHttp for LB {
|
|||||||
fn new_ctx(&self) -> Self::CTX {
|
fn new_ctx(&self) -> Self::CTX {
|
||||||
Context { backend_id: String::new() }
|
Context { backend_id: String::new() }
|
||||||
}
|
}
|
||||||
async fn upstream_peer(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<Box<HttpPeer>> {
|
|
||||||
let host_name = return_header_host(&session);
|
|
||||||
|
|
||||||
match host_name {
|
|
||||||
Some(host) => {
|
|
||||||
// session.req_header_mut().headers.insert("X-Host-Name", host.to_string().parse().unwrap());
|
|
||||||
|
|
||||||
let mut backend_id = None;
|
|
||||||
if self.extraparams.load().stickysessions {
|
|
||||||
if let Some(cookies) = session.req_header().headers.get("cookie") {
|
|
||||||
if let Ok(cookie_str) = cookies.to_str() {
|
|
||||||
for cookie in cookie_str.split(';') {
|
|
||||||
let trimmed = cookie.trim();
|
|
||||||
if let Some(value) = trimmed.strip_prefix("backend_id=") {
|
|
||||||
backend_id = Some(value);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let ddr = self.get_host(host, host, backend_id);
|
|
||||||
|
|
||||||
match ddr {
|
|
||||||
Some((host, port, ssl)) => {
|
|
||||||
// let mut peer = Box::new(HttpPeer::new((host, port), ssl, String::new()));
|
|
||||||
let mut peer = Box::new(HttpPeer::new((host.clone(), port.clone()), ssl, String::new()));
|
|
||||||
if session.is_http2() {
|
|
||||||
peer.options.alpn = ALPN::H2;
|
|
||||||
}
|
|
||||||
_ctx.backend_id = format!("{}:{}:{}", host.clone(), port.clone(), ssl);
|
|
||||||
Ok(peer)
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
warn!("Upstream not found. Host: {:?}, Path: {}", host, session.req_header().uri);
|
|
||||||
Ok(return_no_host(&self.config.local_server))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
warn!("Upstream not found. Host: {:?}, Path: {}", host_name, session.req_header().uri);
|
|
||||||
Ok(return_no_host(&self.config.local_server))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
|
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
|
||||||
if let Some(auth) = self.extraparams.load().authentication.get("authorization") {
|
if let Some(auth) = self.extraparams.load().authentication.get("authorization") {
|
||||||
let authenticated = authenticate(&auth.value(), &session);
|
let authenticated = authenticate(&auth.value(), &session);
|
||||||
@@ -95,6 +49,58 @@ impl ProxyHttp for LB {
|
|||||||
// };
|
// };
|
||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
|
async fn upstream_peer(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<Box<HttpPeer>> {
|
||||||
|
let host_name = return_header_host(&session);
|
||||||
|
|
||||||
|
match host_name {
|
||||||
|
Some(hostname) => {
|
||||||
|
// session.req_header_mut().headers.insert("X-Host-Name", host.to_string().parse().unwrap());
|
||||||
|
let mut backend_id = None;
|
||||||
|
if self.extraparams.load().stickysessions {
|
||||||
|
if let Some(cookies) = session.req_header().headers.get("cookie") {
|
||||||
|
if let Ok(cookie_str) = cookies.to_str() {
|
||||||
|
for cookie in cookie_str.split(';') {
|
||||||
|
let trimmed = cookie.trim();
|
||||||
|
if let Some(value) = trimmed.strip_prefix("backend_id=") {
|
||||||
|
backend_id = Some(value);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let ddr = self.get_host(hostname, hostname, backend_id);
|
||||||
|
|
||||||
|
match ddr {
|
||||||
|
Some((address, port, ssl, is_h2)) => {
|
||||||
|
let mut peer = Box::new(HttpPeer::new((address.clone(), port.clone()), ssl, String::new()));
|
||||||
|
// if session.is_http2() {
|
||||||
|
if is_h2 {
|
||||||
|
peer.options.alpn = ALPN::H2;
|
||||||
|
}
|
||||||
|
if ssl {
|
||||||
|
peer.sni = hostname.to_string();
|
||||||
|
peer.options.verify_cert = false;
|
||||||
|
peer.options.verify_hostname = false;
|
||||||
|
}
|
||||||
|
// println!(" ==> {} ==> {} => {} => {:?}", hostname, address.as_str(), peer.options.alpn, is_h2);
|
||||||
|
_ctx.backend_id = format!("{}:{}:{}", address.clone(), port.clone(), ssl);
|
||||||
|
Ok(peer)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
warn!("Upstream not found. Host: {:?}, Path: {}", hostname, session.req_header().uri);
|
||||||
|
Ok(return_no_host(&self.config.local_server))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
warn!("Upstream not found. Host: {:?}, Path: {}", host_name, session.req_header().uri);
|
||||||
|
Ok(return_no_host(&self.config.local_server))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn upstream_request_filter(&self, _session: &mut Session, _upstream_request: &mut RequestHeader, _ctx: &mut Self::CTX) -> Result<()> {
|
async fn upstream_request_filter(&self, _session: &mut Session, _upstream_request: &mut RequestHeader, _ctx: &mut Self::CTX) -> Result<()> {
|
||||||
let clientip = _session.client_addr();
|
let clientip = _session.client_addr();
|
||||||
match clientip {
|
match clientip {
|
||||||
@@ -118,7 +124,6 @@ impl ProxyHttp for LB {
|
|||||||
|
|
||||||
async fn response_filter(&self, _session: &mut Session, _upstream_response: &mut ResponseHeader, _ctx: &mut Self::CTX) -> Result<()> {
|
async fn response_filter(&self, _session: &mut Session, _upstream_response: &mut ResponseHeader, _ctx: &mut Self::CTX) -> Result<()> {
|
||||||
// _upstream_response.insert_header("X-Proxied-From", "Fooooooooooooooo").unwrap();
|
// _upstream_response.insert_header("X-Proxied-From", "Fooooooooooooooo").unwrap();
|
||||||
|
|
||||||
if self.extraparams.load().stickysessions {
|
if self.extraparams.load().stickysessions {
|
||||||
let backend_id = _ctx.backend_id.clone();
|
let backend_id = _ctx.backend_id.clone();
|
||||||
if let Some(bid) = self.ump_byid.get(&backend_id) {
|
if let Some(bid) = self.ump_byid.get(&backend_id) {
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ use dashmap::DashMap;
|
|||||||
use log::info;
|
use log::info;
|
||||||
use pingora_core::prelude::{background_service, Opt};
|
use pingora_core::prelude::{background_service, Opt};
|
||||||
use pingora_core::server::Server;
|
use pingora_core::server::Server;
|
||||||
|
use rustls::crypto::ring::default_provider;
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
|
default_provider().install_default().expect("Failed to install rustls crypto provider");
|
||||||
let parameters = Some(Opt::parse_args()).unwrap();
|
let parameters = Some(Opt::parse_args()).unwrap();
|
||||||
let file = parameters.conf.clone().unwrap();
|
let file = parameters.conf.clone().unwrap();
|
||||||
let maincfg = crate::utils::parceyaml::parce_main_config(file.as_str());
|
let maincfg = crate::utils::parceyaml::parce_main_config(file.as_str());
|
||||||
|
|||||||
Reference in New Issue
Block a user