mirror of
https://github.com/sadoyan/aralez.git
synced 2026-10-23 06:01:35 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
430f867792 | ||
|
|
f6c092adc4 | ||
|
|
19ad8fdbf4 | ||
|
|
b55ff2d392 | ||
|
|
b73ccc527f | ||
|
|
c89fe48e44 | ||
|
|
d21fd8cb4b | ||
|
|
491442bb92 | ||
|
|
e07791e1f0 | ||
|
|
7b952b467c | ||
|
|
9a1e8fe149 | ||
|
|
874ce4fddb | ||
|
|
99c7a811da | ||
|
|
edadda803c | ||
|
|
c5d0fe60a0 | ||
|
|
d7fe476b24 | ||
|
|
aa22749393 | ||
|
|
4b6a558b4b | ||
|
|
6c9c7acf65 | ||
|
|
2845dc5923 | ||
|
|
f2e07a8d70 | ||
|
|
5815da6576 | ||
|
|
1ab0916026 | ||
|
|
707f725b88 | ||
|
|
eb4e73ece0 | ||
|
|
53e7dcfd33 | ||
|
|
f3b346a28d | ||
|
|
c011800e1e | ||
|
|
265ff6b774 | ||
|
|
1c3d9a263f | ||
|
|
162c5060c9 | ||
|
|
132cf45dfe | ||
|
|
77dcafbb4e | ||
|
|
649bd979f7 | ||
|
|
bd315106b9 | ||
|
|
3ba2ed33ae | ||
|
|
c09efab9fd | ||
|
|
735d605f6d | ||
|
|
6773d0f502 | ||
|
|
a8cb727da5 | ||
|
|
f81194aee7 | ||
|
|
0f09a2e02b |
+4
-3
@@ -5,13 +5,13 @@
|
||||
*.dll
|
||||
*.exe
|
||||
*.sh
|
||||
/docs/
|
||||
*.yaml
|
||||
/docs
|
||||
/etc
|
||||
assets/
|
||||
assets
|
||||
/target/
|
||||
*.iml
|
||||
.idea/
|
||||
.etc/
|
||||
*.ipr
|
||||
*.iws
|
||||
/out/
|
||||
@@ -22,4 +22,5 @@ crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
/target
|
||||
/z_shpo
|
||||
/configs
|
||||
Makefile
|
||||
|
||||
Generated
+369
-606
File diff suppressed because it is too large
Load Diff
+20
-14
@@ -1,7 +1,11 @@
|
||||
[package]
|
||||
name = "aralez"
|
||||
version = "0.9.2"
|
||||
version = "0.92.15"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Reverse proxy built on top of Cloudflare's Pingora"
|
||||
exclude = ["configs/*"]
|
||||
repository = "https://github.com/sadoyan/aralez"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
@@ -12,32 +16,32 @@ strip = true
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.52.3", features = ["full"] }
|
||||
pingora = { version = "0.8.0", features = ["lb", "openssl"] } # openssl, rustls, boringssl
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
pingora = { version = "0.8.1", features = ["lb", "openssl"] } # openssl, rustls, boringssl
|
||||
pingora-core = "0.8.1"
|
||||
pingora-proxy = "0.8.1"
|
||||
pingora-http = "0.8.1"
|
||||
pingora-limits = "0.8.1"
|
||||
pingora-cache = "0.8.1"
|
||||
dashmap = "7.0.0-rc2"
|
||||
pingora-core = "0.8.0"
|
||||
pingora-proxy = "0.8.0"
|
||||
pingora-http = "0.8.0"
|
||||
pingora-limits = "0.8.0"
|
||||
async-trait = "0.1.89"
|
||||
log = "0.4.30"
|
||||
futures = "0.3.32"
|
||||
log = "0.4.33"
|
||||
notify = "9.0.0-rc.4"
|
||||
axum = { version = "0.8.9" }
|
||||
reqwest = { version = "0.13.4", features = ["json", "stream", "blocking"] }
|
||||
serde_yml = "0.0.12"
|
||||
rand = "0.10.1"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
noyalib = { version = "0.0.15", features = ["compat-serde-yaml"] }
|
||||
rand = "0.10.2"
|
||||
base64 = "0.22.1"
|
||||
jsonwebtoken = { version = "10.4.0", default-features = false, features = ["use_pem", "rust_crypto"] }
|
||||
tonic = "0.14.6"
|
||||
sha2 = { version = "0.11.0-rc.5", default-features = false }
|
||||
base16ct = { version = "1.0.0", features = ["alloc"] }
|
||||
urlencoding = "2.1.3"
|
||||
arc-swap = "1.9.1"
|
||||
arc-swap = "1.9.2"
|
||||
prometheus = "0.14.0"
|
||||
x509-parser = "0.18.1"
|
||||
rustls-pemfile = "2.2.0"
|
||||
tower-http = { version = "0.6.11", features = ["fs"] }
|
||||
tower-http = { version = "0.7.0", features = ["fs"] }
|
||||
privdrop = "0.5.6"
|
||||
serde_json = "1.0.150"
|
||||
subtle = "2.6.1"
|
||||
@@ -45,7 +49,9 @@ moka = { version = "0.12.15", features = ["sync"] }
|
||||
ahash = "0.8.12"
|
||||
instant-acme = "0.8.5"
|
||||
rcgen = "0.14.8"
|
||||
log4rs = "1.4.0"
|
||||
log4rs = { version = "1.4.0", features = ["rolling_file_appender", "compound_policy", "size_trigger", "fixed_window_roller", "gzip"] }
|
||||
mimalloc = { version = "0.1.52", default-features = false }
|
||||
signal-hook = "0.4.4"
|
||||
sd-notify = "0.5.0"
|
||||
libc = "0.2.186"
|
||||
|
||||
|
||||
@@ -9,13 +9,23 @@
|
||||
Aralez is a high-performance Rust reverse proxy with zero-configuration automatic protocol handling, TLS, and upstream management,
|
||||
featuring Consul and Kubernetes integration for dynamic pod discovery and health-checked routing, acting as a lightweight ingress-style proxy.
|
||||
|
||||
|
||||
---
|
||||
What Aralez means ?
|
||||
**Aralez = Արալեզ** <ins>Named after the legendary Armenian guardian spirit, winged dog-like creature, that descend upon fallen heroes to lick their wounds and resurrect them</ins>.
|
||||
|
||||
Built on Rust, on top of **Cloudflare’s Pingora engine**, **Aralez** delivers world-class performance, security and scalability — right out of the box.
|
||||
|
||||
[](https://www.buymeacoffee.com/sadoyan)
|
||||
---
|
||||
|
||||
## Links
|
||||
|
||||
- [**Documentation**](https://aralez.rs) : The manual you should read
|
||||
- [**Downloads**](https://github.com/sadoyan/aralez/releases) : Binary downloads
|
||||
- [**Issues**](https://github.com/sadoyan/aralez/issues) : Issues and requests
|
||||
- [**Crates**](https://crates.io/crates/aralez) : The Rust crate registry
|
||||
- [**DockerHUB**](https://hub.docker.com/r/sadoyan/aralez) : DockerHUB official repository
|
||||
- [**GitHUB Packages**](https://github.com/sadoyan/aralez/pkgs/container/aralez) : GitHUB ghcr.io images
|
||||
|
||||
---
|
||||
|
||||
@@ -50,27 +60,30 @@ Built on Rust, on top of **Cloudflare’s Pingora engine**, **Aralez** delivers
|
||||
|
||||
### `main.yaml`
|
||||
|
||||
| Key | Example Value | Description |
|
||||
|----------------------------------|----------------------------|-------------------------------------------------------------------------------------------------|
|
||||
| **threads** | 12 | Number of running daemon threads. Optional, defaults to 1 |
|
||||
| **runuser** | aralez | Optional. Username for running aralez after dropping root privileges (requires launch as root) |
|
||||
| **rungroup** | aralez | Optional. Group for running aralez after dropping root privileges (requires launch as root) |
|
||||
| **daemon** | false | Run in background (boolean) |
|
||||
| **upstream_keepalive_pool_size** | 500 | Pool size for upstream keepalive connections |
|
||||
| **pid_file** | /tmp/aralez.pid | Path to PID file |
|
||||
| **config_address** | 0.0.0.0:3000 | HTTP API address for pushing upstreams.yaml from remote location |
|
||||
| **proxy_tls_grade** | high, medium, unsafe | Grade of TLS ciphers. `high` matches Qualys SSL Labs A+ (defaults to `medium`) |
|
||||
| **proxy_address_http** | 0.0.0.0:6193 | Aralez HTTP bind address |
|
||||
| **proxy_address_tls** | 0.0.0.0:6194 | Aralez HTTPS bind address (Optional) |
|
||||
| **proxy_configs** | /etc/aralez/ | Direcotry containing configuration files, must be writeable by user `aralez` |
|
||||
| **upstreams_conf** | /etc/aralez/upstreams.yaml | Location of the upstreams file |
|
||||
| **log_level** | info | Log level: `info`, `warn`, `error`, `debug`, `trace`, `off` |
|
||||
| **log_file** | /full/path/to/aralez.log | Optional, the location of log file. If thi entry does not exist logs will be emitted to stdout. |
|
||||
| **hc_method** | HEAD | Healthcheck method: HEAD, GET, POST (UPPERCASE) |
|
||||
| **hc_interval** | 2 | Interval for health checks in seconds |
|
||||
| **file_server_folder** | /some/local/folder | Optional. Local folder to serve |
|
||||
| **file_server_address** | 127.0.0.1:3002 | Optional. Local address for file server |
|
||||
| **config_api_enabled** | true | Enable/disable remote config push capability |
|
||||
| Key | Example Value | Description |
|
||||
|----------------------------------|----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| **threads** | 12 | Number of running daemon threads. Optional, defaults to 1 |
|
||||
| **runuser** | aralez | Optional. Username for running aralez after dropping root privileges (requires launch as root) |
|
||||
| **rungroup** | aralez | Optional. Group for running aralez after dropping root privileges (requires launch as root) |
|
||||
| **daemon** | false | Run in background (boolean) |
|
||||
| **upstream_keepalive_pool_size** | 500 | Pool size for upstream keepalive connections |
|
||||
| **pid_file** | /tmp/aralez.pid | Path to PID file |
|
||||
| **config_address** | 0.0.0.0:3000 | HTTP API address for pushing upstreams.yaml from remote location |
|
||||
| **proxy_tls_grade** | high, medium, unsafe | Grade of TLS ciphers. `high` matches Qualys SSL Labs A+ (defaults to `medium`) |
|
||||
| **proxy_address_http** | 0.0.0.0:6193 | Aralez HTTP bind address |
|
||||
| **proxy_address_tls** | 0.0.0.0:6194 | Aralez HTTPS bind address (Optional) |
|
||||
| **proxy_configs** | /etc/aralez/ | Direcotry containing configuration files, must be writeable by user `aralez` |
|
||||
| **upstreams_conf** | /etc/aralez/upstreams.yaml | Location of the upstreams file |
|
||||
| **access_log** | access | Configure access logging. Values: `access, error` |
|
||||
| **log_level** | info | Log level: `info`, `warn`, `error`, `debug`, `trace`, `off` |
|
||||
| **log_file** | /tmp/aralez.log, 20, 5, compress | Optional, the location of log file, file size in megabytes, number of log files to keep, compress files .valueas are separated by comma. Defaults to None, 100, 5, No |
|
||||
| **hc_method** | HEAD | Healthcheck method: HEAD, GET, POST (UPPERCASE) |
|
||||
| **hc_interval** | 2 | Interval for health checks in seconds |
|
||||
| **file_server_folder** | /some/local/folder | Optional. Local folder to serve |
|
||||
| **file_server_address** | 127.0.0.1:3002 | Optional. Local address for file server |
|
||||
| **config_api_enabled** | true | Enable/disable remote config push capability |
|
||||
| **cache_size_mb** | 50 | Optional. Enable internal cache with size in megabytes of value. Cache is entirely disabled when this line is commented out. |
|
||||
| **cache_ttl** | 10 | Optional. Set Default TTL in seconds for cached items, works if cache control headers are not set via upstream. Defaults to 60 if cache_size_mb is set. |
|
||||
|
||||
---
|
||||
|
||||
@@ -107,6 +120,9 @@ For getting the best performance on newer hardware use `aralez-x86_64-*.gz`.
|
||||
|
||||
```shell
|
||||
docker run -d -v /path/to/config:/etc/aralez:rw -p 80:80 -p 443:443 sadoyan/aralez
|
||||
docker run -d -v /path/to/config:/etc/aralez:rw -p 80:80 -p 443:443 sadoyan/aralez:compat
|
||||
docker run -d -v /path/to/config:/etc/aralez:rw -p 80:80 -p 443:443 ghcr.io/sadoyan/aralez:latest
|
||||
docker run -d -v /path/to/config:/etc/aralez:rw -p 80:80 -p 443:443 ghcr.io/sadoyan/aralez:compat
|
||||
```
|
||||
|
||||
**Dockerfile :**
|
||||
@@ -554,10 +570,3 @@ The results show requests per second performed by Load balancer. You can see 3 b
|
||||
1. Requests via http1.1 to plain text endpoint.
|
||||
2. Requests to via http2 to SSL endpoint.
|
||||
3. Mixed workload with plain http1.1 and htt2 SSL.
|
||||
|
||||
## Links
|
||||
|
||||
- [**Documentation**](https://aralez.rs) : The manual you should read
|
||||
- [**Downloads**](https://github.com/sadoyan/aralez/releases) : Binary downloads
|
||||
- [**Issues**](https://github.com/sadoyan/aralez/issues) : Issues and requests
|
||||
|
||||
|
||||
+17
-13
@@ -1,23 +1,27 @@
|
||||
# Main configuration file, applied on startup
|
||||
threads: 12 # Number of daemon threads default setting
|
||||
#runuser: pastor # Username for running aralez after dropping root privileges, requires program to start as root
|
||||
#rungroup: pastor # Group for running aralez after dropping root privileges, requires program to start as root
|
||||
daemon: false # Run in background
|
||||
runuser: aralez # Username for running aralez after dropping root privileges, requires program to start as root
|
||||
rungroup: aralez # Group for running aralez after dropping root privileges, requires program to start as root
|
||||
upstream_keepalive_pool_size: 500 # Pool size for upstream keepalive connections
|
||||
pid_file: /tmp/aralez.pid # Path to PID file
|
||||
error_log: /tmp/aralez_err.log # Path to error log
|
||||
upgrade_sock: /tmp/aralez.sock # Path to socket file
|
||||
config_api_enabled: true # Boolean to enable/disable remote config push capability.
|
||||
config_address: 0.0.0.0:3000 # HTTP API address for pushing upstreams.yaml from remote location
|
||||
proxy_address_http: 0.0.0.0:6193 # Proxy HTTP bind address
|
||||
proxy_address_tls: 0.0.0.0:6194 # Optional, Proxy TLS bind address
|
||||
proxy_configs: /opt/Rust/Projects/asyncweb/etc # Mandatory if proxy_address_tls set, should contain a certificate and key files strictly in a format {NAME}.crt, {NAME}.key.
|
||||
config_address: 127.0.0.1:3000 # HTTP API address for pushing upstreams.yaml from remote location
|
||||
proxy_address_http: 0.0.0.0:80 # Proxy HTTP bind address
|
||||
proxy_address_tls: 0.0.0.0:443 # Optional, Proxy TLS bind address
|
||||
proxy_configs: /opt/aralez/asyncweb/etc # Mandatory if proxy_address_tls set, should contain a certificate and key files strictly in a format {NAME}.crt, {NAME}.key.
|
||||
proxy_tls_grade: high # Grade of TLS suite for proxy (high, medium, unsafe), matching grades of Qualys SSL Labs
|
||||
upstreams_conf: /opt/Rust/Projects/asyncweb/etc/upstreams.yaml # the location of upstreams file
|
||||
#file_server_folder: /opt/storage # Optional, local folder to serve
|
||||
#file_server_address: 127.0.0.1:3002 # Optional, Local address for file server. Can set as upstream for public access.
|
||||
upstreams_conf: /opt/aralez/etc/upstreams.yaml # the location of upstreams file
|
||||
file_server_folder: /opt/aralez/public # Optional, local folder to serve
|
||||
file_server_address: 0.0.0.0:3002 # Optional, Local address for file server. Can set as upstream for public access.
|
||||
log_level: info # info, warn, error, debug, trace, off
|
||||
log_file: /tmp/aralez.log # Optional, the location of log file. If this entry does not exist logs will be emitted to stdout.
|
||||
log_file: /tmp/aralez.log, 20, 5, compress # Optional, the location of log file, file size in megabytes, number of log files to keep, compress files .valueas are separated by comma.
|
||||
access_log: error # all, error, (Off if commented)
|
||||
hc_method: HEAD # Healthcheck method (HEAD, GET, POST are supported) UPPERCASE
|
||||
hc_interval: 2 #Interval for health checks in seconds
|
||||
#master_key: 910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774 # Mater key for working with API server and JWT Secret
|
||||
tcp_keepalive_idle: 60 # Seconds of inactivity before the kernel starts sending keepalive probes to a downstream client
|
||||
tcp_keepalive_interval: 10 # Seconds between individual keepalive probes if the client does not respond
|
||||
tcp_keepalive_count: 5 # Number of unanswered probes before the kernel declares the connection dead and closes it
|
||||
cache_size_mb: 50 # Optional. Enable internal cache with size in megabytes of value. Cache is entirely disabled when this line is commented out
|
||||
cache_ttl: 120 # Optional. Set Default TTL in seconds for cached items, works if cache control headers are not set via upstream. Defaults to 60 if cache_size_mb is set
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
provider: "file"
|
||||
globals:
|
||||
headers:
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
- "X-Custom-Header:Something Special"
|
||||
upstreams:
|
||||
myip.netangels.net:
|
||||
paths:
|
||||
"/":
|
||||
ssl: false
|
||||
headers:
|
||||
- "X-Proxy-From:Aralez"
|
||||
servers:
|
||||
- "192.168.221.213:8000"
|
||||
- "192.168.221.214:8000"
|
||||
- "192.168.221.210:8000"
|
||||
- "192.168.221.212:8000"
|
||||
+83
-67
@@ -1,49 +1,44 @@
|
||||
# The file under watch and hot reload, changes are applied immediately, no need to restart or reload.
|
||||
provider: "file" # "file" "consul" "kubernetes"
|
||||
sticky_sessions: 8600
|
||||
sticky_sessions: 172000
|
||||
to_https: false
|
||||
rate_limit: 300
|
||||
x4xx_limit: 200
|
||||
rate_limit: 500000
|
||||
x4xx_limit: 100000
|
||||
server_headers:
|
||||
- "X-Forwarded-Proto:https"
|
||||
- "X-Forwarded-Port:443"
|
||||
- "Y-Global-Something: Something For Servers"
|
||||
client_headers:
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
- "X-Global-Something: Something For Clients"
|
||||
#authorization:
|
||||
# type: "jwt"
|
||||
# creds: "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||
# type: "basic"
|
||||
# creds: "username:Pa$$w0rd"
|
||||
# type: "apikey"
|
||||
# creds: "5ecbf799-1343-4e94-a9b5-e278af5cd313-56b45249-1839-4008-a450-a60dc76d2bae"
|
||||
# data: "root:toor"
|
||||
# type: "jwt"
|
||||
# data: "910517d9-f9a1-48de-8826-dbadacbd84af-cb6f830e-ab16-47ec-9d8f-0090de732774"
|
||||
# type: "apikey"
|
||||
# data: "5ecbf799-1343-4e94-a9b5-e278af5cd313-56b45249-1839-4008-a450-a60dc76d2bae"
|
||||
consul:
|
||||
servers:
|
||||
- "http://192.168.1.199:8500"
|
||||
- "http://192.168.1.200:8500"
|
||||
- "http://192.168.1.201:8500"
|
||||
- "http://consul1:8500"
|
||||
services: # hostname: The hostname to access the proxy server, upstream : The real service name in Consul database.
|
||||
- hostname: "webapi-service"
|
||||
upstream: "webapi-service-health"
|
||||
- hostname: "nconsul"
|
||||
upstream: "nginx-consul-NginX-health"
|
||||
path: "/one"
|
||||
client_headers:
|
||||
- "X-Some-Thing:Yaaaaaaaaaaaaaaa"
|
||||
- "X-Proxy-From:Aralez"
|
||||
rate_limit: 1
|
||||
to_https: false
|
||||
- hostname: "webapi-service"
|
||||
upstream: "webapi-service-health"
|
||||
- hostname: "nconsul"
|
||||
upstream: "nginx-consul-NginX-health"
|
||||
path: "/"
|
||||
token: "8e2db809-845b-45e1-8b47-2c8356a09da0-a4370955-18c2-4d6e-a8f8-ffcc0b47be81" # Consul server access token, If Consul auth is enabled
|
||||
kubernetes:
|
||||
servers:
|
||||
- "192.168.1.55:443" #For testing only, overrides with KUBERNETES_SERVICE_HOST : KUBERNETES_SERVICE_PORT_HTTPS env variables.
|
||||
- "172.16.0.11:5443" # Gets KUBERNETES_SERVICE_HOST : KUBERNETES_SERVICE_PORT_HTTPS env variables.
|
||||
services:
|
||||
- hostname: "webapi-service"
|
||||
- hostname: "api-service"
|
||||
upstream: "api-service"
|
||||
path: "/"
|
||||
upstream: "webapi-service"
|
||||
- hostname: "webapi-service"
|
||||
- hostname: "api-service"
|
||||
upstream: "console-service"
|
||||
path: "/one"
|
||||
client_headers:
|
||||
@@ -51,71 +46,92 @@ kubernetes:
|
||||
- "X-Proxy-From:Aralez"
|
||||
rate_limit: 100
|
||||
to_https: false
|
||||
- hostname: "webapi-service"
|
||||
upstream: "rambul-service"
|
||||
- hostname: "api-service"
|
||||
upstream: "feed-fanout-service"
|
||||
path: "/two"
|
||||
- hostname: "websocket-service"
|
||||
upstream: "websocket-service"
|
||||
path: "/"
|
||||
tokenpath: "/path/to/kubetoken.txt" #If not set, will default to /var/run/secrets/kubernetes.io/serviceaccount/token
|
||||
tokenpath: "/opt/Rust/Projects/asyncweb/etc/kubetoken.txt" # Defaults to /var/run/secrets/kubernetes.io/serviceaccount/token
|
||||
upstreams:
|
||||
myip.mydomain.com:
|
||||
www.example.com:
|
||||
paths:
|
||||
"/":
|
||||
rate_limit: 200
|
||||
rate_limit: 50
|
||||
x4xx_limit: 100
|
||||
to_https: false
|
||||
client_headers:
|
||||
- "X-Proxy-From:Aralez"
|
||||
servers:
|
||||
- "127.0.0.1:8000"
|
||||
- "127.0.0.2:8000"
|
||||
- "127.0.0.3:8000"
|
||||
- "127.0.0.4:8000"
|
||||
- "127.0.0.5:8000"
|
||||
"/ping":
|
||||
authorization: # Will be ignored if global authentication is enabled.
|
||||
authorization:
|
||||
type: "basic"
|
||||
creds: "admin:admin"
|
||||
to_https: false
|
||||
data: "root:toor"
|
||||
server_headers:
|
||||
- "X-Forwarded-Proto:https"
|
||||
- "X-Forwarded-Port:443"
|
||||
- "Y-Proxy-Server-Some:Yaaaaaaaaaaaaaaa"
|
||||
- "Y-Proxy-Server-From:Aralez"
|
||||
- "Y-Proxy-Server-Vers:Aralez v-xxx"
|
||||
client_headers:
|
||||
- "X-Some-Thing:Yaaaaaaaaaaaaaaa"
|
||||
- "X-Proxy-From:Aralez"
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
- "Strict-Transport-Security:max-age=31536000; includeSubDomains; preload"
|
||||
servers:
|
||||
- "127.0.0.1:8000"
|
||||
- "127.0.0.2:8000"
|
||||
"/draw":
|
||||
servers:
|
||||
- "192.168.1.1:8000"
|
||||
polo.mydomain.com:
|
||||
paths:
|
||||
"/":
|
||||
to_https: false
|
||||
client_headers:
|
||||
- "X-Some-Thing:Yaaaaaaaaaaaaaaa"
|
||||
servers:
|
||||
- "192.168.1.1:8000"
|
||||
- "192.168.1.10:8000"
|
||||
- "127.0.0.1:8000"
|
||||
- "127.0.0.2:8000"
|
||||
- "127.0.0.3:8000"
|
||||
- "127.0.0.4:8000"
|
||||
apt.mydomain.com:
|
||||
"/ping":
|
||||
to_https: true
|
||||
client_headers:
|
||||
- "X-Some-Thing:Something Else"
|
||||
- "Access-Control-Allow-Origin:*"
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
- "Access-Control-Max-Age:86400"
|
||||
- "Strict-Transport-Security:max-age=31536000; includeSubDomains; preload"
|
||||
servers:
|
||||
- "127.0.0.1:8000"
|
||||
"/secret":
|
||||
authorization:
|
||||
type: "forward"
|
||||
data: "http://127.0.0.1:8899/admin/login"
|
||||
servers:
|
||||
- "127.0.0.10:8000"
|
||||
example.com:
|
||||
paths:
|
||||
"/":
|
||||
redirect_to: "https://www.example.com:443"
|
||||
servers:
|
||||
- "192.168.1.10:443"
|
||||
- "127.0.0.1:80"
|
||||
h2.example.com:
|
||||
paths:
|
||||
"/":
|
||||
server_headers:
|
||||
- "Y-Global-Something: Yes this is something"
|
||||
client_headers:
|
||||
- "Access-Control-Allow-Methods:POST, GET, OPTIONS"
|
||||
rate_limit: 60
|
||||
x4xx_limit: 30
|
||||
authorization:
|
||||
type: "jwt"
|
||||
servers:
|
||||
- "127.0.0.1:8000"
|
||||
- "127.0.0.2:8000"
|
||||
"/.well-known/acme-challenge":
|
||||
healthcheck: false
|
||||
servers:
|
||||
- "127.0.0.1:8001"
|
||||
rdr.mydomain.com:
|
||||
paths:
|
||||
"/":
|
||||
redirect_to: "https://som.other.domain:6194"
|
||||
"/400":
|
||||
rate_limit: 4
|
||||
x4xx_limit: 2
|
||||
servers:
|
||||
- "127.0.0.1:8899"
|
||||
"/500":
|
||||
healthcheck: false
|
||||
servers:
|
||||
- "127.0.0.1:8080"
|
||||
- "127.0.0.1:8899"
|
||||
DEFAULT:
|
||||
paths:
|
||||
"/":
|
||||
healthcheck: false
|
||||
servers:
|
||||
- "127.0.0.1:3000"
|
||||
"/.well-known/acme-challenge":
|
||||
healthcheck: false
|
||||
servers:
|
||||
- "127.0.0.1:3000"
|
||||
|
||||
+5
-1
@@ -3,10 +3,14 @@ mod utils;
|
||||
mod web;
|
||||
|
||||
#[global_allocator]
|
||||
// static ALLOC: Jemalloc = Jemalloc;
|
||||
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
// pub static A: CountingAllocator = CountingAllocator;
|
||||
|
||||
fn main() {
|
||||
if std::env::args().any(|a| a == "--version" || a == "-v") {
|
||||
println!("aralez {}", env!("CARGO_PKG_VERSION"));
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
web::start::run();
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ use crate::utils::kuberconsul::{ConsulDiscovery, KubernetesDiscovery, ServiceDis
|
||||
use crate::utils::structs::{Configuration, UpstreamsDashMap};
|
||||
use crate::web::webserver;
|
||||
use async_trait::async_trait;
|
||||
use futures::channel::mpsc::Sender;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::Sender;
|
||||
|
||||
pub struct APIUpstreamProvider {
|
||||
pub config_api_enabled: bool,
|
||||
@@ -46,7 +46,7 @@ impl Discovery for APIUpstreamProvider {
|
||||
#[async_trait]
|
||||
impl Discovery for FromFileProvider {
|
||||
async fn start(&self, tx: Sender<Configuration>) {
|
||||
tokio::spawn(filewatch::start(self.path.clone(), tx.clone()));
|
||||
tokio::spawn(filewatch::start(self.path.clone(), tx));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
use crate::utils::parceyaml::load_configuration;
|
||||
use crate::utils::structs::Configuration;
|
||||
use futures::channel::mpsc::Sender;
|
||||
use futures::SinkExt;
|
||||
use log::error;
|
||||
use notify::event::ModifyKind;
|
||||
use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use pingora::prelude::sleep;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc::Sender;
|
||||
use tokio::task;
|
||||
|
||||
pub async fn start(fp: String, mut toreturn: Sender<Configuration>) {
|
||||
pub async fn start(fp: String, toreturn: Sender<Configuration>) {
|
||||
sleep(Duration::from_millis(50)).await; // For having nice logs :-)
|
||||
let file_path = fp.as_str();
|
||||
let parent_dir = Path::new(file_path).parent().unwrap();
|
||||
|
||||
@@ -4,8 +4,6 @@ use crate::utils::structs::{Configuration, GlobalServiceMapping, InnerMap, Upstr
|
||||
use crate::utils::tools::{clone_dashmap_into, compare_dashmaps, print_upstreams};
|
||||
use async_trait::async_trait;
|
||||
use dashmap::DashMap;
|
||||
use futures::channel::mpsc::Sender;
|
||||
use futures::SinkExt;
|
||||
use pingora::prelude::sleep;
|
||||
use rand::RngExt;
|
||||
use serde::Deserialize;
|
||||
@@ -18,6 +16,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::sync::mpsc::Sender;
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct KubeEndpoints {
|
||||
@@ -95,7 +94,7 @@ pub struct ConsulDiscovery;
|
||||
|
||||
#[async_trait]
|
||||
impl ServiceDiscovery for KubernetesDiscovery {
|
||||
async fn fetch_upstreams(&self, config: Arc<Configuration>, mut toreturn: Sender<Configuration>) {
|
||||
async fn fetch_upstreams(&self, config: Arc<Configuration>, toreturn: Sender<Configuration>) {
|
||||
let prev_upstreams = UpstreamsDashMap::new();
|
||||
|
||||
if let Some(kuber) = config.kubernetes.clone() {
|
||||
@@ -162,7 +161,7 @@ fn get_current_namespace() -> Option<String> {
|
||||
|
||||
#[async_trait]
|
||||
impl ServiceDiscovery for ConsulDiscovery {
|
||||
async fn fetch_upstreams(&self, config: Arc<Configuration>, mut toreturn: Sender<Configuration>) {
|
||||
async fn fetch_upstreams(&self, config: Arc<Configuration>, toreturn: Sender<Configuration>) {
|
||||
let prev_upstreams = UpstreamsDashMap::new();
|
||||
loop {
|
||||
let upstreams = UpstreamsDashMap::new();
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use dashmap::DashMap;
|
||||
use moka::sync::Cache;
|
||||
use pingora_cache::eviction::simple_lru::Manager;
|
||||
use pingora_cache::lock::CacheLock;
|
||||
use pingora_cache::MemCache;
|
||||
use pingora_limits::rate::Rate;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -9,3 +13,7 @@ pub static REVERSE_STORE: LazyLock<DashMap<String, String>> = LazyLock::new(Dash
|
||||
pub static RATE_LIMITER: LazyLock<Rate> = LazyLock::new(|| Rate::new(Duration::from_secs(1)));
|
||||
pub static REQUESTS_4XX: LazyLock<Cache<IpAddr, u32>> = LazyLock::new(|| Cache::builder().time_to_live(Duration::from_secs(1)).build());
|
||||
pub static LOCALHOST: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("localhost"));
|
||||
pub static MEM_CACHE: LazyLock<MemCache> = LazyLock::new(MemCache::new);
|
||||
pub static CACHE_LOCK: LazyLock<CacheLock> = LazyLock::new(|| CacheLock::new(Duration::from_secs(30)));
|
||||
pub static EVICTION: OnceLock<Manager> = OnceLock::new();
|
||||
pub static CACHE_TTL: OnceLock<u64> = OnceLock::new();
|
||||
|
||||
+15
-9
@@ -1,3 +1,5 @@
|
||||
use crate::utils::lazylock::EVICTION;
|
||||
use pingora_cache::eviction::EvictionManager;
|
||||
use pingora_http::Method;
|
||||
use pingora_http::StatusCode;
|
||||
use pingora_http::Version;
|
||||
@@ -15,22 +17,19 @@ pub struct MetricTypes {
|
||||
}
|
||||
|
||||
pub static OPEN_FILES: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_open_files", "Number of open file descriptors").unwrap());
|
||||
pub static LOGGING_ERRORS: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_logging_errors", "Number of log errors").unwrap());
|
||||
pub static MEMORY_USAGE: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_memory_bytes", "Total memory allocated in bytes").unwrap());
|
||||
pub static ACTIVE_SESSIONS: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_active_sessions", "Current number of active sessions").unwrap());
|
||||
pub static REQUEST_COUNT: LazyLock<IntCounter> = LazyLock::new(|| register_int_counter!("aralez_requests_total", "Total number of requests handled by Aralez").unwrap());
|
||||
|
||||
pub static CACHE_SIZE_BYTES: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_cache_size_bytes", "Current cache size in bytes").unwrap());
|
||||
pub static CACHE_ITEMS: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_cache_items", "Current number of cached objects").unwrap());
|
||||
pub static CACHE_EVICTED_BYTES: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_cache_evicted_bytes_total", "Total bytes evicted from cache").unwrap());
|
||||
|
||||
pub static CACHE_EVICTED_ITEMS: LazyLock<IntGauge> = LazyLock::new(|| register_int_gauge!("aralez_cache_evicted_items_total", "Total cache items evicted").unwrap());
|
||||
pub static RESPONSE_CODES: LazyLock<IntCounterVec> =
|
||||
LazyLock::new(|| register_int_counter_vec!("aralez_responses_total", "Responses grouped by status code", &["status"]).unwrap());
|
||||
|
||||
// pub static RESPONSE_LATENCY: LazyLock<Histogram> = LazyLock::new(|| {
|
||||
// register_histogram!(
|
||||
// "aralez_response_latency_seconds",
|
||||
// "Response latency in seconds",
|
||||
// vec![0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0]
|
||||
// )
|
||||
// .unwrap()
|
||||
// });
|
||||
|
||||
pub static RESPONSE_LATENCY: LazyLock<Histogram> = LazyLock::new(|| {
|
||||
register_histogram!(
|
||||
"aralez_response_latency_seconds",
|
||||
@@ -63,6 +62,13 @@ pub fn calc_metrics(metric_types: &MetricTypes) {
|
||||
REQUESTS_BY_METHOD.with_label_values(&[metric_types.method.as_str()]).inc();
|
||||
REQUESTS_BY_UPSTREAM.with_label_values(&[metric_types.upstream.as_ref()]).inc();
|
||||
RESPONSE_LATENCY.observe(metric_types.latency.as_secs_f64());
|
||||
|
||||
if let Some(eviction) = EVICTION.get() {
|
||||
CACHE_SIZE_BYTES.set(eviction.total_size() as i64);
|
||||
CACHE_ITEMS.set(eviction.total_items() as i64);
|
||||
CACHE_EVICTED_BYTES.set(eviction.evicted_size() as i64);
|
||||
CACHE_EVICTED_ITEMS.set(eviction.evicted_items() as i64);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_memory_usage() -> usize {
|
||||
|
||||
+10
-52
@@ -3,14 +3,9 @@ use crate::utils::lazylock::REVERSE_STORE;
|
||||
use crate::utils::state::{is_first_run, mark_not_first_run};
|
||||
use crate::utils::structs::*;
|
||||
use crate::utils::tools::{clone_dashmap, clone_dashmap_into, print_upstreams};
|
||||
use crate::web::logging::log_builder;
|
||||
use dashmap::DashMap;
|
||||
use log::LevelFilter;
|
||||
use log::{error, info, warn};
|
||||
use log4rs::{
|
||||
append::{console::ConsoleAppender, file::FileAppender},
|
||||
config::{Appender, Config as Log4rsConfig, Root},
|
||||
encode::pattern::PatternEncoder,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
@@ -96,7 +91,7 @@ pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>,
|
||||
}
|
||||
|
||||
info!("Reading upstreams from {}", d);
|
||||
data
|
||||
data // [2606:4700:2ff9::1]:443
|
||||
}
|
||||
"content" => {
|
||||
info!("Reading upstreams from API post body");
|
||||
@@ -108,7 +103,7 @@ pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>,
|
||||
}
|
||||
};
|
||||
|
||||
let mut parsed: Config = match serde_yml::from_str(&yaml_data) {
|
||||
let mut parsed: Config = match noyalib::from_str(&yaml_data) {
|
||||
Ok(cfg) => cfg,
|
||||
Err(e) => {
|
||||
error!("Failed to parse upstreams file: {}", e);
|
||||
@@ -118,7 +113,7 @@ pub async fn load_configuration(d: &str, kind: &str) -> (Option<Configuration>,
|
||||
|
||||
if let Some(ref mut upstreams) = parsed.upstreams {
|
||||
for uconf in conf_files {
|
||||
let p: HashMap<String, HostConfig> = match serde_yml::from_str(&uconf) {
|
||||
let p: HashMap<String, HostConfig> = match noyalib::from_str(&uconf) {
|
||||
Ok(ucfg) => ucfg,
|
||||
Err(e) => {
|
||||
error!("Failed to parse upstreams file: {}", e);
|
||||
@@ -225,7 +220,8 @@ async fn populate_file_upstreams(config: &mut Configuration, parsed: &Config) {
|
||||
}
|
||||
|
||||
let redirect_link = path_config.redirect_to.as_ref().map(|www| Arc::from(www.as_str()));
|
||||
if let Some((ip, port_str)) = server.split_once(':') {
|
||||
|
||||
if let Some((ip, port_str)) = server.rsplit_once(':') {
|
||||
if let Ok(port) = port_str.parse::<u16>() {
|
||||
server_list.push(Arc::from(InnerMap {
|
||||
address: Arc::from(ip),
|
||||
@@ -264,31 +260,25 @@ 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 mut cfo: AppConfig = noyalib::from_str(&data).expect("Failed to parse main config file");
|
||||
if let Ok(jwt_key) = env::var("JWT_KEY") {
|
||||
cfo.master_key = Some(jwt_key);
|
||||
};
|
||||
|
||||
log_builder(&cfo, &cfo.log_file);
|
||||
cfo.hc_method = cfo.hc_method.to_uppercase();
|
||||
for (k, v) in cfg {
|
||||
reply.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
if let Some((ip, port_str)) = cfo.config_address.split_once(':') {
|
||||
if let Some((ip, port_str)) = cfo.config_address.rsplit_once(':') {
|
||||
if let Ok(port) = port_str.parse::<u16>() {
|
||||
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 Some((_, port_str)) = tlsport_cfg.rsplit_once(':') {
|
||||
cfo.proxy_port_tls = Some(port_str.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
if let Some((_, port_str)) = cfo.proxy_address_http.split_once(':') {
|
||||
if let Some((_, port_str)) = cfo.proxy_address_http.rsplit_once(':') {
|
||||
cfo.proxy_port = Some(port_str.to_string());
|
||||
}
|
||||
|
||||
@@ -332,35 +322,3 @@ pub fn build_headers(path_config: &Option<Vec<String>>, _config: &Configuration,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_builder(conf: &AppConfig, location: &Option<String>) {
|
||||
let log_level = match conf.log_level.as_str() {
|
||||
"info" => LevelFilter::Info,
|
||||
"error" => LevelFilter::Error,
|
||||
"warn" => LevelFilter::Warn,
|
||||
"debug" => LevelFilter::Debug,
|
||||
"trace" => LevelFilter::Trace,
|
||||
"off" => LevelFilter::Off,
|
||||
_ => {
|
||||
println!("Error reading log level, defaulting to: INFO");
|
||||
LevelFilter::Info
|
||||
}
|
||||
};
|
||||
// let pattern = "{d(%Y-%m-%d %H:%M:%S)} {l} {t} - {m}{n}";
|
||||
let pattern = "{d(%Y-%m-%d %H:%M:%S)} {l} {t} - {m}\n";
|
||||
if let Some(location) = location {
|
||||
let file = FileAppender::builder().encoder(Box::new(PatternEncoder::new(pattern))).build(location).unwrap();
|
||||
let config = Log4rsConfig::builder()
|
||||
.appender(Appender::builder().build("file", Box::new(file)))
|
||||
.build(Root::builder().appender("file").build(log_level))
|
||||
.unwrap();
|
||||
log4rs::init_config(config).unwrap();
|
||||
} else {
|
||||
let stdout = ConsoleAppender::builder().encoder(Box::new(PatternEncoder::new(pattern))).build();
|
||||
let config = Log4rsConfig::builder()
|
||||
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||
.build(Root::builder().appender("stdout").build(log_level))
|
||||
.unwrap();
|
||||
log4rs::init_config(config).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@ pub type UpstreamsDashMap = DashMap<Arc<str>, DashMap<Arc<str>, (Vec<Arc<InnerMa
|
||||
|
||||
pub type UpstreamsIdMap = DashMap<String, Arc<InnerMap>>;
|
||||
pub type Headers = DashMap<Arc<str>, DashMap<Arc<str>, Vec<(String, Arc<str>)>>>;
|
||||
// pub type UpstreamsSerDde = Option<HashMap<String, HostConfig>>;
|
||||
// pub type UpstreamsSerDe = HashMap<String, HostConfig>;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Extraparams {
|
||||
@@ -112,6 +110,10 @@ pub struct AppConfig {
|
||||
pub hc_method: String,
|
||||
pub upstreams_conf: String,
|
||||
pub log_level: String,
|
||||
pub cache_size_mb: Option<usize>,
|
||||
pub cache_ttl: Option<u64>,
|
||||
pub access_log: Option<String>,
|
||||
pub pid_file: Option<String>,
|
||||
pub master_key: Option<String>,
|
||||
pub config_address: String,
|
||||
pub proxy_address_http: String,
|
||||
@@ -130,6 +132,9 @@ pub struct AppConfig {
|
||||
pub runuser: Option<String>,
|
||||
pub rungroup: Option<String>,
|
||||
pub log_file: Option<String>,
|
||||
pub tcp_keepalive_idle: Option<u64>,
|
||||
pub tcp_keepalive_interval: Option<u64>,
|
||||
pub tcp_keepalive_count: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
|
||||
|
||||
+16
-19
@@ -1,6 +1,6 @@
|
||||
use crate::tls::load;
|
||||
use crate::tls::load::CertificateConfig;
|
||||
use crate::utils::structs::{Extraparams, InnerMap, InnerMapForJson, UpstreamSnapshotForJson, UpstreamsDashMap, UpstreamsIdMap};
|
||||
use crate::utils::structs::{Extraparams, InnerMapForJson, UpstreamSnapshotForJson, UpstreamsDashMap, UpstreamsIdMap};
|
||||
use dashmap::DashMap;
|
||||
use log::{error, info};
|
||||
use notify::{event::ModifyKind, Config, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
@@ -10,9 +10,12 @@ use sha2::{Digest, Sha256};
|
||||
use std::any::type_name;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write as IoWrite;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::TcpListener;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::str::FromStr;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{channel, Sender};
|
||||
@@ -144,11 +147,8 @@ pub fn clone_idmap_into(original: &UpstreamsDashMap, cloned: &UpstreamsIdMap) {
|
||||
cloned.clear();
|
||||
for outer_entry in original.iter() {
|
||||
let inner_map = outer_entry.value();
|
||||
let new_inner_map = DashMap::new();
|
||||
for inner_entry in inner_map.iter() {
|
||||
let path = inner_entry.key();
|
||||
let (vec, _) = inner_entry.value();
|
||||
let new_vec = vec.clone();
|
||||
for x in vec.iter() {
|
||||
let mut id = String::new();
|
||||
write!(
|
||||
@@ -172,22 +172,8 @@ 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();
|
||||
let to_add = InnerMap {
|
||||
address: Arc::from("127.0.0.1"),
|
||||
port: 0,
|
||||
is_ssl: false,
|
||||
is_http2: false,
|
||||
to_https: false,
|
||||
rate_limit: None,
|
||||
x4xx_limit: None,
|
||||
healthcheck: None,
|
||||
redirect_to: None,
|
||||
authorization: None,
|
||||
};
|
||||
cloned.insert(id, Arc::from(to_add));
|
||||
cloned.insert(hh, x.to_owned());
|
||||
}
|
||||
new_inner_map.insert(path.clone(), new_vec);
|
||||
}
|
||||
}
|
||||
info!("Upstreams are fully populated. Ready to server requests");
|
||||
@@ -274,7 +260,7 @@ pub fn drop_priv(user: String, group: String, http_addr: String, tls_addr: Optio
|
||||
}
|
||||
|
||||
pub fn check_priv(addr: &str) {
|
||||
let port = SocketAddr::from_str(addr).map(|sa| sa.port()).unwrap();
|
||||
let port = SocketAddr::from_str(addr).map(|sa| sa.port()).expect("Failed to parse address port ");
|
||||
if port < 1024 {
|
||||
let meta = std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap();
|
||||
if meta != 0 {
|
||||
@@ -380,3 +366,14 @@ pub fn prepend(prefix: &str, val: &Option<Arc<str>>, uri: &str, port: &str) -> O
|
||||
buf
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_pid_file(path: &str) -> std::io::Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.custom_flags(libc::O_NOFOLLOW) // refuse to follow symlinks
|
||||
.open(path)?;
|
||||
file.write_all(process::id().to_string().as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod acme;
|
||||
pub mod bgservice;
|
||||
pub mod gethosts;
|
||||
pub mod logging;
|
||||
pub mod proxyhttp;
|
||||
pub mod start;
|
||||
pub mod webserver;
|
||||
|
||||
@@ -4,21 +4,21 @@ use crate::utils::parceyaml::load_configuration;
|
||||
use crate::utils::structs::Configuration;
|
||||
use crate::utils::tools::*;
|
||||
use crate::utils::*;
|
||||
use crate::web::logging::init_logging;
|
||||
use crate::web::proxyhttp::LB;
|
||||
use async_trait::async_trait;
|
||||
use dashmap::DashMap;
|
||||
use futures::channel::mpsc;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use log::{error, info};
|
||||
use pingora_core::server::ShutdownWatch;
|
||||
use pingora_core::services::background::BackgroundService;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for LB {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
info!("Starting background service"); // tx: Sender<Configuration>
|
||||
let (mut tx, mut rx) = mpsc::channel::<Configuration>(1);
|
||||
let (tx, mut rx) = mpsc::channel::<Configuration>(1);
|
||||
let tx_api = tx.clone();
|
||||
let config = load_configuration(self.config.upstreams_conf.clone().as_str(), "filepath")
|
||||
.await
|
||||
@@ -77,13 +77,13 @@ impl BackgroundService for LB {
|
||||
healthcheck::hc2(uu, ff, im, (&*hc_method.to_string(), hc_interval.to_string().parse().unwrap())).await
|
||||
}));
|
||||
drop(tokio::spawn(async move { refresh_order(certdir, confdir).await }));
|
||||
|
||||
init_logging(self.config.access_log.clone());
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => {
|
||||
break;
|
||||
}
|
||||
val = rx.next() => {
|
||||
val = rx.recv() => {
|
||||
if let Some(ss) = val {
|
||||
clone_dashmap_into(&ss.upstreams, &self.ump_full);
|
||||
clone_dashmap_into(&ss.upstreams, &self.ump_upst);
|
||||
|
||||
+23
-17
@@ -1,7 +1,6 @@
|
||||
use crate::utils::structs::InnerMap;
|
||||
use crate::web::proxyhttp::LB;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -10,30 +9,38 @@ pub struct GetHostsReturHeaders {
|
||||
pub server_headers: Option<Vec<(String, Arc<str>)>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait GetHost {
|
||||
fn find_sticky_backend(&self, servers: &[Arc<InnerMap>], backend_id: Option<&str>) -> Option<Arc<InnerMap>>;
|
||||
fn pick_backend(&self, servers: &[Arc<InnerMap>], index: &AtomicUsize, backend_id: Option<&str>) -> Option<Arc<InnerMap>>;
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<Arc<InnerMap>>;
|
||||
|
||||
fn get_header(&self, peer: &str, path: &str) -> Option<GetHostsReturHeaders>;
|
||||
// fn get_upstreams(&self) -> Arc<UpstreamsDashMap>;
|
||||
}
|
||||
#[async_trait]
|
||||
impl GetHost for LB {
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<Arc<InnerMap>> {
|
||||
if let Some(b) = backend_id {
|
||||
if let Some(bb) = self.ump_byid.get(b) {
|
||||
return Some(bb.value().clone());
|
||||
}
|
||||
fn find_sticky_backend(&self, servers: &[Arc<InnerMap>], backend_id: Option<&str>) -> Option<Arc<InnerMap>> {
|
||||
let b = backend_id?;
|
||||
let bb = self.ump_byid.get(b)?;
|
||||
let target = bb.value();
|
||||
servers.iter().any(|s| s.address == target.address && s.port == target.port).then(|| target.clone())
|
||||
}
|
||||
fn pick_backend(&self, servers: &[Arc<InnerMap>], index: &AtomicUsize, backend_id: Option<&str>) -> Option<Arc<InnerMap>> {
|
||||
if servers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(target) = self.find_sticky_backend(servers, backend_id) {
|
||||
return Some(target);
|
||||
}
|
||||
let idx = index.fetch_add(1, Ordering::Relaxed) % servers.len();
|
||||
Some(servers[idx].clone())
|
||||
}
|
||||
fn get_host(&self, peer: &str, path: &str, backend_id: Option<&str>) -> Option<Arc<InnerMap>> {
|
||||
let host_entry = self.ump_upst.get(peer)?;
|
||||
let mut end = path.len();
|
||||
loop {
|
||||
let slice = &path[..end];
|
||||
if let Some(entry) = host_entry.get(slice) {
|
||||
let (servers, index) = entry.value();
|
||||
if !servers.is_empty() {
|
||||
let idx = index.fetch_add(1, Ordering::Relaxed) % servers.len();
|
||||
return Some(servers[idx].clone());
|
||||
if let Some(backend) = self.pick_backend(servers, index, backend_id) {
|
||||
return Some(backend);
|
||||
}
|
||||
}
|
||||
if let Some(pos) = slice.rfind('/') {
|
||||
@@ -44,9 +51,8 @@ impl GetHost for LB {
|
||||
}
|
||||
if let Some(entry) = host_entry.get("/") {
|
||||
let (servers, index) = entry.value();
|
||||
if !servers.is_empty() {
|
||||
let idx = index.fetch_add(1, Ordering::Relaxed) % servers.len();
|
||||
return Some(servers[idx].clone());
|
||||
if let Some(backend) = self.pick_backend(servers, index, backend_id) {
|
||||
return Some(backend);
|
||||
}
|
||||
}
|
||||
None
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
use crate::utils::metrics::LOGGING_ERRORS;
|
||||
use crate::utils::structs::AppConfig;
|
||||
use log::{info, LevelFilter};
|
||||
use log4rs::append::rolling_file::policy::compound::roll::fixed_window::FixedWindowRoller;
|
||||
use log4rs::append::rolling_file::policy::compound::trigger::size::SizeTrigger;
|
||||
use log4rs::append::rolling_file::policy::compound::CompoundPolicy;
|
||||
use log4rs::append::rolling_file::RollingFileAppender;
|
||||
use log4rs::{
|
||||
append::console::ConsoleAppender,
|
||||
config::{Appender, Config as Log4rsConfig, Root},
|
||||
encode::pattern::PatternEncoder,
|
||||
};
|
||||
use pingora_cache::CachePhase;
|
||||
use pingora_http::Version;
|
||||
use pingora_proxy::Session;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::OnceLock;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LogMessage {
|
||||
pub response_code: u16,
|
||||
pub summary: String,
|
||||
pub client_ip: IpAddr,
|
||||
pub version: Version,
|
||||
pub user_agent: String,
|
||||
pub cache_status: CachePhase,
|
||||
}
|
||||
static LOG_SENDER: OnceLock<mpsc::Sender<LogMessage>> = OnceLock::new();
|
||||
static ACCESS_LOG: OnceLock<LogLevel> = OnceLock::new();
|
||||
const LOG_BUFFER: usize = 16384;
|
||||
|
||||
pub fn log_builder(conf: &AppConfig, location: &Option<String>) {
|
||||
let log_level = match conf.log_level.as_str() {
|
||||
"info" => LevelFilter::Info,
|
||||
"error" => LevelFilter::Error,
|
||||
"warn" => LevelFilter::Warn,
|
||||
"debug" => LevelFilter::Debug,
|
||||
"trace" => LevelFilter::Trace,
|
||||
"off" => LevelFilter::Off,
|
||||
_ => {
|
||||
println!("Error reading log level, defaulting to: INFO");
|
||||
LevelFilter::Info
|
||||
}
|
||||
};
|
||||
|
||||
let pattern = "{d(%Y-%m-%d %H:%M:%S)} {l} {t} - {m}\n";
|
||||
|
||||
if let Some(location) = location {
|
||||
let parts: Vec<&str> = location.splitn(4, ',').map(|s| s.trim()).collect();
|
||||
|
||||
let path = parts.get(0).expect("Syntax error, could not get path for log files");
|
||||
let compress = parts.get(3).unwrap_or(&"No");
|
||||
let size_mb: u64 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(100);
|
||||
let keep: u32 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(5);
|
||||
|
||||
let pattern_str = match compress {
|
||||
&"compress" => format!("{}.{{}}.gz", path),
|
||||
_ => format!("{}.{{}}", path),
|
||||
};
|
||||
|
||||
let roller = FixedWindowRoller::builder().build(pattern_str.as_str(), keep).unwrap();
|
||||
let trigger = SizeTrigger::new(size_mb * 1024 * 1024);
|
||||
let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roller));
|
||||
|
||||
let file = RollingFileAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(pattern)))
|
||||
.build(path, Box::new(policy))
|
||||
.unwrap();
|
||||
|
||||
let config = Log4rsConfig::builder()
|
||||
.appender(Appender::builder().build("file", Box::new(file)))
|
||||
.build(Root::builder().appender("file").build(log_level))
|
||||
.unwrap();
|
||||
log4rs::init_config(config).unwrap();
|
||||
info!("Logging to: {}, Max file size: {}mb, Files to keep: {}, compression: {} ", path, size_mb, keep, compress);
|
||||
} else {
|
||||
let stdout = ConsoleAppender::builder().encoder(Box::new(PatternEncoder::new(pattern))).build();
|
||||
|
||||
let config = Log4rsConfig::builder()
|
||||
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||
.build(Root::builder().appender("stdout").build(log_level))
|
||||
.unwrap();
|
||||
log4rs::init_config(config).unwrap();
|
||||
info!("No files are configured, logging to stdout");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_access_log(level_str: &str) {
|
||||
let level = LogLevel::from_str(level_str);
|
||||
let _ = ACCESS_LOG.set(level);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LogLevel {
|
||||
Access,
|
||||
Error,
|
||||
None,
|
||||
}
|
||||
|
||||
impl LogLevel {
|
||||
pub fn from_str(s: &str) -> Self {
|
||||
match s {
|
||||
"all" => LogLevel::Access,
|
||||
"error" => LogLevel::Error,
|
||||
_ => LogLevel::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn access_log(response_code: u16, summary: &str, session: &Session) {
|
||||
let level = ACCESS_LOG.get().unwrap_or(&LogLevel::None);
|
||||
|
||||
let should_log = match level {
|
||||
LogLevel::Access => true,
|
||||
LogLevel::None => false,
|
||||
LogLevel::Error => !(100..=399).contains(&response_code),
|
||||
};
|
||||
|
||||
if !should_log {
|
||||
return;
|
||||
}
|
||||
|
||||
let ip = session
|
||||
.client_addr()
|
||||
.and_then(|addr| addr.as_inet())
|
||||
.map(|addr| addr.ip())
|
||||
.unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST));
|
||||
|
||||
let user_agent = session.req_header().headers.get("user-agent").and_then(|v| v.to_str().ok()).unwrap_or("-");
|
||||
// let cache_status = match session.cache.phase() {
|
||||
// CachePhase::Hit => "Hit",
|
||||
// CachePhase::Miss => "Miss",
|
||||
// CachePhase::Expired => "Expired",
|
||||
// _ => "Disabled",
|
||||
// };
|
||||
let log = LogMessage {
|
||||
response_code,
|
||||
summary: summary.to_owned(),
|
||||
client_ip: ip,
|
||||
version: session.req_header().version,
|
||||
user_agent: user_agent.to_owned(),
|
||||
cache_status: session.cache.phase(),
|
||||
};
|
||||
|
||||
if let Some(sender) = LOG_SENDER.get() {
|
||||
let sender = sender;
|
||||
if let Err(_) = sender.try_send(log) {
|
||||
LOGGING_ERRORS.inc();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_logging(enabled: Option<String>) {
|
||||
if let Some(_) = enabled {
|
||||
LOGGING_ERRORS.set(0);
|
||||
info!("Enabling {:?} log, with buffer of {} messages", ACCESS_LOG.get().unwrap_or(&LogLevel::None), LOG_BUFFER);
|
||||
let (ltx, lrx) = mpsc::channel(LOG_BUFFER);
|
||||
LOG_SENDER.set(ltx).unwrap();
|
||||
std::thread::spawn(move || log_receiver(lrx));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn log_receiver(mut receiver: mpsc::Receiver<LogMessage>) {
|
||||
while let Some(msg) = receiver.blocking_recv() {
|
||||
info!(
|
||||
"{}, {}, {}, client: {}, version: {:?}, useragent: {}",
|
||||
msg.response_code,
|
||||
msg.cache_status.as_str(),
|
||||
msg.summary,
|
||||
msg.client_ip,
|
||||
msg.version,
|
||||
msg.user_agent,
|
||||
);
|
||||
}
|
||||
}
|
||||
+60
-21
@@ -1,15 +1,18 @@
|
||||
use crate::utils::auth::authenticate;
|
||||
use crate::utils::lazylock::{LOCALHOST, RATE_LIMITER, REQUESTS_4XX, REVERSE_STORE};
|
||||
use crate::utils::lazylock::{CACHE_LOCK, CACHE_TTL, EVICTION, LOCALHOST, MEM_CACHE, RATE_LIMITER, REQUESTS_4XX, REVERSE_STORE};
|
||||
use crate::utils::metrics::*;
|
||||
use crate::utils::structs::{AppConfig, Extraparams, Headers, InnerMap, UpstreamsDashMap, UpstreamsIdMap};
|
||||
use crate::web::gethosts::{GetHost, GetHostsReturHeaders};
|
||||
use crate::web::logging::access_log;
|
||||
use arc_swap::ArcSwap;
|
||||
use async_trait::async_trait;
|
||||
use axum::body::Bytes;
|
||||
use log::{debug, error, warn};
|
||||
use pingora::http::{RequestHeader, ResponseHeader, StatusCode};
|
||||
use log::error;
|
||||
use pingora::http::{Method, RequestHeader, ResponseHeader, StatusCode};
|
||||
use pingora::prelude::*;
|
||||
use pingora::ErrorSource::Upstream;
|
||||
use pingora_cache::cache_control::CacheControl;
|
||||
use pingora_cache::{CacheKey, CacheMetaDefaults, RespCacheable};
|
||||
use pingora_core::listeners::ALPN;
|
||||
use pingora_core::prelude::HttpPeer;
|
||||
use pingora_proxy::{ProxyHttp, Session};
|
||||
@@ -17,14 +20,10 @@ use sha2::{Digest, Sha256};
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
thread_local! {static IP_BUFFER: RefCell<String> = RefCell::new(String::with_capacity(50));}
|
||||
// static REVERSE_STORE: LazyLock<DashMap<String, String>> = LazyLock::new(DashMap::new);
|
||||
// pub static RATE_LIMITER: LazyLock<Rate> = LazyLock::new(|| Rate::new(Duration::from_secs(1)));
|
||||
// pub static REQUESTS_4XX: LazyLock<Cache<IpAddr, u32>> = LazyLock::new(|| Cache::builder().time_to_live(Duration::from_secs(1)).build());
|
||||
// pub static LOCALHOST: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("localhost"));
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct LB {
|
||||
pub ump_upst: Arc<UpstreamsDashMap>,
|
||||
@@ -34,6 +33,7 @@ pub struct LB {
|
||||
pub server_headers: Arc<Headers>,
|
||||
pub config: Arc<AppConfig>,
|
||||
pub extraparams: Arc<ArcSwap<Extraparams>>,
|
||||
pub cache_enabled: bool,
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
@@ -60,6 +60,34 @@ impl ProxyHttp for LB {
|
||||
x4xx_limit: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_key_callback(&self, session: &Session, _ctx: &mut Self::CTX) -> Result<CacheKey> {
|
||||
Ok(CacheKey::new(_ctx.hostname.clone().unwrap_or_default().as_ref(), session.req_header().uri.to_string(), ""))
|
||||
}
|
||||
fn request_cache_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<()> {
|
||||
if self.cache_enabled && session.req_header().method == Method::GET {
|
||||
if let Some(eviction) = EVICTION.get() {
|
||||
session.cache.enable(&*MEM_CACHE, Some(eviction), None, Some(&*CACHE_LOCK), None);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn response_cache_filter(&self, _session: &Session, resp: &ResponseHeader, _ctx: &mut Self::CTX) -> Result<RespCacheable> {
|
||||
let cc = CacheControl::from_resp_headers(resp);
|
||||
let defaults = CacheMetaDefaults::new(
|
||||
|status| {
|
||||
if status == StatusCode::OK {
|
||||
Some(Duration::from_secs(*CACHE_TTL.get().unwrap_or(&60)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
},
|
||||
0,
|
||||
0,
|
||||
);
|
||||
Ok(pingora_cache::filters::resp_cacheable(cc.as_ref(), resp.clone(), false, &defaults))
|
||||
}
|
||||
|
||||
async fn request_filter(&self, session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool> {
|
||||
ACTIVE_SESSIONS.inc();
|
||||
let hostname = return_header_host_from_upstream(session, &self.ump_upst);
|
||||
@@ -86,7 +114,6 @@ impl ProxyHttp for LB {
|
||||
if let Some(auth) = _ctx.extraparams.authentication.as_ref().or(innermap.authorization.as_ref()) {
|
||||
if !authenticate(&auth, session).await {
|
||||
let _ = session.respond_error(401).await;
|
||||
warn!("Forbidden: {:?}, {}", session.client_addr(), session.req_header().uri.path());
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
@@ -99,9 +126,6 @@ impl ProxyHttp for LB {
|
||||
let header = ResponseHeader::build(429, None)?;
|
||||
session.set_keepalive(None);
|
||||
session.write_response_header(Box::new(header), true).await?;
|
||||
if let (Some(oi), Some(oa)) = (&_ctx.hostname, rate_key) {
|
||||
warn!("Limit 4XX: {}-rps exceed on {} from {} path {}", rate, oi, oa, session.req_header().uri.path());
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
@@ -113,9 +137,6 @@ impl ProxyHttp for LB {
|
||||
let header = ResponseHeader::build(429, None)?;
|
||||
session.set_keepalive(None);
|
||||
session.write_response_header(Box::new(header), true).await?;
|
||||
if let (Some(oi), Some(oa)) = (&_ctx.hostname, rate_key) {
|
||||
warn!("Limit: {}-rps exceed on {} from {}", rate, oi, oa);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
@@ -169,7 +190,6 @@ impl ProxyHttp for LB {
|
||||
Some(hostname) => match ctx.upstream_peer.as_ref() {
|
||||
Some(innermap) => {
|
||||
let mut peer = Box::new(HttpPeer::new((&*innermap.address, innermap.port), innermap.is_ssl, hostname.to_string()));
|
||||
|
||||
if innermap.is_http2 {
|
||||
peer.options.alpn = ALPN::H2;
|
||||
}
|
||||
@@ -177,6 +197,20 @@ impl ProxyHttp for LB {
|
||||
peer.options.verify_cert = false;
|
||||
peer.options.verify_hostname = false;
|
||||
}
|
||||
/*
|
||||
Experimental optionsv
|
||||
The following TCP optimizations were tested but caused performance degrade under heavy load:
|
||||
peer.options.tcp_keepalive = Some(TcpKeepalive {
|
||||
idle: Duration::from_secs(60),
|
||||
interval: Duration::from_secs(10),
|
||||
count: 5,
|
||||
user_timeout: Duration::from_secs(30),
|
||||
});
|
||||
|
||||
peer.options.idle_timeout = Some(Duration::from_secs(300));
|
||||
peer.options.tcp_recv_buf = Some(128 * 1024);
|
||||
End of experimental options
|
||||
*/
|
||||
if let Some(_) = ctx.extraparams.sticky_sessions {
|
||||
let mut s = String::with_capacity(64);
|
||||
write!(
|
||||
@@ -267,15 +301,13 @@ impl ProxyHttp for LB {
|
||||
REVERSE_STORE.insert(hh.clone(), bid.clone());
|
||||
hh
|
||||
};
|
||||
// let _ = _upstream_response.insert_header("set-cookie", format!("backend_id={}; Path=/; Max-Age=600; HttpOnly; SameSite=Lax", tt));
|
||||
let mut buf = String::with_capacity(80);
|
||||
buf.push_str("backend_id=");
|
||||
buf.push_str(&tt);
|
||||
buf.push_str("; Path=/; Max-Age=");
|
||||
buf.push_str(&val.to_string());
|
||||
buf.push_str("; HttpOnly; SameSite=Lax");
|
||||
// buf.push_str("; Path=/; Max-Age=86400; HttpOnly; SameSite=Lax");
|
||||
let _ = _upstream_response.insert_header("set-cookie", buf.as_str());
|
||||
let _ = _upstream_response.append_header("set-cookie", buf.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +321,6 @@ impl ProxyHttp for LB {
|
||||
|
||||
async fn logging(&self, session: &mut Session, _e: Option<&pingora::Error>, ctx: &mut Self::CTX) {
|
||||
let response_code = session.response_written().map_or(0, |resp| resp.status.as_u16());
|
||||
debug!("{}, response code: {response_code}", self.request_summary(session, ctx));
|
||||
let m = &MetricTypes {
|
||||
method: session.req_header().method.clone(),
|
||||
code: session.response_written().map(|resp| resp.status),
|
||||
@@ -300,13 +331,21 @@ impl ProxyHttp for LB {
|
||||
calc_metrics(m);
|
||||
ACTIVE_SESSIONS.dec();
|
||||
if let Some(_) = ctx.x4xx_limit.or(ctx.extraparams.x4xx_limit) {
|
||||
if 400 <= response_code && response_code <= 499 {
|
||||
if (400..=499).contains(&response_code) {
|
||||
if let Some(ip) = session.client_addr().and_then(|a| a.as_inet()).map(|i| i.ip()) {
|
||||
let current = REQUESTS_4XX.get(&ip).unwrap_or(0);
|
||||
REQUESTS_4XX.insert(ip, current + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// match session.cache.phase() {
|
||||
// CachePhase::Hit => info!("Cache Status: HIT (Served from Memory)"),
|
||||
// CachePhase::Miss => info!("Cache Status: MISS (Fetched from Upstream)"),
|
||||
// CachePhase::Expired => info!("Cache Status: EXPIRED (Revalidating)"),
|
||||
// _ => {}
|
||||
// }
|
||||
|
||||
access_log(response_code, &self.request_summary(session, ctx), session);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+51
-6
@@ -2,15 +2,20 @@
|
||||
use crate::tls::grades;
|
||||
use crate::tls::load;
|
||||
use crate::tls::load::CertificateConfig;
|
||||
use crate::utils::lazylock::{CACHE_TTL, EVICTION};
|
||||
use crate::utils::structs::Extraparams;
|
||||
use crate::utils::tools::*;
|
||||
use crate::web::logging::init_access_log;
|
||||
use crate::web::proxyhttp::LB;
|
||||
use arc_swap::ArcSwap;
|
||||
use dashmap::DashMap;
|
||||
use log::info;
|
||||
use pingora::tls::ssl::{SslAlert, SslRef};
|
||||
use pingora_cache::eviction::simple_lru::Manager;
|
||||
use pingora_core::listeners::tls::TlsSettings;
|
||||
use pingora_core::listeners::TcpSocketOptions;
|
||||
use pingora_core::prelude::{background_service, Opt};
|
||||
use pingora_core::protocols::TcpKeepalive;
|
||||
use pingora_core::server::Server;
|
||||
use privdrop::reexports::libc::SIGQUIT;
|
||||
use sd_notify::NotifyState;
|
||||
@@ -21,7 +26,7 @@ use signal_hook::{
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::{fs, process, thread};
|
||||
use std::{fs, thread};
|
||||
|
||||
pub fn run() {
|
||||
// default_provider().install_default().expect("Failed to install rustls crypto provider");
|
||||
@@ -29,6 +34,13 @@ pub fn run() {
|
||||
let file = parameters.conf.clone().unwrap();
|
||||
let maincfg = crate::utils::parceyaml::parce_main_config(file.as_str());
|
||||
|
||||
let cache_enabled = maincfg.cache_size_mb.is_some();
|
||||
CACHE_TTL.set(maincfg.cache_ttl.unwrap_or(60)).unwrap();
|
||||
if let Some(size) = maincfg.cache_size_mb {
|
||||
let cache_size = size * 1024 * 1024;
|
||||
drop(EVICTION.set(Manager::new(cache_size)));
|
||||
}
|
||||
|
||||
let mut server = Server::new(parameters).unwrap();
|
||||
server.bootstrap();
|
||||
|
||||
@@ -56,18 +68,43 @@ pub fn run() {
|
||||
client_headers: ch_config,
|
||||
server_headers: sh_config,
|
||||
extraparams: ec_config,
|
||||
cache_enabled: cache_enabled,
|
||||
};
|
||||
let al = cfg.access_log.clone().unwrap_or("none".to_string());
|
||||
init_access_log(al.as_str());
|
||||
|
||||
let grade = cfg.proxy_tls_grade.clone().unwrap_or("medium".to_string());
|
||||
info!("TLS grade set to: [ {} ]", grade);
|
||||
|
||||
let bg_srvc = background_service("bgsrvc", lb.clone());
|
||||
let mut proxy = pingora_proxy::http_proxy_service(&server.configuration, lb.clone());
|
||||
let bind_address_http = cfg.proxy_address_http.clone();
|
||||
let bind_address_tls = cfg.proxy_address_tls.clone();
|
||||
|
||||
let mut proxy = pingora_proxy::http_proxy_service(&server.configuration, lb.clone());
|
||||
|
||||
check_priv(bind_address_http.as_str());
|
||||
|
||||
// let mut tcp_options: Option<TcpSocketOptions> = Some(TcpSocketOptions::default());
|
||||
// let mut tcp_options = TcpSocketOptions::default();
|
||||
|
||||
let mut tcp_options: Option<TcpSocketOptions> = None;
|
||||
if let Some(idle) = cfg.tcp_keepalive_idle {
|
||||
let mut to = TcpSocketOptions::default();
|
||||
to.tcp_keepalive = Some(TcpKeepalive {
|
||||
idle: Duration::from_secs(idle),
|
||||
interval: Duration::from_secs(cfg.tcp_keepalive_interval.unwrap_or(10)),
|
||||
user_timeout: Default::default(),
|
||||
count: cfg.tcp_keepalive_count.unwrap_or(5usize),
|
||||
});
|
||||
tcp_options = Some(to);
|
||||
info!(
|
||||
"Applying kernel tcp_keepalive parameters: idle {}, interval {}, count {}",
|
||||
idle,
|
||||
cfg.tcp_keepalive_interval.unwrap_or(60),
|
||||
cfg.tcp_keepalive_count.unwrap_or(5),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(bind_address_tls) = bind_address_tls {
|
||||
check_priv(bind_address_tls.as_str());
|
||||
let (tx, rx): (Sender<Vec<CertificateConfig>>, Receiver<Vec<CertificateConfig>>) = channel();
|
||||
@@ -95,7 +132,7 @@ pub fn run() {
|
||||
tls_settings.set_servername_callback(move |ssl_ref: &mut SslRef, ssl_alert: &mut SslAlert| certs_for_callback.load().server_name_callback(ssl_ref, ssl_alert));
|
||||
tls_settings.set_alpn_select_callback(grades::prefer_h2);
|
||||
|
||||
proxy.add_tls_with_settings(&bind_address_tls, None, tls_settings);
|
||||
proxy.add_tls_with_settings(&bind_address_tls, tcp_options.clone(), tls_settings);
|
||||
|
||||
let certs_for_watcher = certificates.clone();
|
||||
thread::spawn(move || {
|
||||
@@ -107,8 +144,13 @@ pub fn run() {
|
||||
}
|
||||
});
|
||||
}
|
||||
info!("Running HTTP listener on :{}", bind_address_http.as_str());
|
||||
proxy.add_tcp(bind_address_http.as_str());
|
||||
info!("Running HTTP listener on :{}", bind_address_http);
|
||||
if let Some(tc) = tcp_options {
|
||||
proxy.add_tcp_with_settings(&bind_address_http, tc);
|
||||
} else {
|
||||
proxy.add_tcp(&bind_address_http)
|
||||
}
|
||||
|
||||
server.add_service(proxy);
|
||||
server.add_service(bg_srvc);
|
||||
thread::spawn(move || server.run_forever());
|
||||
@@ -117,8 +159,11 @@ pub fn run() {
|
||||
drop_priv(user, group, cfg.proxy_address_http.clone(), cfg.proxy_address_tls.clone());
|
||||
}
|
||||
let _ = sd_notify::notify(&[NotifyState::Ready]);
|
||||
let _ = fs::write("/tmp/aralez.pid", process::id().to_string());
|
||||
|
||||
let pf = cfg.pid_file.clone().unwrap_or("/tmp/aralez.pid".to_string());
|
||||
if let Err(e) = write_pid_file(pf.as_str()) {
|
||||
panic!("Failed to write PID file: {} : {}", pf, e);
|
||||
}
|
||||
let mut signals = Signals::new(&[SIGINT, SIGTERM, SIGQUIT]).unwrap();
|
||||
for sig in signals.forever() {
|
||||
match sig {
|
||||
|
||||
+29
-23
@@ -10,14 +10,14 @@ use axum::http::{Response, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::{any, get, post};
|
||||
use axum::{Json, Router};
|
||||
use futures::channel::mpsc::Sender;
|
||||
use futures::SinkExt;
|
||||
use jsonwebtoken::{encode, EncodingKey, Header};
|
||||
use log::{debug, error, info, warn};
|
||||
use prometheus::{gather, Encoder, TextEncoder};
|
||||
use serde::Serialize;
|
||||
use signal_hook::{consts::SIGQUIT, iterator::Signals};
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
@@ -35,14 +35,14 @@ pub(crate) struct AppState {
|
||||
pub(crate) cert_creds: String,
|
||||
pub(crate) certs_dir: String,
|
||||
upstreams_file: String,
|
||||
config_sender: Sender<Configuration>,
|
||||
config_sender: mpsc::Sender<Configuration>,
|
||||
config_api_enabled: bool,
|
||||
current_upstreams: Arc<UpstreamsDashMap>,
|
||||
full_upstreams: Arc<UpstreamsDashMap>,
|
||||
}
|
||||
|
||||
#[allow(unused_mut)]
|
||||
pub async fn run_server(config: &APIUpstreamProvider, mut to_return: Sender<Configuration>, upstreams_curr: Arc<UpstreamsDashMap>, upstreams_full: Arc<UpstreamsDashMap>) {
|
||||
pub async fn run_server(config: &APIUpstreamProvider, mut to_return: mpsc::Sender<Configuration>, upstreams_curr: Arc<UpstreamsDashMap>, upstreams_full: Arc<UpstreamsDashMap>) {
|
||||
let credsfile = config.config_dir.clone() + "/acme_credentials.json";
|
||||
let app_state = AppState {
|
||||
master_key: config.masterkey.clone(),
|
||||
@@ -67,16 +67,24 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: Sender<Conf
|
||||
|
||||
let mut static_handle: Option<tokio::task::JoinHandle<()>> = None;
|
||||
if let (Some(address), Some(folder)) = (&config.file_server_address, &config.file_server_folder) {
|
||||
port_is_available("File Server", &address).await;
|
||||
let static_listen = port_is_available("File Server", &address).await;
|
||||
let static_files = ServeDir::new(folder);
|
||||
let static_serve: Router = Router::new().fallback_service(static_files);
|
||||
let static_listen = TcpListener::bind(address).await.unwrap();
|
||||
// drop(tokio::spawn(async move { axum::serve(static_listen, static_serve).await.unwrap() }));
|
||||
static_handle = Some(tokio::spawn(async move { axum::serve(static_listen, static_serve).await.unwrap() }))
|
||||
info!("Starting file server on: {}", address);
|
||||
|
||||
static_handle = Some(tokio::spawn(async move {
|
||||
match axum::serve(static_listen, static_serve).await {
|
||||
Ok(o) => info!("File server exited normally: {:?}", o),
|
||||
Err(e) => error!("File server exited: {}", e),
|
||||
}
|
||||
}))
|
||||
|
||||
// let a = config.file_server_address.to_owned();
|
||||
// let f = config.file_server_folder.to_owned();
|
||||
// drop(tokio::spawn(async move { run_file_server(a, f).await }));
|
||||
}
|
||||
|
||||
port_is_available("Config API", &config.address).await;
|
||||
let listener = TcpListener::bind(config.address.clone()).await.unwrap();
|
||||
let listener = port_is_available("Config API", &config.address).await;
|
||||
info!("Starting the API server on: {}", config.address);
|
||||
let api_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
|
||||
@@ -102,7 +110,7 @@ async fn conf(State(st): State<AppState>, Query(params): Query<HashMap<String, S
|
||||
}
|
||||
|
||||
let strcontent = content.as_str();
|
||||
let parsed = serde_yml::from_str::<Config>(strcontent);
|
||||
let parsed = noyalib::from_str::<Config>(strcontent);
|
||||
match parsed {
|
||||
Ok(_) => {
|
||||
if let Some(_) = params.get("save") {
|
||||
@@ -119,7 +127,7 @@ async fn conf(State(st): State<AppState>, Query(params): Query<HashMap<String, S
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_config(content: &str, mut st: AppState, save: bool) {
|
||||
async fn apply_config(content: &str, st: AppState, save: bool) {
|
||||
let sl = crate::utils::parceyaml::load_configuration(content, "content").await;
|
||||
if let Some(serverlist) = sl.0 {
|
||||
if save {
|
||||
@@ -227,20 +235,18 @@ async fn status(State(st): State<AppState>, Query(params): Query<HashMap<String,
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub async fn port_is_available(name: &str, address: &str) {
|
||||
let addr_port = address.split(":").collect::<Vec<&str>>();
|
||||
pub async fn port_is_available(name: &str, address: &str) -> TcpListener {
|
||||
let addr = SocketAddr::from_str(address).unwrap_or_else(|e| panic!("{}: Invalid address format: {:?}", name, e));
|
||||
let t = Duration::from_secs(2);
|
||||
|
||||
let mut a = addr_port[0];
|
||||
if address == "0.0.0.0" {
|
||||
a = "127.0.0.1";
|
||||
}
|
||||
let p = addr_port[1].parse::<u16>().unwrap();
|
||||
|
||||
//if addr.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED) {
|
||||
// addr.set_ip(IpAddr::V4(Ipv4Addr::LOCALHOST));
|
||||
//}
|
||||
let p = addr.port();
|
||||
loop {
|
||||
match TcpListener::bind((a, p)).await {
|
||||
Ok(_) => {
|
||||
break;
|
||||
match TcpListener::bind(addr).await {
|
||||
Ok(listener) => {
|
||||
return listener;
|
||||
}
|
||||
Err(_) => {
|
||||
warn!("{} port is not available: {} will try again in {:?}", name, p, t);
|
||||
|
||||
Reference in New Issue
Block a user