mirror of
https://github.com/sadoyan/aralez.git
synced 2026-04-30 23:08:40 +08:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a89592bd07 | ||
|
|
2a93bc2cd6 | ||
|
|
d38588a299 | ||
|
|
3e93920a0d |
26
README.md
26
README.md
@@ -123,18 +123,19 @@ A sample `upstreams.yaml` entry:
|
||||
|
||||
```yaml
|
||||
provider: "file"
|
||||
stickysessions: false
|
||||
globals:
|
||||
headers:
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
authorization:
|
||||
- "jwt"
|
||||
- "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||
sticky_sessions: false
|
||||
to_ssl: false
|
||||
headers:
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
authorization:
|
||||
type: "jwt"
|
||||
creds: "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||
myhost.mydomain.com:
|
||||
paths:
|
||||
"/":
|
||||
to_https: false
|
||||
headers:
|
||||
- "X-Some-Thing:Yaaaaaaaaaaaaaaa"
|
||||
- "X-Proxy-From:Hopaaaaaaaaaaaar"
|
||||
@@ -142,6 +143,7 @@ myhost.mydomain.com:
|
||||
- "127.0.0.1:8000"
|
||||
- "127.0.0.2:8000"
|
||||
"/foo":
|
||||
to_https: true
|
||||
headers:
|
||||
- "X-Another-Header:Hohohohoho"
|
||||
servers:
|
||||
@@ -151,15 +153,17 @@ myhost.mydomain.com:
|
||||
|
||||
**This means:**
|
||||
|
||||
- Sticky sessions are disabled globally. This setting applies to all upstreams.
|
||||
- Sticky sessions are disabled globally. This setting applies to all upstreams. If enabled all requests will be 301 redirected to HTTPS.
|
||||
- HTTP to HTTPS redirect disabled globally, but can be overridden by `to_https` setting per upstream.
|
||||
- Requests to `myhost.mydomain.com/` will be proxied to `127.0.0.1` and `127.0.0.2`.
|
||||
- Plain HTTP to `myhost.mydomain.com/foo` will get 301 redirect to configured TLS port of Gazan.
|
||||
- Requests to `myhost.mydomain.com/foo` will be proxied to `127.0.0.4` and `127.0.0.5`.
|
||||
- SSL/TLS for upstreams is detected automatically, no need to set any config parameter.
|
||||
- Assuming the `127.0.0.5:8443` is SSL protected. The inner traffic will use TLS.
|
||||
- Self signed certificates are silently accepted.
|
||||
- Global headers (CORS for this case) will be injected to all upstreams
|
||||
- Additional headers will be injected into the request for `myhost.mydomain.com`.
|
||||
- You can choose any path, deep nested paths are supported, the best match is chosen.
|
||||
- You can choose any path, deep nested paths are supported, the best match chosen.
|
||||
- All requests to servers will require JWT token authentication (You can comment out the authorization to disable it),
|
||||
- Firs parameter specifies the mechanism of authorisation `jwt`
|
||||
- Second is the secret key for validating `jwt` tokens
|
||||
|
||||
@@ -1,37 +1,34 @@
|
||||
# The file is under watch and hot reload , changes are applied immediately, no need to restart or reload
|
||||
# The file under watch and hot reload, changes are applied immediately, no need to restart or reload.
|
||||
provider: "file" # consul
|
||||
stickysessions: true
|
||||
globals:
|
||||
headers: # Global headers, appended for all upstreams and all paths.
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
- "X-Custom-Header:Something Special"
|
||||
# authorization: # Optional, only one of auth methods below can be active at a time
|
||||
# - "basic"
|
||||
# - "gazan:Gazanpass1234"
|
||||
# - "apikey"
|
||||
# - "5a28cc4c-ce10-4ff1-824e-743c38835f5c"
|
||||
# - "jwt"
|
||||
# - "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||
consul: # If the provider is consul. Otherwise ignored
|
||||
sticky_sessions: false
|
||||
to_ssl: false
|
||||
headers:
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
- "X-Custom-Header:Something Special"
|
||||
authorization:
|
||||
type: "jwt"
|
||||
creds: "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||
# name: "basic"
|
||||
# creds: "user:Passw0rd"
|
||||
# name: "apikey"
|
||||
# creds: "5ecbf799-1343-4e94-a9b5-e278af5cd313-56b45249-1839-4008-a450-a60dc76d2bae"
|
||||
consul: # If the provider is consul. Otherwise, ignored.
|
||||
servers:
|
||||
- "http://master1:8500"
|
||||
- "http://192.168.22.1:8500"
|
||||
- "http://master1.digitai.local:8500"
|
||||
services: # proxy: The hostname to access proxy server, real : The real service name in Consul
|
||||
- "http://master1.foo.local:8500"
|
||||
services: # proxy: The hostname to access the proxy server, real : The real service name in Consul database.
|
||||
- proxy: "proxy-frontend-dev-frontend-srv"
|
||||
real: "frontend-dev-frontend-srv"
|
||||
# - proxy: "proxy-gateway-test-gateway-srv"
|
||||
# real: "gateway-test-gateway-srv"
|
||||
# - proxy: "proxy-backoffice-dev-backoffice-srv"
|
||||
# real: "backoffice-dev-backoffice-srv"
|
||||
token: "8e2db809-845b-45e1-8b47-2c8356a09da0-a4370955-18c2-4d6e-a8f8-ffcc0b47be81" # Consul server access token, If Consul auth is enabled
|
||||
upstreams: # If provider is files. Otherwise ignored
|
||||
myip.netangels.net: # Hostname, or header host to access the upstream
|
||||
paths: # URL path(s) for current upstream, closest match wins
|
||||
upstreams:
|
||||
myip.mydomain.com:
|
||||
paths:
|
||||
"/":
|
||||
headers: # Custom headers, set only for this Host and Path
|
||||
to_https: false
|
||||
headers:
|
||||
- "X-Proxy-From:Gazan"
|
||||
servers: # List of upstreams HOST:PORT
|
||||
- "127.0.0.1:8000"
|
||||
@@ -39,6 +36,7 @@ upstreams: # If provider is files. Otherwise ignored
|
||||
- "127.0.0.3:8000"
|
||||
- "127.0.0.4:8000"
|
||||
"/ping":
|
||||
to_https: true
|
||||
headers:
|
||||
- "X-Some-Thing:Yaaaaaaaaaaaaaaa"
|
||||
- "X-Proxy-From:Gazan"
|
||||
@@ -48,7 +46,7 @@ upstreams: # If provider is files. Otherwise ignored
|
||||
"/draw":
|
||||
servers:
|
||||
- "192.168.1.1:8000"
|
||||
polo.netangels.net:
|
||||
polo.mydomain.com:
|
||||
paths:
|
||||
"/":
|
||||
headers:
|
||||
@@ -60,36 +58,3 @@ upstreams: # If provider is files. Otherwise ignored
|
||||
- "127.0.0.2:8000"
|
||||
- "127.0.0.3:8000"
|
||||
- "127.0.0.4:8000"
|
||||
glop.netangels.net:
|
||||
paths:
|
||||
"/":
|
||||
headers:
|
||||
- "X-Hopar-From:Hopaaaaaaaaaaaar"
|
||||
servers:
|
||||
- "192.168.1.10:8000"
|
||||
- "192.168.1.1:8000"
|
||||
apt.netangels.net:
|
||||
paths:
|
||||
"/":
|
||||
servers:
|
||||
- "apt.netangels.net:443"
|
||||
test.netangels.net:
|
||||
paths:
|
||||
"/":
|
||||
servers:
|
||||
- "myip.netangels.net:80"
|
||||
127.0.0.1:
|
||||
paths:
|
||||
"/":
|
||||
servers:
|
||||
- "192.168.1.5:8080"
|
||||
127.0.0.2:
|
||||
paths:
|
||||
"/":
|
||||
servers:
|
||||
- "10.0.55.171:3000"
|
||||
localpost:
|
||||
paths:
|
||||
"/":
|
||||
servers:
|
||||
- "127.0.0.1:9000"
|
||||
@@ -109,7 +109,7 @@ async fn consul_request(url: String, whitelist: Option<Vec<ServiceMapping>>, tok
|
||||
Some(upstreams)
|
||||
}
|
||||
|
||||
async fn get_by_http(url: String, token: Option<String>) -> Option<DashMap<String, (Vec<(String, u16, bool, bool)>, AtomicUsize)>> {
|
||||
async fn get_by_http(url: String, token: Option<String>) -> Option<DashMap<String, (Vec<(String, u16, bool, bool, bool)>, AtomicUsize)>> {
|
||||
let client = reqwest::Client::new();
|
||||
let mut headers = HeaderMap::new();
|
||||
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 u = client.get(url).timeout(to).send();
|
||||
let mut values = Vec::new();
|
||||
let upstreams: DashMap<String, (Vec<(String, u16, bool, bool)>, AtomicUsize)> = DashMap::new();
|
||||
let upstreams: DashMap<String, (Vec<(String, u16, bool, bool, bool)>, AtomicUsize)> = DashMap::new();
|
||||
match u.await {
|
||||
Ok(r) => {
|
||||
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 {
|
||||
let addr = service.tagged_addresses.get("lan_ipv4").unwrap().address.clone();
|
||||
let prt = service.tagged_addresses.get("lan_ipv4").unwrap().port.clone();
|
||||
let to_add = (addr, prt, false, false);
|
||||
let to_add = (addr, prt, false, false, false);
|
||||
values.push(to_add);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,13 +20,13 @@ pub async fn hc2(upslist: Arc<UpstreamsDashMap>, fullist: Arc<UpstreamsDashMap>,
|
||||
for val in fclone.iter() {
|
||||
let host = val.key();
|
||||
let inner = DashMap::new();
|
||||
let mut _scheme: (String, u16, bool, bool) = ("".to_string(), 0, false, false);
|
||||
let mut _scheme: (String, u16, bool, bool, bool) = ("".to_string(), 0, false, false, false);
|
||||
for path_entry in val.value().iter() {
|
||||
// let inner = DashMap::new();
|
||||
let path = path_entry.key();
|
||||
let mut innervec= Vec::new();
|
||||
for k in path_entry.value().0 .iter().enumerate() {
|
||||
let (ip, port, _ssl, _version) = k.1;
|
||||
let (ip, port, _ssl, _version, _redir) = k.1;
|
||||
let mut _link = String::new();
|
||||
let tls = detect_tls(ip, port).await;
|
||||
let mut is_h2 = false;
|
||||
@@ -52,13 +52,13 @@ pub async fn hc2(upslist: Arc<UpstreamsDashMap>, fullist: Arc<UpstreamsDashMap>,
|
||||
// }else {
|
||||
// _scheme = (ip.to_string(), *port, false);
|
||||
// }
|
||||
_scheme = (ip.to_string(), *port, tls.0, is_h2);
|
||||
_scheme = (ip.to_string(), *port, tls.0, is_h2, *_redir);
|
||||
// let link = format!("{}{}:{}{}", _pref, ip, port, path);
|
||||
let resp = http_request(_link.as_str(), params.0, "").await;
|
||||
match resp.0 {
|
||||
true => {
|
||||
if resp.1 {
|
||||
_scheme = (ip.to_string(), *port, tls.0, true);
|
||||
_scheme = (ip.to_string(), *port, tls.0, true, *_redir);
|
||||
}
|
||||
innervec.push(_scheme.clone());
|
||||
}
|
||||
@@ -75,7 +75,8 @@ pub async fn hc2(upslist: Arc<UpstreamsDashMap>, fullist: Arc<UpstreamsDashMap>,
|
||||
if first_run == 1 {
|
||||
info!("Performing initial hatchecks and upstreams ssl detection");
|
||||
clone_idmap_into(&totest, &idlist);
|
||||
info!("Gazan is up and ready to serve requests");
|
||||
info!("Gazan is up and ready to serve requests, the upstreams list is:");
|
||||
print_upstreams(&totest)
|
||||
}
|
||||
|
||||
first_run+=1;
|
||||
|
||||
@@ -13,7 +13,8 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
||||
consul: None,
|
||||
typecfg: "".to_string(),
|
||||
extraparams: Extraparams {
|
||||
stickysessions: false,
|
||||
sticky_sessions: false,
|
||||
to_ssl: None,
|
||||
authentication: DashMap::new(),
|
||||
},
|
||||
};
|
||||
@@ -46,25 +47,27 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
||||
Ok(parsed) => {
|
||||
let global_headers = DashMap::new();
|
||||
let mut hl = Vec::new();
|
||||
if let Some(globals) = &parsed.globals {
|
||||
for headers in globals.get("headers").iter().by_ref() {
|
||||
for header in headers.iter() {
|
||||
if let Some((key, val)) = header.split_once(':') {
|
||||
hl.push((key.to_string(), val.to_string()));
|
||||
}
|
||||
if let Some(headers) = &parsed.headers {
|
||||
for header in headers.iter() {
|
||||
if let Some((key, val)) = header.split_once(':') {
|
||||
hl.push((key.to_string(), val.to_string()));
|
||||
}
|
||||
}
|
||||
global_headers.insert("/".to_string(), hl);
|
||||
toreturn.headers.insert("GLOBAL_HEADERS".to_string(), global_headers);
|
||||
toreturn.extraparams.stickysessions = parsed.stickysessions;
|
||||
let cfg = DashMap::new();
|
||||
if let Some(k) = globals.get("authorization") {
|
||||
cfg.insert("authorization".to_string(), k.to_owned());
|
||||
toreturn.extraparams.authentication = cfg;
|
||||
} else {
|
||||
toreturn.extraparams.authentication = DashMap::new();
|
||||
}
|
||||
|
||||
toreturn.extraparams.sticky_sessions = parsed.sticky_sessions;
|
||||
toreturn.extraparams.to_ssl = parsed.to_ssl;
|
||||
}
|
||||
if let Some(auth) = &parsed.authorization {
|
||||
let name = auth.get("type").unwrap().to_string();
|
||||
let creds = auth.get("creds").unwrap().to_string();
|
||||
let val: Vec<String> = vec![name, creds];
|
||||
toreturn.extraparams.authentication.insert("authorization".to_string(), val);
|
||||
} else {
|
||||
toreturn.extraparams.authentication = DashMap::new();
|
||||
}
|
||||
|
||||
match parsed.provider.as_str() {
|
||||
"file" => {
|
||||
toreturn.typecfg = "file".to_string();
|
||||
@@ -86,8 +89,9 @@ pub fn load_configuration(d: &str, kind: &str) -> Option<Configuration> {
|
||||
for server in path_config.servers {
|
||||
if let Some((ip, port_str)) = server.split_once(':') {
|
||||
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, true, false));
|
||||
// let to_https = matches!(path_config.to_https, Some(true));
|
||||
let to_https = path_config.to_https.unwrap_or(false);
|
||||
server_list.push((ip.to_string(), port, true, false, to_https));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,5 +143,12 @@ pub fn parce_main_config(path: &str) -> AppConfig {
|
||||
cfo.local_server = Option::from((ip.to_string(), port));
|
||||
}
|
||||
}
|
||||
if let Some(tlsport_cfg) = cfo.proxy_address_tls.clone() {
|
||||
if let Some((_, port_str)) = tlsport_cfg.split_once(':') {
|
||||
if let Ok(port) = port_str.parse::<u16>() {
|
||||
cfo.proxy_port_tls = Some(port);
|
||||
}
|
||||
}
|
||||
};
|
||||
cfo
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@ use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::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 InnerMap = (String, u16, bool, bool, bool);
|
||||
pub type UpstreamsDashMap = DashMap<String, DashMap<String, (Vec<InnerMap>, AtomicUsize)>>;
|
||||
pub type UpstreamsIdMap = DashMap<String, InnerMap>;
|
||||
pub type Headers = DashMap<String, DashMap<String, Vec<(String, String)>>>;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -15,7 +16,8 @@ pub struct ServiceMapping {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Extraparams {
|
||||
pub stickysessions: bool,
|
||||
pub sticky_sessions: bool,
|
||||
pub to_ssl: Option<bool>,
|
||||
pub authentication: DashMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
@@ -28,9 +30,12 @@ pub struct Consul {
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
pub provider: String,
|
||||
pub stickysessions: bool,
|
||||
pub sticky_sessions: bool,
|
||||
pub to_ssl: Option<bool>,
|
||||
pub upstreams: Option<HashMap<String, HostConfig>>,
|
||||
pub globals: Option<HashMap<String, Vec<String>>>,
|
||||
pub headers: Option<Vec<String>>,
|
||||
pub authorization: Option<HashMap<String, String>>,
|
||||
pub consul: Option<Consul>,
|
||||
}
|
||||
|
||||
@@ -42,6 +47,7 @@ pub struct HostConfig {
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct PathConfig {
|
||||
pub servers: Vec<String>,
|
||||
pub to_https: Option<bool>,
|
||||
pub headers: Option<Vec<String>>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
@@ -63,6 +69,7 @@ pub struct AppConfig {
|
||||
pub proxy_address_http: String,
|
||||
pub master_key: String,
|
||||
pub proxy_address_tls: Option<String>,
|
||||
pub proxy_port_tls: Option<u16>,
|
||||
pub tls_certificate: Option<String>,
|
||||
pub tls_key_file: Option<String>,
|
||||
pub local_server: Option<(String, u16)>,
|
||||
|
||||
@@ -16,8 +16,8 @@ pub fn print_upstreams(upstreams: &UpstreamsDashMap) {
|
||||
let path = path_entry.key();
|
||||
println!(" Path: {}", path);
|
||||
|
||||
for (ip, port, ssl, vers) in path_entry.value().0.clone() {
|
||||
println!(" ===> IP: {}, Port: {}, SSL: {}, H2: {}", ip, port, ssl, vers);
|
||||
for (ip, port, ssl, vers, to_https) in path_entry.value().0.clone() {
|
||||
println!(" ===> IP: {}, Port: {}, SSL: {}, H2: {}, To HTTPS: {}", ip, port, ssl, vers, to_https);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
|
||||
let hash = hasher.finalize();
|
||||
let hex_hash = base16ct::lower::encode_string(&hash);
|
||||
let hh = hex_hash[0..50].to_string();
|
||||
cloned.insert(id, (hh.clone(), 0000, false, false));
|
||||
cloned.insert(id, (hh.clone(), 0000, false, false, false));
|
||||
cloned.insert(hh, x.to_owned());
|
||||
}
|
||||
new_inner_map.insert(path.clone(), new_vec);
|
||||
|
||||
@@ -56,7 +56,8 @@ impl BackgroundService for LB {
|
||||
clone_dashmap_into(&ss.upstreams, &self.ump_upst);
|
||||
let current = self.extraparams.load_full();
|
||||
let mut new = (*current).clone();
|
||||
new.stickysessions = ss.extraparams.stickysessions;
|
||||
new.sticky_sessions = ss.extraparams.sticky_sessions;
|
||||
new.to_ssl = ss.extraparams.to_ssl;
|
||||
new.authentication = ss.extraparams.authentication.clone();
|
||||
self.extraparams.store(Arc::new(new));
|
||||
self.headers.clear();
|
||||
@@ -79,8 +80,8 @@ impl BackgroundService for LB {
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("Upstreams list is changed, updating to:");
|
||||
print_upstreams(&self.ump_full);
|
||||
// info!("Upstreams list is changed, updating to:");
|
||||
// print_upstreams(&self.ump_full);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use crate::utils::structs::InnerMap;
|
||||
use crate::web::proxyhttp::LB;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
#[async_trait]
|
||||
pub trait GetHost {
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<(String, u16, bool, bool)>;
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<InnerMap>;
|
||||
fn get_header(&self, peer: &str, path: &str) -> Option<Vec<(String, String)>>;
|
||||
}
|
||||
#[async_trait]
|
||||
impl GetHost for LB {
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<(String, u16, bool, bool)> {
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<InnerMap> {
|
||||
if let Some(b) = backend_id {
|
||||
if let Some(bb) = self.ump_byid.get(b) {
|
||||
// println!("BIB :===> {:?}", Some(bb.value()));
|
||||
@@ -19,7 +20,7 @@ impl GetHost for LB {
|
||||
|
||||
let host_entry = self.ump_upst.get(peer)?;
|
||||
let mut current_path = path.to_string();
|
||||
let mut best_match: Option<(String, u16, bool, bool)> = None;
|
||||
let mut best_match: Option<InnerMap> = None;
|
||||
loop {
|
||||
if let Some(entry) = host_entry.get(¤t_path) {
|
||||
let (servers, index) = entry.value();
|
||||
|
||||
@@ -4,11 +4,10 @@ use crate::web::gethosts::GetHost;
|
||||
use arc_swap::ArcSwap;
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, warn};
|
||||
use pingora::http::RequestHeader;
|
||||
use pingora::http::{RequestHeader, ResponseHeader, StatusCode};
|
||||
use pingora::prelude::*;
|
||||
use pingora_core::listeners::ALPN;
|
||||
use pingora_core::prelude::HttpPeer;
|
||||
use pingora_http::ResponseHeader;
|
||||
use pingora_proxy::{ProxyHttp, Session};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -23,6 +22,8 @@ pub struct LB {
|
||||
|
||||
pub struct Context {
|
||||
backend_id: String,
|
||||
to_https: bool,
|
||||
redirect_to: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -31,7 +32,11 @@ impl ProxyHttp for LB {
|
||||
// fn new_ctx(&self) -> Self::CTX {}
|
||||
type CTX = Context;
|
||||
fn new_ctx(&self) -> Self::CTX {
|
||||
Context { backend_id: String::new() }
|
||||
Context {
|
||||
backend_id: String::new(),
|
||||
to_https: false,
|
||||
redirect_to: String::new(),
|
||||
}
|
||||
}
|
||||
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
|
||||
if let Some(auth) = self.extraparams.load().authentication.get("authorization") {
|
||||
@@ -42,21 +47,17 @@ impl ProxyHttp for LB {
|
||||
return Ok(true);
|
||||
}
|
||||
};
|
||||
// if session.req_header().uri.path().starts_with("/denied") {
|
||||
// let _ = session.respond_error(403).await;
|
||||
// warn!("Forbidden: {:?}, {}", session.client_addr(), session.req_header().uri.path().to_string());
|
||||
// return Ok(true);
|
||||
// };
|
||||
Ok(false)
|
||||
}
|
||||
async fn upstream_peer(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<Box<HttpPeer>> {
|
||||
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 self.extraparams.load().sticky_sessions {
|
||||
if let Some(cookies) = session.req_header().headers.get("cookie") {
|
||||
if let Ok(cookie_str) = cookies.to_str() {
|
||||
for cookie in cookie_str.split(';') {
|
||||
@@ -73,7 +74,7 @@ impl ProxyHttp for LB {
|
||||
let ddr = self.get_host(hostname, hostname, backend_id);
|
||||
|
||||
match ddr {
|
||||
Some((address, port, ssl, is_h2)) => {
|
||||
Some((address, port, ssl, is_h2, to_https)) => {
|
||||
let mut peer = Box::new(HttpPeer::new((address.clone(), port.clone()), ssl, String::new()));
|
||||
// if session.is_http2() {
|
||||
if is_h2 {
|
||||
@@ -84,14 +85,23 @@ impl ProxyHttp for LB {
|
||||
peer.options.verify_cert = false;
|
||||
peer.options.verify_hostname = false;
|
||||
}
|
||||
// info!(
|
||||
// "upstream peer: hostname {}, address{}, alpn {}, h2 {:?}",
|
||||
// hostname,
|
||||
// address.as_str(),
|
||||
// peer.options.alpn,
|
||||
// is_h2
|
||||
// );
|
||||
_ctx.backend_id = format!("{}:{}:{}", address.clone(), port.clone(), ssl);
|
||||
// println!("{}, {}, alpn {}, h2 {:?}, to_https {}", hostname, address.as_str(), peer.options.alpn, is_h2, _to_https);
|
||||
if self.extraparams.load().to_ssl.unwrap_or(false) || to_https {
|
||||
if let Some(stream) = session.stream() {
|
||||
if stream.get_ssl().is_none() {
|
||||
if let Some(addr) = session.server_addr() {
|
||||
if let Some((host, _)) = addr.to_string().split_once(':') {
|
||||
let uri = session.req_header().uri.path_and_query().map_or("/", |pq| pq.as_str());
|
||||
let port = self.config.proxy_port_tls.unwrap_or(443);
|
||||
ctx.to_https = true;
|
||||
ctx.redirect_to = format!("https://{}:{}{}", host, port, uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx.backend_id = format!("{}:{}:{}", address.clone(), port.clone(), ssl);
|
||||
Ok(peer)
|
||||
}
|
||||
None => {
|
||||
@@ -107,9 +117,8 @@ impl ProxyHttp for LB {
|
||||
}
|
||||
}
|
||||
|
||||
async fn upstream_request_filter(&self, _session: &mut Session, _upstream_request: &mut RequestHeader, _ctx: &mut Self::CTX) -> Result<()> {
|
||||
let clientip = _session.client_addr();
|
||||
match clientip {
|
||||
async fn upstream_request_filter(&self, session: &mut Session, _upstream_request: &mut RequestHeader, _ctx: &mut Self::CTX) -> Result<()> {
|
||||
match session.client_addr() {
|
||||
Some(ip) => {
|
||||
let inet = ip.as_inet();
|
||||
match inet {
|
||||
@@ -128,20 +137,30 @@ impl ProxyHttp for LB {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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();
|
||||
if self.extraparams.load().stickysessions {
|
||||
let backend_id = _ctx.backend_id.clone();
|
||||
if self.extraparams.load().sticky_sessions {
|
||||
let backend_id = ctx.backend_id.clone();
|
||||
if let Some(bid) = self.ump_byid.get(&backend_id) {
|
||||
// let _ = _upstream_response.insert_header("set-cookie", format!("backend {}", bid.0));
|
||||
let _ = _upstream_response.insert_header("set-cookie", format!("backend_id={}; Path=/; Max-Age=600; HttpOnly; SameSite=Lax", bid.0));
|
||||
}
|
||||
}
|
||||
|
||||
let host_name = return_header_host(&_session);
|
||||
match host_name {
|
||||
if ctx.to_https {
|
||||
// println!("{} => {}", ctx.to_https, ctx.redirect_to);
|
||||
let mut redirect_response = ResponseHeader::build(StatusCode::MOVED_PERMANENTLY, None)?;
|
||||
redirect_response.insert_header("Location", ctx.redirect_to.clone())?;
|
||||
redirect_response.insert_header("Content-Length", "0")?;
|
||||
session.write_response_header(Box::new(redirect_response), false).await?;
|
||||
// return Ok(());
|
||||
// let response = session.write_response_header(Box::new(redirect_response), false).await?;
|
||||
// return Ok(response);
|
||||
}
|
||||
|
||||
match return_header_host(&session) {
|
||||
Some(host) => {
|
||||
let path = _session.req_header().uri.path();
|
||||
let path = session.req_header().uri.path();
|
||||
let host_header = host;
|
||||
let split_header = host_header.split_once(':');
|
||||
match split_header {
|
||||
|
||||
@@ -23,7 +23,8 @@ pub fn run() {
|
||||
let im_config = Arc::new(DashMap::new());
|
||||
let hh_config = Arc::new(DashMap::new());
|
||||
let ec_config = Arc::new(ArcSwap::from_pointee(Extraparams {
|
||||
stickysessions: false,
|
||||
sticky_sessions: false,
|
||||
to_ssl: None,
|
||||
authentication: DashMap::new(),
|
||||
}));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user