mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-29 05:56:38 +08:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 891cb7b9c1 | |||
| 007b1d8929 | |||
| 782304012c | |||
| 4945b8b44f | |||
| 1fbe156a7c | |||
| c844f4c784 | |||
| 67197220ae | |||
| 0cb4e06b11 | |||
| c84d5bd540 |
@@ -226,6 +226,9 @@ go run ./cmd/agent -config /path/to/agent.json
|
||||
|
||||
登录管理端后,可访问 Swagger UI:`/swagger/index.html`
|
||||
|
||||
如需重新生成 Swagger 文档,请使用与服务端依赖一致的版本:
|
||||
`go install github.com/swaggo/swag/cmd/swag@v1.16.4`
|
||||
|
||||
## 开源协议
|
||||
|
||||
本项目采用 [Apache License 2.0](./LICENSE) 开源。
|
||||
|
||||
+6
-2
@@ -76,14 +76,18 @@ OpenResty 性能参数与缓存参数继续统一保存在 `Option` 表。当前
|
||||
* `OpenRestyProxyReadTimeout`
|
||||
* `OpenRestyProxyBufferingEnabled`
|
||||
* `OpenRestyGzipEnabled`
|
||||
* `OpenRestyResolvers`
|
||||
* `OpenRestyCacheEnabled`
|
||||
* `OpenRestyCachePath`
|
||||
* `OpenRestyCacheMaxSize`
|
||||
|
||||
这类参数必须以结构化方式校验、保存并参与版本渲染。
|
||||
|
||||
* `OpenRestyResolvers` 由管理端性能页面维护,支持填写多个 DNS 服务器 IP;留空时不额外生成 `resolver` 指令。
|
||||
* 管理端不再暴露 `resolver` 配置;规则上游统一渲染为 named `upstream` 并启用 keepalive,单上游如带 base path 或 query,会在 `proxy_pass` 中补回原始 URI。
|
||||
* 多上游仍要求每个上游都为纯 `scheme://host[:port]`,且同一规则内协议一致,避免在负载均衡模式下引入不可预测的 URI 差异。
|
||||
* `OpenRestyCacheEnabled` 用于启用缓存基础设施与全局默认参数;实际是否缓存、按 URL / 后缀 / 路径等命中策略由各条 `proxy_routes` 单独决定,不再默认对所有规则开启缓存。
|
||||
* 默认缓存 Key 为 `$scheme$host$request_uri`,更贴近代理域名维度;如需按其他维度命中,可在性能页显式覆盖。
|
||||
* 默认 `keepalive_timeout` 为 `20` 秒,默认 `proxy_connect_timeout` 为 `3` 秒,优先兼顾资源占用与回源失败切换速度。
|
||||
* 默认事件模型为 `epoll`,并默认开启 `multi_accept`;HTTPS 监听默认使用独立 `http2 on;` 指令,避免新版 Nginx/OpenResty 对 `listen ... http2` 的弃用告警。
|
||||
### 1.5 前端构建环境变量
|
||||
|
||||
| 环境变量 | 作用 | 默认值 |
|
||||
|
||||
+1
-1
@@ -107,7 +107,7 @@ docker compose up -d
|
||||
如需在本地重新生成文档:
|
||||
|
||||
```bash
|
||||
go install github.com/swaggo/swag/cmd/swag@latest
|
||||
go install github.com/swaggo/swag/cmd/swag@v1.16.4
|
||||
cd openflare_server
|
||||
swag init -g main.go -o docs
|
||||
```
|
||||
|
||||
+5
-2
@@ -119,10 +119,12 @@ Origin
|
||||
|
||||
稳定约束:
|
||||
|
||||
* 一个域名只对应一个 `origin_url`
|
||||
* 一个域名只对应一条 `proxy_routes` 规则
|
||||
* `proxy_routes` 至少包含一个上游地址;为兼容历史数据保留 `origin_url` 主上游字段,也允许在同一规则内补充多个上游做负载均衡
|
||||
* `proxy_routes` 上游统一渲染为带 keepalive 的 named `upstream`;单上游可附带 base path 或 query 并在 `proxy_pass` 中追加,多上游仍限定为纯 `scheme://host[:port]`
|
||||
* `proxy_routes.origin_host` 为可选字段,用于回源时覆盖 `Host` 请求头;未设置时默认透传访问域名
|
||||
* `proxy_routes.domain` 必须唯一
|
||||
* `origin_url` 必须为合法 `http://` 或 `https://`
|
||||
* 所有上游地址都必须为合法 `http://` 或 `https://`
|
||||
* `config_versions` 必须保存完整快照、渲染结果与 `checksum`
|
||||
* 全局同时只能有一个激活版本
|
||||
* 回滚通过重新激活旧版本实现
|
||||
@@ -171,6 +173,7 @@ Origin
|
||||
* 主配置、路由配置、证书与 Lua 资源写入
|
||||
* 执行 `openresty -t` / `openresty -s reload`
|
||||
* 失败回滚
|
||||
* 对已失败并回退的目标版本做本地熔断,直到控制面出现新的激活版本
|
||||
* 节点观测采集与结果上报
|
||||
|
||||
### 7.3 `openflare_server/web`
|
||||
|
||||
@@ -115,7 +115,8 @@
|
||||
通用约束:
|
||||
|
||||
* 不新增平台化对象,除非设计文档明确要求
|
||||
* `proxy_routes` 维持一条域名对应一个 `origin_url`
|
||||
* `proxy_routes` 维持一条域名对应一条规则;规则内允许保存一个或多个上游地址用于负载均衡,但不引入独立 `origin_pool`
|
||||
* `proxy_routes` 的上游统一使用 named `upstream` + keepalive;单上游如带 base path 或 query,应在 `proxy_pass` 上补回 URI,多上游仅允许纯 `scheme://host[:port]`
|
||||
* `proxy_routes.origin_host` 为可选字段,仅用于覆盖回源 `Host` 请求头,不引入新的平台化对象
|
||||
* `config_versions` 必须保存完整快照与渲染结果
|
||||
* 全局同时只能有一个激活版本
|
||||
@@ -191,6 +192,7 @@ Agent 必须满足:
|
||||
* 写入新配置后以运行态恢复为目标执行激活,Docker 模式优先重建容器并确认容器保持运行
|
||||
* 新配置激活失败时必须先尝试用目标配置恢复运行,再回滚到旧配置并重新拉起 OpenResty
|
||||
* 回滚后 OpenResty 恢复正常时上报警告;回滚后仍无法恢复运行时上报失败
|
||||
* 某个目标 `version + checksum` 一旦应用失败并回退,Agent 必须在本地状态中阻断该目标的重复应用;只有远端激活版本或 checksum 发生变化时,才允许再次尝试
|
||||
|
||||
## 6. 测试与交付要求
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ type Snapshot struct {
|
||||
NodeID string `json:"node_id"`
|
||||
CurrentVersion string `json:"current_version"`
|
||||
CurrentChecksum string `json:"current_checksum"`
|
||||
BlockedVersion string `json:"blocked_version"`
|
||||
BlockedChecksum string `json:"blocked_checksum"`
|
||||
BlockedReason string `json:"blocked_reason"`
|
||||
LastError string `json:"last_error"`
|
||||
OpenrestyStatus string `json:"openresty_status"`
|
||||
OpenrestyMessage string `json:"openresty_message"`
|
||||
|
||||
@@ -105,13 +105,27 @@ func (s *Service) sync(ctx context.Context, startup bool, target *protocol.Activ
|
||||
}
|
||||
snapshot.CurrentVersion = target.Version
|
||||
snapshot.CurrentChecksum = target.Checksum
|
||||
clearBlockedTarget(snapshot)
|
||||
snapshot.LastError = ""
|
||||
slog.Debug("sync finished without changes", "mode", mode, "version", target.Version)
|
||||
return s.stateStore.Save(snapshot)
|
||||
}
|
||||
if isBlockedTarget(snapshot, target.Version, target.Checksum) {
|
||||
slog.Warn("skipping blocked config version after previous failed apply", "mode", mode, "version", target.Version, "checksum", target.Checksum)
|
||||
if startup {
|
||||
if err = s.ensureRuntimeForCurrentConfig(ctx, mode, snapshot, currentChecksum); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.stateStore.Save(snapshot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if hasBlockedTarget(snapshot) {
|
||||
clearBlockedTarget(snapshot)
|
||||
}
|
||||
if snapshot.CurrentVersion == target.Version && snapshot.CurrentChecksum == target.Checksum && !startup {
|
||||
slog.Debug("skipping config fetch because state already records target version/checksum", "version", target.Version, "checksum", target.Checksum)
|
||||
return nil
|
||||
return s.stateStore.Save(snapshot)
|
||||
}
|
||||
|
||||
config, err := s.client.GetActiveConfig(ctx)
|
||||
@@ -139,6 +153,7 @@ func (s *Service) applyIfNeeded(ctx context.Context, mode string, startup bool,
|
||||
}
|
||||
snapshot.CurrentVersion = config.Version
|
||||
snapshot.CurrentChecksum = config.Checksum
|
||||
clearBlockedTarget(snapshot)
|
||||
snapshot.LastError = ""
|
||||
slog.Debug("sync finished without changes", "mode", mode, "version", config.Version)
|
||||
return s.stateStore.Save(snapshot)
|
||||
@@ -146,9 +161,22 @@ func (s *Service) applyIfNeeded(ctx context.Context, mode string, startup bool,
|
||||
if target != nil && (target.Version != config.Version || target.Checksum != config.Checksum) {
|
||||
slog.Warn("active config changed between heartbeat and fetch", "heartbeat_version", target.Version, "heartbeat_checksum", target.Checksum, "fetched_version", config.Version, "fetched_checksum", config.Checksum)
|
||||
}
|
||||
if isBlockedTarget(snapshot, config.Version, config.Checksum) {
|
||||
slog.Warn("skipping blocked config after fetch because the same version previously failed", "mode", mode, "version", config.Version, "checksum", config.Checksum)
|
||||
if startup {
|
||||
if err := s.ensureRuntimeForCurrentConfig(ctx, mode, snapshot, currentChecksum); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.stateStore.Save(snapshot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if hasBlockedTarget(snapshot) {
|
||||
clearBlockedTarget(snapshot)
|
||||
}
|
||||
if snapshot.CurrentVersion == config.Version && snapshot.CurrentChecksum == config.Checksum && !startup {
|
||||
slog.Debug("skipping apply because state already records target version/checksum", "version", config.Version, "checksum", config.Checksum)
|
||||
return nil
|
||||
return s.stateStore.Save(snapshot)
|
||||
}
|
||||
routeConfig := config.RouteConfig
|
||||
if routeConfig == "" {
|
||||
@@ -172,6 +200,7 @@ func (s *Service) applyIfNeeded(ctx context.Context, mode string, startup bool,
|
||||
slog.Info("openresty config applied successfully", "mode", mode, "version", config.Version)
|
||||
snapshot.CurrentVersion = config.Version
|
||||
snapshot.CurrentChecksum = config.Checksum
|
||||
clearBlockedTarget(snapshot)
|
||||
snapshot.LastError = ""
|
||||
snapshot.OpenrestyStatus = protocol.OpenrestyStatusHealthy
|
||||
snapshot.OpenrestyMessage = ""
|
||||
@@ -184,6 +213,7 @@ func (s *Service) applyIfNeeded(ctx context.Context, mode string, startup bool,
|
||||
message = "apply rolled back to previous config"
|
||||
}
|
||||
slog.Warn("openresty config apply rolled back", "mode", mode, "version", config.Version, "message", message)
|
||||
markBlockedTarget(snapshot, config.Version, config.Checksum, message)
|
||||
snapshot.LastError = message
|
||||
snapshot.OpenrestyStatus = protocol.OpenrestyStatusHealthy
|
||||
snapshot.OpenrestyMessage = message
|
||||
@@ -193,6 +223,7 @@ func (s *Service) applyIfNeeded(ctx context.Context, mode string, startup bool,
|
||||
message = "openresty apply failed"
|
||||
}
|
||||
slog.Error("apply openresty config failed", "mode", mode, "version", config.Version, "message", message)
|
||||
markBlockedTarget(snapshot, config.Version, config.Checksum, message)
|
||||
snapshot.LastError = message
|
||||
snapshot.OpenrestyStatus = protocol.OpenrestyStatusUnhealthy
|
||||
snapshot.OpenrestyMessage = message
|
||||
@@ -230,6 +261,56 @@ func outcomeError(version string, message string) error {
|
||||
return fmt.Errorf("apply version %s failed: %s", version, trimmed)
|
||||
}
|
||||
|
||||
func (s *Service) ensureRuntimeForCurrentConfig(ctx context.Context, mode string, snapshot *state.Snapshot, currentChecksum string) error {
|
||||
if strings.TrimSpace(currentChecksum) == "" {
|
||||
slog.Warn("blocked config cannot be retried and no local checksum is available for runtime recovery", "mode", mode, "blocked_version", snapshot.BlockedVersion)
|
||||
return nil
|
||||
}
|
||||
slog.Info("ensuring runtime with current local config while active target remains blocked", "mode", mode, "current_version", snapshot.CurrentVersion, "current_checksum", currentChecksum, "blocked_version", snapshot.BlockedVersion)
|
||||
if err := s.nginxManager.EnsureRuntime(ctx, true); err != nil {
|
||||
snapshot.OpenrestyStatus = protocol.OpenrestyStatusUnhealthy
|
||||
snapshot.OpenrestyMessage = err.Error()
|
||||
_ = s.stateStore.Save(snapshot)
|
||||
return err
|
||||
}
|
||||
snapshot.OpenrestyStatus = protocol.OpenrestyStatusHealthy
|
||||
if strings.TrimSpace(snapshot.OpenrestyMessage) == strings.TrimSpace(snapshot.BlockedReason) {
|
||||
snapshot.OpenrestyMessage = ""
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func markBlockedTarget(snapshot *state.Snapshot, version string, checksum string, reason string) {
|
||||
if snapshot == nil {
|
||||
return
|
||||
}
|
||||
snapshot.BlockedVersion = strings.TrimSpace(version)
|
||||
snapshot.BlockedChecksum = strings.TrimSpace(checksum)
|
||||
snapshot.BlockedReason = strings.TrimSpace(reason)
|
||||
}
|
||||
|
||||
func clearBlockedTarget(snapshot *state.Snapshot) {
|
||||
if snapshot == nil {
|
||||
return
|
||||
}
|
||||
snapshot.BlockedVersion = ""
|
||||
snapshot.BlockedChecksum = ""
|
||||
snapshot.BlockedReason = ""
|
||||
}
|
||||
|
||||
func hasBlockedTarget(snapshot *state.Snapshot) bool {
|
||||
return snapshot != nil && (strings.TrimSpace(snapshot.BlockedVersion) != "" || strings.TrimSpace(snapshot.BlockedChecksum) != "")
|
||||
}
|
||||
|
||||
func isBlockedTarget(snapshot *state.Snapshot, version string, checksum string) bool {
|
||||
if snapshot == nil {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(snapshot.BlockedVersion) == strings.TrimSpace(version) &&
|
||||
strings.TrimSpace(snapshot.BlockedChecksum) == strings.TrimSpace(checksum) &&
|
||||
(strings.TrimSpace(version) != "" || strings.TrimSpace(checksum) != "")
|
||||
}
|
||||
|
||||
func checksumString(content string) string {
|
||||
sum := sha256.Sum256([]byte(content))
|
||||
return hex.EncodeToString(sum[:])
|
||||
|
||||
@@ -203,6 +203,9 @@ func TestSyncOnceRollbackOnNginxFailure(t *testing.T) {
|
||||
if snapshot.CurrentVersion != "20260309-001" {
|
||||
t.Fatal("expected failed sync not to overwrite current version")
|
||||
}
|
||||
if snapshot.BlockedVersion != "20260309-002" || snapshot.BlockedChecksum != "checksum-2" {
|
||||
t.Fatalf("expected failed target version to be blocked, got %+v", snapshot)
|
||||
}
|
||||
if snapshot.OpenrestyStatus != protocol.OpenrestyStatusUnhealthy {
|
||||
t.Fatalf("expected unhealthy openresty status, got %q", snapshot.OpenrestyStatus)
|
||||
}
|
||||
@@ -267,6 +270,9 @@ func TestSyncOnceReportsWarningWhenRollbackKeepsOpenrestyHealthy(t *testing.T) {
|
||||
if snapshot.CurrentVersion != "20260309-001" || snapshot.CurrentChecksum != "checksum-1" {
|
||||
t.Fatal("expected warning apply to keep previous version state")
|
||||
}
|
||||
if snapshot.BlockedVersion != "20260309-002" || snapshot.BlockedChecksum != "checksum-2" {
|
||||
t.Fatalf("expected rolled-back target version to be blocked, got %+v", snapshot)
|
||||
}
|
||||
if snapshot.OpenrestyStatus != protocol.OpenrestyStatusHealthy {
|
||||
t.Fatalf("expected healthy openresty after rollback, got %q", snapshot.OpenrestyStatus)
|
||||
}
|
||||
@@ -368,6 +374,165 @@ func TestSyncOnStartupRecordsRuntimeFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncOnceSkipsPreviouslyBlockedVersion(t *testing.T) {
|
||||
client := &fakeClient{
|
||||
config: protocol.ActiveConfigResponse{
|
||||
Version: "20260309-006",
|
||||
Checksum: "checksum-6",
|
||||
MainConfig: "worker_processes 6;",
|
||||
RouteConfig: "server { listen 86; }",
|
||||
RenderedConfig: "server { listen 86; }",
|
||||
CreatedAt: time.Now().Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
stateStore := state.NewStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
nodeID, err := stateStore.EnsureNodeID()
|
||||
if err != nil {
|
||||
t.Fatalf("EnsureNodeID failed: %v", err)
|
||||
}
|
||||
if err = stateStore.Save(&state.Snapshot{
|
||||
NodeID: nodeID,
|
||||
CurrentVersion: "20260309-005",
|
||||
CurrentChecksum: "checksum-5",
|
||||
BlockedVersion: "20260309-006",
|
||||
BlockedChecksum: "checksum-6",
|
||||
BlockedReason: "apply failed, rolled back to previous config",
|
||||
LastError: "apply failed, rolled back to previous config",
|
||||
}); err != nil {
|
||||
t.Fatalf("failed to seed state: %v", err)
|
||||
}
|
||||
|
||||
manager := &fakeManager{currentChecksum: "checksum-5"}
|
||||
service := New(client, manager, stateStore)
|
||||
if err = service.SyncOnce(context.Background(), &protocol.ActiveConfigMeta{
|
||||
Version: "20260309-006",
|
||||
Checksum: "checksum-6",
|
||||
}); err != nil {
|
||||
t.Fatalf("expected blocked version to be skipped, got %v", err)
|
||||
}
|
||||
if client.fetchCalls != 0 {
|
||||
t.Fatalf("expected blocked version to skip fetch, got %d", client.fetchCalls)
|
||||
}
|
||||
if len(manager.applyMainContents) != 0 {
|
||||
t.Fatal("expected blocked version to skip apply")
|
||||
}
|
||||
if len(client.reports) != 0 {
|
||||
t.Fatal("expected blocked version to skip reporting duplicate apply result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncOnStartupKeepsBlockedVersionSuppressedUntilNewTargetArrives(t *testing.T) {
|
||||
client := &fakeClient{
|
||||
config: protocol.ActiveConfigResponse{
|
||||
Version: "20260309-007",
|
||||
Checksum: "checksum-7",
|
||||
MainConfig: "worker_processes 7;",
|
||||
RouteConfig: "server { listen 87; }",
|
||||
RenderedConfig: "server { listen 87; }",
|
||||
CreatedAt: time.Now().Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
stateStore := state.NewStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
nodeID, err := stateStore.EnsureNodeID()
|
||||
if err != nil {
|
||||
t.Fatalf("EnsureNodeID failed: %v", err)
|
||||
}
|
||||
if err = stateStore.Save(&state.Snapshot{
|
||||
NodeID: nodeID,
|
||||
CurrentVersion: "20260309-005",
|
||||
CurrentChecksum: "checksum-5",
|
||||
BlockedVersion: "20260309-007",
|
||||
BlockedChecksum: "checksum-7",
|
||||
BlockedReason: "apply failed, rolled back to previous config",
|
||||
OpenrestyStatus: protocol.OpenrestyStatusUnhealthy,
|
||||
OpenrestyMessage: "apply failed, rolled back to previous config",
|
||||
LastError: "apply failed, rolled back to previous config",
|
||||
}); err != nil {
|
||||
t.Fatalf("failed to seed state: %v", err)
|
||||
}
|
||||
|
||||
manager := &fakeManager{currentChecksum: "checksum-5"}
|
||||
service := New(client, manager, stateStore)
|
||||
if err = service.SyncOnStartup(context.Background(), &protocol.ActiveConfigMeta{
|
||||
Version: "20260309-007",
|
||||
Checksum: "checksum-7",
|
||||
}); err != nil {
|
||||
t.Fatalf("expected blocked startup target to be skipped, got %v", err)
|
||||
}
|
||||
if len(manager.ensureCalls) != 1 || !manager.ensureCalls[0] {
|
||||
t.Fatal("expected startup skip to ensure runtime with current local config")
|
||||
}
|
||||
if client.fetchCalls != 0 {
|
||||
t.Fatalf("expected blocked startup target to skip fetch, got %d", client.fetchCalls)
|
||||
}
|
||||
if len(client.reports) != 0 {
|
||||
t.Fatal("expected blocked startup target to skip duplicate apply report")
|
||||
}
|
||||
snapshot, err := stateStore.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load state: %v", err)
|
||||
}
|
||||
if snapshot.BlockedVersion != "20260309-007" || snapshot.BlockedChecksum != "checksum-7" {
|
||||
t.Fatalf("expected blocked target to remain recorded, got %+v", snapshot)
|
||||
}
|
||||
if snapshot.OpenrestyStatus != protocol.OpenrestyStatusHealthy {
|
||||
t.Fatalf("expected startup runtime recovery to mark openresty healthy, got %q", snapshot.OpenrestyStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncOnceClearsBlockedTargetWhenNewVersionArrives(t *testing.T) {
|
||||
client := &fakeClient{
|
||||
config: protocol.ActiveConfigResponse{
|
||||
Version: "20260309-008",
|
||||
Checksum: "checksum-8",
|
||||
MainConfig: "worker_processes 8;",
|
||||
RouteConfig: "server { listen 88; }",
|
||||
RenderedConfig: "server { listen 88; }",
|
||||
CreatedAt: time.Now().Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
stateStore := state.NewStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
nodeID, err := stateStore.EnsureNodeID()
|
||||
if err != nil {
|
||||
t.Fatalf("EnsureNodeID failed: %v", err)
|
||||
}
|
||||
if err = stateStore.Save(&state.Snapshot{
|
||||
NodeID: nodeID,
|
||||
CurrentVersion: "20260309-005",
|
||||
CurrentChecksum: "checksum-5",
|
||||
BlockedVersion: "20260309-007",
|
||||
BlockedChecksum: "checksum-7",
|
||||
BlockedReason: "apply failed, rolled back to previous config",
|
||||
}); err != nil {
|
||||
t.Fatalf("failed to seed state: %v", err)
|
||||
}
|
||||
|
||||
manager := &fakeManager{}
|
||||
service := New(client, manager, stateStore)
|
||||
if err = service.SyncOnce(context.Background(), &protocol.ActiveConfigMeta{
|
||||
Version: "20260309-008",
|
||||
Checksum: "checksum-8",
|
||||
}); err != nil {
|
||||
t.Fatalf("expected new target version to be applied, got %v", err)
|
||||
}
|
||||
if client.fetchCalls != 1 {
|
||||
t.Fatalf("expected new target to trigger fetch, got %d", client.fetchCalls)
|
||||
}
|
||||
if len(manager.applyMainContents) != 1 {
|
||||
t.Fatal("expected new target to trigger apply")
|
||||
}
|
||||
snapshot, err := stateStore.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load state: %v", err)
|
||||
}
|
||||
if snapshot.BlockedVersion != "" || snapshot.BlockedChecksum != "" {
|
||||
t.Fatalf("expected blocked target to be cleared after new version succeeds, got %+v", snapshot)
|
||||
}
|
||||
if snapshot.CurrentVersion != "20260309-008" || snapshot.CurrentChecksum != "checksum-8" {
|
||||
t.Fatalf("expected current version to move to new target, got %+v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncOnceSkipsFetchWhenHeartbeatChecksumMatches(t *testing.T) {
|
||||
client := &fakeClient{
|
||||
config: protocol.ActiveConfigResponse{
|
||||
|
||||
@@ -60,16 +60,16 @@ var GeoIPProvider = "ipinfo"
|
||||
var OpenRestyWorkerProcesses = "auto"
|
||||
var OpenRestyWorkerConnections = 4096
|
||||
var OpenRestyWorkerRlimitNofile = 65535
|
||||
var OpenRestyEventsUse = ""
|
||||
var OpenRestyEventsMultiAcceptEnabled = false
|
||||
var OpenRestyKeepaliveTimeout = 65
|
||||
var OpenRestyEventsUse = "epoll"
|
||||
var OpenRestyEventsMultiAcceptEnabled = true
|
||||
var OpenRestyKeepaliveTimeout = 20
|
||||
var OpenRestyKeepaliveRequests = 1000
|
||||
var OpenRestyClientHeaderTimeout = 15
|
||||
var OpenRestyClientBodyTimeout = 15
|
||||
var OpenRestyClientMaxBodySize = "64m"
|
||||
var OpenRestyLargeClientHeaderBuffers = "4 16k"
|
||||
var OpenRestySendTimeout = 30
|
||||
var OpenRestyProxyConnectTimeout = 5
|
||||
var OpenRestyProxyConnectTimeout = 3
|
||||
var OpenRestyProxySendTimeout = 60
|
||||
var OpenRestyProxyReadTimeout = 60
|
||||
var OpenRestyWebsocketEnabled = true
|
||||
@@ -81,13 +81,12 @@ var OpenRestyProxyBusyBuffersSize = "64k"
|
||||
var OpenRestyGzipEnabled = true
|
||||
var OpenRestyGzipMinLength = 1024
|
||||
var OpenRestyGzipCompLevel = 5
|
||||
var OpenRestyResolvers = ""
|
||||
var OpenRestyCacheEnabled = false
|
||||
var OpenRestyCachePath = ""
|
||||
var OpenRestyCacheLevels = "1:2"
|
||||
var OpenRestyCacheInactive = "30m"
|
||||
var OpenRestyCacheMaxSize = "1g"
|
||||
var OpenRestyCacheKeyTemplate = "$scheme$proxy_host$request_uri"
|
||||
var OpenRestyCacheKeyTemplate = "$scheme$host$request_uri"
|
||||
var OpenRestyCacheLockEnabled = true
|
||||
var OpenRestyCacheLockTimeout = "5s"
|
||||
var OpenRestyCacheUseStale = "error timeout updating http_500 http_502 http_503 http_504"
|
||||
@@ -103,7 +102,7 @@ events {
|
||||
http {
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
log_format openflare_json escape=json '{"ts":"$time_iso8601","host":"$host","path":"$request_uri","remote_addr":"$remote_addr","status":$status,"request_time":$request_time,"bytes_sent":$body_bytes_sent,"request_length":$request_length}';
|
||||
{{OpenRestyConnectionUpgradeMap}}{{OpenRestyDefaultServerBlock}} log_format openflare_json escape=json '{"ts":"$time_iso8601","host":"$host","path":"$request_uri","remote_addr":"$remote_addr","status":$status,"request_time":$request_time,"bytes_sent":$body_bytes_sent,"request_length":$request_length}';
|
||||
access_log {{OpenRestyAccessLogPath}} openflare_json;
|
||||
sendfile on;
|
||||
tcp_nopush on;
|
||||
@@ -126,7 +125,7 @@ http {
|
||||
gzip {{OpenRestyGzip}};
|
||||
gzip_min_length {{OpenRestyGzipMinLength}};
|
||||
gzip_comp_level {{OpenRestyGzipCompLevel}};
|
||||
{{OpenRestyResolverDirective}}{{OpenRestyCacheBlock}} include {{OpenRestyRouteConfigInclude}};
|
||||
{{OpenRestyCacheBlock}} include {{OpenRestyRouteConfigInclude}};
|
||||
}
|
||||
`
|
||||
|
||||
|
||||
@@ -247,3 +247,27 @@ func GetNodeObservability(c *gin.Context) {
|
||||
}
|
||||
respondSuccess(c, view)
|
||||
}
|
||||
|
||||
// CleanupNodeHealthEvents godoc
|
||||
// @Summary Cleanup node health events
|
||||
// @Tags Nodes
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Node ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 400 {object} map[string]interface{}
|
||||
// @Router /api/nodes/{id}/observability/cleanup [post]
|
||||
func CleanupNodeHealthEvents(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
respondBadRequest(c, "")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := service.CleanupNodeHealthEvents(uint(id))
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccess(c, result)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net"
|
||||
"net/http"
|
||||
"openflare/common"
|
||||
"openflare/model"
|
||||
@@ -115,15 +114,7 @@ func validateOpenRestyOption(key string, value string) error {
|
||||
return fmt.Errorf("%s 仅支持 epoll、kqueue、poll、select、rtsig、/dev/poll、eventport 或留空", key)
|
||||
}
|
||||
case "OpenRestyResolvers":
|
||||
if trimmed == "" {
|
||||
return nil
|
||||
}
|
||||
for _, token := range splitOpenRestyResolvers(trimmed) {
|
||||
if net.ParseIP(token) == nil {
|
||||
return fmt.Errorf("%s only supports IP resolver entries, invalid value %q", key, token)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return fmt.Errorf("%s 已废弃,不再支持配置 resolver", key)
|
||||
case "OpenRestyEventsMultiAcceptEnabled",
|
||||
"OpenRestyWebsocketEnabled",
|
||||
"OpenRestyProxyRequestBufferingEnabled",
|
||||
@@ -187,12 +178,6 @@ func validateOpenRestyOption(key string, value string) error {
|
||||
}
|
||||
}
|
||||
|
||||
func splitOpenRestyResolvers(value string) []string {
|
||||
return strings.FieldsFunc(value, func(r rune) bool {
|
||||
return r == ',' || r == '\n' || r == '\r' || r == '\t' || r == ' '
|
||||
})
|
||||
}
|
||||
|
||||
// GetOptions godoc
|
||||
// @Summary List editable options
|
||||
// @Tags Options
|
||||
|
||||
@@ -14,6 +14,7 @@ func TestValidateOpenRestyOption(t *testing.T) {
|
||||
{name: "worker processes invalid", key: "OpenRestyWorkerProcesses", value: "0", wantErr: true},
|
||||
{name: "events use empty", key: "OpenRestyEventsUse", value: ""},
|
||||
{name: "events use invalid", key: "OpenRestyEventsUse", value: "io_uring", wantErr: true},
|
||||
{name: "resolvers deprecated", key: "OpenRestyResolvers", value: "1.1.1.1", wantErr: true},
|
||||
{name: "proxy buffers valid", key: "OpenRestyProxyBuffers", value: "16 16k"},
|
||||
{name: "proxy buffers invalid", key: "OpenRestyProxyBuffers", value: "16x16k", wantErr: true},
|
||||
{name: "cache max size valid", key: "OpenRestyCacheMaxSize", value: "2g"},
|
||||
@@ -32,9 +33,6 @@ func TestValidateOpenRestyOption(t *testing.T) {
|
||||
{name: "cache use stale invalid", key: "OpenRestyCacheUseStale", value: "error whatever", wantErr: true},
|
||||
{name: "gzip level valid", key: "OpenRestyGzipCompLevel", value: "9"},
|
||||
{name: "gzip level invalid", key: "OpenRestyGzipCompLevel", value: "10", wantErr: true},
|
||||
{name: "resolvers empty", key: "OpenRestyResolvers", value: ""},
|
||||
{name: "resolvers valid", key: "OpenRestyResolvers", value: "1.1.1.1, 8.8.8.8"},
|
||||
{name: "resolvers invalid", key: "OpenRestyResolvers", value: "dns.internal", wantErr: true},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
|
||||
+1150
-180
File diff suppressed because it is too large
Load Diff
+1149
-181
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,12 @@
|
||||
basePath: /
|
||||
definitions:
|
||||
controller.geoIPLookupRequest:
|
||||
properties:
|
||||
ip:
|
||||
type: string
|
||||
provider:
|
||||
type: string
|
||||
type: object
|
||||
model.Option:
|
||||
properties:
|
||||
key:
|
||||
@@ -7,12 +14,94 @@ definitions:
|
||||
value:
|
||||
type: string
|
||||
type: object
|
||||
service.AgentBufferedObservabilityRecord:
|
||||
properties:
|
||||
access_logs:
|
||||
items:
|
||||
$ref: '#/definitions/service.AgentNodeAccessLog'
|
||||
type: array
|
||||
snapshot:
|
||||
$ref: '#/definitions/service.AgentNodeMetricSnapshot'
|
||||
traffic_report:
|
||||
$ref: '#/definitions/service.AgentNodeTrafficReport'
|
||||
window_started_at_unix:
|
||||
type: integer
|
||||
type: object
|
||||
service.AgentNodeAccessLog:
|
||||
properties:
|
||||
host:
|
||||
type: string
|
||||
logged_at_unix:
|
||||
type: integer
|
||||
path:
|
||||
type: string
|
||||
remote_addr:
|
||||
type: string
|
||||
status_code:
|
||||
type: integer
|
||||
type: object
|
||||
service.AgentNodeHealthEvent:
|
||||
properties:
|
||||
event_type:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
metadata:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
severity:
|
||||
type: string
|
||||
triggered_at_unix:
|
||||
type: integer
|
||||
type: object
|
||||
service.AgentNodeMetricSnapshot:
|
||||
properties:
|
||||
captured_at_unix:
|
||||
type: integer
|
||||
cpu_usage_percent:
|
||||
type: number
|
||||
disk_read_bytes:
|
||||
type: integer
|
||||
disk_write_bytes:
|
||||
type: integer
|
||||
memory_total_bytes:
|
||||
type: integer
|
||||
memory_used_bytes:
|
||||
type: integer
|
||||
network_rx_bytes:
|
||||
type: integer
|
||||
network_tx_bytes:
|
||||
type: integer
|
||||
openresty_connections:
|
||||
type: integer
|
||||
openresty_rx_bytes:
|
||||
type: integer
|
||||
openresty_tx_bytes:
|
||||
type: integer
|
||||
storage_total_bytes:
|
||||
type: integer
|
||||
storage_used_bytes:
|
||||
type: integer
|
||||
type: object
|
||||
service.AgentNodePayload:
|
||||
properties:
|
||||
access_logs:
|
||||
items:
|
||||
$ref: '#/definitions/service.AgentNodeAccessLog'
|
||||
type: array
|
||||
agent_version:
|
||||
type: string
|
||||
buffered_observability:
|
||||
items:
|
||||
$ref: '#/definitions/service.AgentBufferedObservabilityRecord'
|
||||
type: array
|
||||
current_version:
|
||||
type: string
|
||||
health_events:
|
||||
items:
|
||||
$ref: '#/definitions/service.AgentNodeHealthEvent'
|
||||
type: array
|
||||
ip:
|
||||
type: string
|
||||
last_error:
|
||||
@@ -27,15 +116,82 @@ definitions:
|
||||
type: string
|
||||
openresty_status:
|
||||
type: string
|
||||
profile:
|
||||
$ref: '#/definitions/service.AgentNodeSystemProfile'
|
||||
snapshot:
|
||||
$ref: '#/definitions/service.AgentNodeMetricSnapshot'
|
||||
traffic_report:
|
||||
$ref: '#/definitions/service.AgentNodeTrafficReport'
|
||||
type: object
|
||||
service.AgentNodeSystemProfile:
|
||||
properties:
|
||||
architecture:
|
||||
type: string
|
||||
cpu_cores:
|
||||
type: integer
|
||||
cpu_model:
|
||||
type: string
|
||||
hostname:
|
||||
type: string
|
||||
kernel_version:
|
||||
type: string
|
||||
os_name:
|
||||
type: string
|
||||
os_version:
|
||||
type: string
|
||||
reported_at_unix:
|
||||
type: integer
|
||||
total_disk_bytes:
|
||||
type: integer
|
||||
total_memory_bytes:
|
||||
type: integer
|
||||
uptime_seconds:
|
||||
type: integer
|
||||
type: object
|
||||
service.AgentNodeTrafficReport:
|
||||
properties:
|
||||
error_count:
|
||||
type: integer
|
||||
request_count:
|
||||
type: integer
|
||||
source_countries:
|
||||
additionalProperties:
|
||||
format: int64
|
||||
type: integer
|
||||
type: object
|
||||
status_codes:
|
||||
additionalProperties:
|
||||
format: int64
|
||||
type: integer
|
||||
type: object
|
||||
top_domains:
|
||||
additionalProperties:
|
||||
format: int64
|
||||
type: integer
|
||||
type: object
|
||||
unique_visitor_count:
|
||||
type: integer
|
||||
window_ended_at_unix:
|
||||
type: integer
|
||||
window_started_at_unix:
|
||||
type: integer
|
||||
type: object
|
||||
service.ApplyLogPayload:
|
||||
properties:
|
||||
checksum:
|
||||
type: string
|
||||
main_config_checksum:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
node_id:
|
||||
type: string
|
||||
result:
|
||||
type: string
|
||||
route_config_checksum:
|
||||
type: string
|
||||
support_file_count:
|
||||
type: integer
|
||||
version:
|
||||
type: string
|
||||
type: object
|
||||
@@ -54,6 +210,16 @@ definitions:
|
||||
properties:
|
||||
auto_update_enabled:
|
||||
type: boolean
|
||||
geo_latitude:
|
||||
type: number
|
||||
geo_longitude:
|
||||
type: number
|
||||
geo_manual_override:
|
||||
type: boolean
|
||||
geo_name:
|
||||
type: string
|
||||
ip:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
type: object
|
||||
@@ -66,6 +232,14 @@ definitions:
|
||||
type: object
|
||||
service.ProxyRouteInput:
|
||||
properties:
|
||||
cache_enabled:
|
||||
type: boolean
|
||||
cache_policy:
|
||||
type: string
|
||||
cache_rules:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
cert_id:
|
||||
type: integer
|
||||
custom_headers:
|
||||
@@ -78,14 +252,18 @@ definitions:
|
||||
type: boolean
|
||||
enabled:
|
||||
type: boolean
|
||||
origin_url:
|
||||
type: string
|
||||
origin_host:
|
||||
type: string
|
||||
origin_url:
|
||||
type: string
|
||||
redirect_http:
|
||||
type: boolean
|
||||
remark:
|
||||
type: string
|
||||
upstreams:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
type: object
|
||||
service.TLSCertificateInput:
|
||||
properties:
|
||||
@@ -104,6 +282,204 @@ info:
|
||||
title: OpenFlare Server API
|
||||
version: "3.0"
|
||||
paths:
|
||||
/api/access-logs/:
|
||||
get:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: query
|
||||
name: node_id
|
||||
type: string
|
||||
- description: Remote address
|
||||
in: query
|
||||
name: remote_addr
|
||||
type: string
|
||||
- description: Host
|
||||
in: query
|
||||
name: host
|
||||
type: string
|
||||
- description: Path
|
||||
in: query
|
||||
name: path
|
||||
type: string
|
||||
- description: Page index
|
||||
in: query
|
||||
name: p
|
||||
type: integer
|
||||
- description: Page size
|
||||
in: query
|
||||
name: page_size
|
||||
type: integer
|
||||
- description: Sort by
|
||||
in: query
|
||||
name: sort_by
|
||||
type: string
|
||||
- description: Sort order
|
||||
in: query
|
||||
name: sort_order
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: List access logs
|
||||
tags:
|
||||
- AccessLogs
|
||||
/api/access-logs/cleanup:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Cleanup access logs by retention days
|
||||
tags:
|
||||
- AccessLogs
|
||||
/api/access-logs/folds:
|
||||
get:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: query
|
||||
name: node_id
|
||||
type: string
|
||||
- description: Remote address
|
||||
in: query
|
||||
name: remote_addr
|
||||
type: string
|
||||
- description: Host
|
||||
in: query
|
||||
name: host
|
||||
type: string
|
||||
- description: Path
|
||||
in: query
|
||||
name: path
|
||||
type: string
|
||||
- description: Page index
|
||||
in: query
|
||||
name: p
|
||||
type: integer
|
||||
- description: Page size
|
||||
in: query
|
||||
name: page_size
|
||||
type: integer
|
||||
- description: Sort by
|
||||
in: query
|
||||
name: sort_by
|
||||
type: string
|
||||
- description: Sort order
|
||||
in: query
|
||||
name: sort_order
|
||||
type: string
|
||||
- description: Fold minutes
|
||||
in: query
|
||||
name: fold_minutes
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: List folded access logs
|
||||
tags:
|
||||
- AccessLogs
|
||||
/api/access-logs/ip-summary:
|
||||
get:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: query
|
||||
name: node_id
|
||||
type: string
|
||||
- description: Remote address
|
||||
in: query
|
||||
name: remote_addr
|
||||
type: string
|
||||
- description: Host
|
||||
in: query
|
||||
name: host
|
||||
type: string
|
||||
- description: Page index
|
||||
in: query
|
||||
name: p
|
||||
type: integer
|
||||
- description: Page size
|
||||
in: query
|
||||
name: page_size
|
||||
type: integer
|
||||
- description: Sort by
|
||||
in: query
|
||||
name: sort_by
|
||||
type: string
|
||||
- description: Sort order
|
||||
in: query
|
||||
name: sort_order
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: List access log IP summaries
|
||||
tags:
|
||||
- AccessLogs
|
||||
/api/access-logs/ip-summary/trend:
|
||||
get:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: query
|
||||
name: node_id
|
||||
type: string
|
||||
- description: Remote address
|
||||
in: query
|
||||
name: remote_addr
|
||||
required: true
|
||||
type: string
|
||||
- description: Host
|
||||
in: query
|
||||
name: host
|
||||
type: string
|
||||
- description: Hours
|
||||
in: query
|
||||
name: hours
|
||||
type: integer
|
||||
- description: Bucket minutes
|
||||
in: query
|
||||
name: bucket_minutes
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get access log IP trend
|
||||
tags:
|
||||
- AccessLogs
|
||||
/api/agent/apply-logs:
|
||||
post:
|
||||
consumes:
|
||||
@@ -226,6 +602,23 @@ paths:
|
||||
summary: List apply logs
|
||||
tags:
|
||||
- ApplyLogs
|
||||
/api/apply-logs/cleanup:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Cleanup apply logs
|
||||
tags:
|
||||
- ApplyLogs
|
||||
/api/config-versions/:
|
||||
get:
|
||||
produces:
|
||||
@@ -241,8 +634,34 @@ paths:
|
||||
summary: List config versions
|
||||
tags:
|
||||
- ConfigVersions
|
||||
/api/config-versions/{id}:
|
||||
get:
|
||||
parameters:
|
||||
- description: Version ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get config version detail
|
||||
tags:
|
||||
- ConfigVersions
|
||||
/api/config-versions/{id}/activate:
|
||||
put:
|
||||
post:
|
||||
parameters:
|
||||
- description: Version ID
|
||||
in: path
|
||||
@@ -327,6 +746,26 @@ paths:
|
||||
summary: Publish a new config version
|
||||
tags:
|
||||
- ConfigVersions
|
||||
/api/dashboard/overview:
|
||||
get:
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get dashboard overview
|
||||
tags:
|
||||
- Dashboard
|
||||
/api/managed-domains/:
|
||||
get:
|
||||
produces:
|
||||
@@ -370,8 +809,8 @@ paths:
|
||||
summary: Create managed domain
|
||||
tags:
|
||||
- ManagedDomains
|
||||
/api/managed-domains/{id}:
|
||||
delete:
|
||||
/api/managed-domains/{id}/delete:
|
||||
post:
|
||||
parameters:
|
||||
- description: Managed domain ID
|
||||
in: path
|
||||
@@ -396,7 +835,8 @@ paths:
|
||||
summary: Delete managed domain
|
||||
tags:
|
||||
- ManagedDomains
|
||||
put:
|
||||
/api/managed-domains/{id}/update:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
@@ -493,65 +933,6 @@ paths:
|
||||
summary: Create node
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}:
|
||||
delete:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Delete node
|
||||
tags:
|
||||
- Nodes
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Node payload
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/service.NodeInput'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Update node
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}/agent-release:
|
||||
get:
|
||||
parameters:
|
||||
@@ -608,6 +989,92 @@ paths:
|
||||
summary: Request agent self-update on node
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}/delete:
|
||||
post:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Delete node
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}/observability:
|
||||
get:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Lookback window in hours
|
||||
in: query
|
||||
name: hours
|
||||
type: integer
|
||||
- description: Max records per section
|
||||
in: query
|
||||
name: limit
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get node observability details
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}/observability/cleanup:
|
||||
post:
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Cleanup node health events
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}/openresty-restart:
|
||||
post:
|
||||
parameters:
|
||||
@@ -634,6 +1101,40 @@ paths:
|
||||
summary: Request openresty restart on node
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/{id}/update:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Node ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Node payload
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/service.NodeInput'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Update node
|
||||
tags:
|
||||
- Nodes
|
||||
/api/nodes/bootstrap-token:
|
||||
get:
|
||||
produces:
|
||||
@@ -677,7 +1178,35 @@ paths:
|
||||
summary: List editable options
|
||||
tags:
|
||||
- Options
|
||||
put:
|
||||
/api/option/geoip/lookup:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: GeoIP lookup payload
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/controller.geoIPLookupRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
summary: Test GeoIP lookup
|
||||
tags:
|
||||
- Options
|
||||
/api/option/update:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
@@ -746,8 +1275,8 @@ paths:
|
||||
summary: Create proxy route
|
||||
tags:
|
||||
- ProxyRoutes
|
||||
/api/proxy-routes/{id}:
|
||||
delete:
|
||||
/api/proxy-routes/{id}/delete:
|
||||
post:
|
||||
parameters:
|
||||
- description: Route ID
|
||||
in: path
|
||||
@@ -772,7 +1301,8 @@ paths:
|
||||
summary: Delete proxy route
|
||||
tags:
|
||||
- ProxyRoutes
|
||||
put:
|
||||
/api/proxy-routes/{id}/update:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
@@ -862,7 +1392,59 @@ paths:
|
||||
tags:
|
||||
- TLSCertificates
|
||||
/api/tls-certificates/{id}:
|
||||
delete:
|
||||
get:
|
||||
parameters:
|
||||
- description: Certificate ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get TLS certificate detail
|
||||
tags:
|
||||
- TLSCertificates
|
||||
/api/tls-certificates/{id}/content:
|
||||
get:
|
||||
parameters:
|
||||
- description: Certificate ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get TLS certificate PEM content
|
||||
tags:
|
||||
- TLSCertificates
|
||||
/api/tls-certificates/{id}/delete:
|
||||
post:
|
||||
parameters:
|
||||
- description: Certificate ID
|
||||
in: path
|
||||
@@ -887,6 +1469,40 @@ paths:
|
||||
summary: Delete TLS certificate
|
||||
tags:
|
||||
- TLSCertificates
|
||||
/api/tls-certificates/{id}/update:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Certificate ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: TLS certificate payload
|
||||
in: body
|
||||
name: payload
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/service.TLSCertificateInput'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Update TLS certificate from PEM
|
||||
tags:
|
||||
- TLSCertificates
|
||||
/api/tls-certificates/import-file:
|
||||
post:
|
||||
consumes:
|
||||
@@ -942,6 +1558,12 @@ paths:
|
||||
summary: Get latest GitHub release
|
||||
tags:
|
||||
- Update
|
||||
/api/update/logs/ws:
|
||||
get:
|
||||
responses: {}
|
||||
summary: Stream server upgrade logs over websocket
|
||||
tags:
|
||||
- Update
|
||||
/api/update/manual-upgrade:
|
||||
post:
|
||||
consumes:
|
||||
|
||||
@@ -16,7 +16,7 @@ require (
|
||||
github.com/oschwald/maxminddb-golang v1.13.1
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.8.12
|
||||
github.com/swaggo/swag v1.16.4
|
||||
golang.org/x/crypto v0.45.0
|
||||
golang.org/x/net v0.47.0
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
|
||||
@@ -174,8 +174,8 @@ github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
|
||||
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
|
||||
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
|
||||
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||
github.com/swaggo/swag v1.8.12 h1:pctzkNPu0AlQP2royqX3apjKCQonAnf7KGoxeO4y64w=
|
||||
github.com/swaggo/swag v1.8.12/go.mod h1:lNfm6Gg+oAq3zRJQNEMBE66LIJKM44mxFqhEEgy2its=
|
||||
github.com/swaggo/swag v1.16.4 h1:clWJtd9LStiG3VeijiCfOVODP6VpHtKdQy9ELFG3s1A=
|
||||
github.com/swaggo/swag v1.16.4/go.mod h1:VBsHJRsDvfYvqoiMKnsdwhNV9LEMHgEDZcyVYX0sxPg=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
|
||||
@@ -17,7 +17,7 @@ type ApplyLog struct {
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
Version string `json:"version" gorm:"size:32;not null"`
|
||||
Result string `json:"result" gorm:"size:32;not null"`
|
||||
Message string `json:"message" gorm:"size:1024"`
|
||||
Message string `json:"message" gorm:"type:text"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null;default:''"`
|
||||
MainConfigChecksum string `json:"main_config_checksum" gorm:"size:64;not null;default:''"`
|
||||
RouteConfigChecksum string `json:"route_config_checksum" gorm:"size:64;not null;default:''"`
|
||||
|
||||
@@ -126,6 +126,33 @@ func autoMigrateAll(db *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateTextColumns(db *gorm.DB, backend string) error {
|
||||
if backend != "postgres" {
|
||||
return nil
|
||||
}
|
||||
type textColumn struct {
|
||||
model any
|
||||
table string
|
||||
column string
|
||||
}
|
||||
columns := []textColumn{
|
||||
{model: &Node{}, table: "nodes", column: "openresty_message"},
|
||||
{model: &Node{}, table: "nodes", column: "last_error"},
|
||||
{model: &ApplyLog{}, table: "apply_logs", column: "message"},
|
||||
{model: &NodeHealthEvent{}, table: "node_health_events", column: "message"},
|
||||
}
|
||||
for _, item := range columns {
|
||||
if !db.Migrator().HasTable(item.model) || !db.Migrator().HasColumn(item.model, item.column) {
|
||||
continue
|
||||
}
|
||||
sql := fmt.Sprintf(`ALTER TABLE "%s" ALTER COLUMN "%s" TYPE text`, item.table, item.column)
|
||||
if err := db.Exec(sql).Error; err != nil {
|
||||
return fmt.Errorf("migrate column %s.%s to text failed: %w", item.table, item.column, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isDatabaseEmpty(db *gorm.DB) (bool, error) {
|
||||
for _, item := range registeredModels() {
|
||||
var count int64
|
||||
@@ -272,6 +299,9 @@ func InitDB() (err error) {
|
||||
if err = autoMigrateAll(db); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = migrateTextColumns(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = migrateSQLiteDataIfNeeded(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -20,11 +20,11 @@ type Node struct {
|
||||
AgentVersion string `json:"agent_version" gorm:"size:64;not null"`
|
||||
NginxVersion string `json:"nginx_version" gorm:"size:64"`
|
||||
OpenrestyStatus string `json:"openresty_status" gorm:"size:16;not null;default:'unknown'"`
|
||||
OpenrestyMessage string `json:"openresty_message" gorm:"size:2048"`
|
||||
OpenrestyMessage string `json:"openresty_message" gorm:"type:text"`
|
||||
Status string `json:"status" gorm:"size:16;not null;default:'offline'"`
|
||||
CurrentVersion string `json:"current_version" gorm:"size:32"`
|
||||
LastSeenAt time.Time `json:"last_seen_at"`
|
||||
LastError string `json:"last_error" gorm:"size:1024"`
|
||||
LastError string `json:"last_error" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ type NodeHealthEvent struct {
|
||||
EventType string `json:"event_type" gorm:"index;size:64;not null"`
|
||||
Severity string `json:"severity" gorm:"size:16;not null"`
|
||||
Status string `json:"status" gorm:"index;size:16;not null"`
|
||||
Message string `json:"message" gorm:"size:2048"`
|
||||
Message string `json:"message" gorm:"type:text"`
|
||||
FirstTriggeredAt time.Time `json:"first_triggered_at" gorm:"index"`
|
||||
LastTriggeredAt time.Time `json:"last_triggered_at" gorm:"index"`
|
||||
ReportedAt time.Time `json:"reported_at" gorm:"index"`
|
||||
@@ -40,3 +40,8 @@ func ListActiveNodeHealthEvents() (events []*NodeHealthEvent, err error) {
|
||||
err = DB.Where("status = ?", "active").Order("last_triggered_at desc").Find(&events).Error
|
||||
return events, err
|
||||
}
|
||||
|
||||
func DeleteNodeHealthEvents(nodeID string) (deleted int64, err error) {
|
||||
result := DB.Where("node_id = ?", nodeID).Delete(&NodeHealthEvent{})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
@@ -80,7 +80,6 @@ func InitOptionMap() {
|
||||
common.OptionMap["OpenRestyGzipEnabled"] = strconv.FormatBool(common.OpenRestyGzipEnabled)
|
||||
common.OptionMap["OpenRestyGzipMinLength"] = strconv.Itoa(common.OpenRestyGzipMinLength)
|
||||
common.OptionMap["OpenRestyGzipCompLevel"] = strconv.Itoa(common.OpenRestyGzipCompLevel)
|
||||
common.OptionMap["OpenRestyResolvers"] = common.OpenRestyResolvers
|
||||
common.OptionMap["OpenRestyCacheEnabled"] = strconv.FormatBool(common.OpenRestyCacheEnabled)
|
||||
common.OptionMap["OpenRestyCachePath"] = common.OpenRestyCachePath
|
||||
common.OptionMap["OpenRestyCacheLevels"] = common.OpenRestyCacheLevels
|
||||
@@ -132,6 +131,11 @@ func updateOptionMap(key string, value string) {
|
||||
common.OptionMap = make(map[string]string)
|
||||
}
|
||||
common.OptionMap[key] = value
|
||||
if key == "OpenRestyResolvers" {
|
||||
delete(common.OptionMap, key)
|
||||
common.OptionMapRWMutex.Unlock()
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(key, "Permission") {
|
||||
intValue, _ := strconv.Atoi(value)
|
||||
switch key {
|
||||
@@ -299,8 +303,6 @@ func updateOptionMap(key string, value string) {
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.OpenRestyGzipCompLevel = v
|
||||
}
|
||||
case "OpenRestyResolvers":
|
||||
common.OpenRestyResolvers = strings.TrimSpace(value)
|
||||
case "OpenRestyCacheEnabled":
|
||||
common.OpenRestyCacheEnabled = value == "true"
|
||||
case "OpenRestyCachePath":
|
||||
|
||||
@@ -7,10 +7,14 @@ type ProxyRoute struct {
|
||||
Domain string `json:"domain" gorm:"uniqueIndex;size:255;not null"`
|
||||
OriginURL string `json:"origin_url" gorm:"size:2048;not null"`
|
||||
OriginHost string `json:"origin_host" gorm:"size:255"`
|
||||
Upstreams string `json:"upstreams" gorm:"type:text;not null;default:'[]'"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
EnableHTTPS bool `json:"enable_https" gorm:"column:enable_https;not null;default:false"`
|
||||
CertID *uint `json:"cert_id"`
|
||||
RedirectHTTP bool `json:"redirect_http" gorm:"not null;default:false"`
|
||||
CacheEnabled bool `json:"cache_enabled" gorm:"not null;default:false"`
|
||||
CachePolicy string `json:"cache_policy" gorm:"size:32;not null;default:''"`
|
||||
CacheRules string `json:"cache_rules" gorm:"type:text;not null;default:'[]'"`
|
||||
CustomHeaders string `json:"custom_headers" gorm:"type:text;not null;default:'[]'"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
@@ -42,10 +46,14 @@ func (route *ProxyRoute) Update() error {
|
||||
"domain": route.Domain,
|
||||
"origin_url": route.OriginURL,
|
||||
"origin_host": route.OriginHost,
|
||||
"upstreams": route.Upstreams,
|
||||
"enabled": route.Enabled,
|
||||
"enable_https": route.EnableHTTPS,
|
||||
"cert_id": route.CertID,
|
||||
"redirect_http": route.RedirectHTTP,
|
||||
"cache_enabled": route.CacheEnabled,
|
||||
"cache_policy": route.CachePolicy,
|
||||
"cache_rules": route.CacheRules,
|
||||
"custom_headers": route.CustomHeaders,
|
||||
"remark": route.Remark,
|
||||
}).Error
|
||||
|
||||
@@ -126,6 +126,7 @@ func SetApiRouter(router *gin.Engine) {
|
||||
nodeRoute.POST("/", controller.CreateNode)
|
||||
nodeRoute.GET("/:id/agent-release", controller.GetNodeAgentRelease)
|
||||
nodeRoute.GET("/:id/observability", controller.GetNodeObservability)
|
||||
nodeRoute.POST("/:id/observability/cleanup", controller.CleanupNodeHealthEvents)
|
||||
nodeRoute.POST("/:id/agent-update", controller.RequestNodeAgentUpdate)
|
||||
nodeRoute.POST("/:id/openresty-restart", controller.RequestNodeOpenrestyRestart)
|
||||
nodeRoute.POST("/:id/update", controller.UpdateNode)
|
||||
|
||||
@@ -44,11 +44,15 @@ func TestPhase1PublishLifecycle(t *testing.T) {
|
||||
token := prepareRootToken(t)
|
||||
|
||||
createBody := map[string]any{
|
||||
"domain": "app.example.com",
|
||||
"origin_url": "https://origin-a.internal",
|
||||
"origin_host": "origin-a.internal",
|
||||
"enabled": true,
|
||||
"remark": "primary route",
|
||||
"domain": "app.example.com",
|
||||
"origin_url": "https://10.0.0.11:8443",
|
||||
"upstreams": []string{"https://10.0.0.12:8443"},
|
||||
"origin_host": "origin-a.internal",
|
||||
"enabled": true,
|
||||
"cache_enabled": true,
|
||||
"cache_policy": "path_prefix",
|
||||
"cache_rules": []string{"/assets", "/static"},
|
||||
"remark": "primary route",
|
||||
}
|
||||
resp := performJSONRequest(t, engine, token, http.MethodPost, "/api/proxy-routes/", createBody)
|
||||
var createdRoute model.ProxyRoute
|
||||
@@ -59,6 +63,15 @@ func TestPhase1PublishLifecycle(t *testing.T) {
|
||||
if createdRoute.OriginHost != "origin-a.internal" {
|
||||
t.Fatalf("unexpected created route origin host: %s", createdRoute.OriginHost)
|
||||
}
|
||||
if !createdRoute.CacheEnabled || createdRoute.CachePolicy != "path_prefix" {
|
||||
t.Fatalf("expected route cache settings to persist, got %+v", createdRoute)
|
||||
}
|
||||
if !strings.Contains(createdRoute.Upstreams, "10.0.0.12:8443") {
|
||||
t.Fatalf("expected route upstream list to persist, got %s", createdRoute.Upstreams)
|
||||
}
|
||||
if !strings.Contains(createdRoute.CacheRules, "/assets") {
|
||||
t.Fatalf("expected route cache rules to persist, got %s", createdRoute.CacheRules)
|
||||
}
|
||||
|
||||
resp = performJSONRequest(t, engine, token, http.MethodGet, "/api/proxy-routes/", nil)
|
||||
var routes []model.ProxyRoute
|
||||
@@ -103,21 +116,31 @@ func TestPhase1PublishLifecycle(t *testing.T) {
|
||||
initialRendered := version1.RenderedConfig
|
||||
|
||||
updateBody := map[string]any{
|
||||
"domain": "app.example.com",
|
||||
"origin_url": "https://origin-b.internal",
|
||||
"origin_host": "origin-b.internal",
|
||||
"enabled": true,
|
||||
"remark": "updated route",
|
||||
"domain": "app.example.com",
|
||||
"origin_url": "https://10.0.0.21:8443",
|
||||
"upstreams": []string{"https://10.0.0.22:8443"},
|
||||
"origin_host": "origin-b.internal",
|
||||
"enabled": true,
|
||||
"cache_enabled": true,
|
||||
"cache_policy": "path_exact",
|
||||
"cache_rules": []string{"/robots.txt"},
|
||||
"remark": "updated route",
|
||||
}
|
||||
routePath := "/api/proxy-routes/" + toString(createdRoute.ID)
|
||||
resp = performJSONRequest(t, engine, token, http.MethodPost, routePath+"/update", updateBody)
|
||||
decodeResponseData(t, resp, &createdRoute)
|
||||
if createdRoute.OriginURL != "https://origin-b.internal" {
|
||||
if createdRoute.OriginURL != "https://10.0.0.21:8443" {
|
||||
t.Fatalf("unexpected updated route origin: %s", createdRoute.OriginURL)
|
||||
}
|
||||
if createdRoute.OriginHost != "origin-b.internal" {
|
||||
t.Fatalf("unexpected updated route origin host: %s", createdRoute.OriginHost)
|
||||
}
|
||||
if createdRoute.CachePolicy != "path_exact" || !strings.Contains(createdRoute.CacheRules, "/robots.txt") {
|
||||
t.Fatalf("expected updated route cache rules to persist, got %+v", createdRoute)
|
||||
}
|
||||
if !strings.Contains(createdRoute.Upstreams, "10.0.0.22:8443") {
|
||||
t.Fatalf("expected updated route upstream list to persist, got %s", createdRoute.Upstreams)
|
||||
}
|
||||
|
||||
resp = performJSONRequest(t, engine, token, http.MethodPost, "/api/config-versions/publish", nil)
|
||||
var version2 model.ConfigVersion
|
||||
@@ -326,8 +349,11 @@ func TestPhase1HTTPSAndCertificateImportLifecycle(t *testing.T) {
|
||||
if !strings.Contains(version.MainConfig, "include __OPENFLARE_ROUTE_CONFIG__;") {
|
||||
t.Fatal("expected active config to render managed main config")
|
||||
}
|
||||
if !strings.Contains(version.RenderedConfig, "listen 443 ssl http2;") {
|
||||
t.Fatal("expected active config to render https listener with http2 enabled")
|
||||
if !strings.Contains(version.RenderedConfig, "listen 443 ssl;") {
|
||||
t.Fatal("expected active config to render https ssl listener")
|
||||
}
|
||||
if !strings.Contains(version.RenderedConfig, "http2 on;") {
|
||||
t.Fatal("expected active config to render dedicated http2 directive")
|
||||
}
|
||||
if !strings.Contains(version.RenderedConfig, "return 301 https://$host$request_uri;") {
|
||||
t.Fatal("expected active config to render redirect server")
|
||||
|
||||
@@ -281,12 +281,41 @@ func TestPhase2AgentLifecycle(t *testing.T) {
|
||||
t.Fatal("expected node list to expose openresty message")
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&model.NodeHealthEvent{
|
||||
NodeID: createdNode.NodeID,
|
||||
EventType: "openresty_down",
|
||||
Severity: service.NodeHealthSeverityCritical,
|
||||
Status: service.NodeHealthEventStatusActive,
|
||||
Message: "docker run openresty failed: bind 80 already allocated",
|
||||
FirstTriggeredAt: time.Now().Add(-2 * time.Minute),
|
||||
LastTriggeredAt: time.Now().Add(-time.Minute),
|
||||
ReportedAt: time.Now().Add(-time.Minute),
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("failed to insert node health event: %v", err)
|
||||
}
|
||||
|
||||
observabilityResp := performJSONRequest(t, engine, adminToken, http.MethodGet, "/api/nodes/"+toString(createdNode.ID)+"/observability?hours=24&limit=20", nil)
|
||||
var observability service.NodeObservabilityView
|
||||
decodeResponseData(t, observabilityResp, &observability)
|
||||
if observability.NodeID != createdNode.NodeID {
|
||||
t.Fatalf("expected observability response for node %s, got %s", createdNode.NodeID, observability.NodeID)
|
||||
}
|
||||
if len(observability.HealthEvents) != 1 {
|
||||
t.Fatalf("expected observability response to include health events, got %+v", observability.HealthEvents)
|
||||
}
|
||||
|
||||
cleanupHealthResp := performJSONRequest(t, engine, adminToken, http.MethodPost, "/api/nodes/"+toString(createdNode.ID)+"/observability/cleanup", nil)
|
||||
var cleanupHealthResult service.NodeHealthEventCleanupResult
|
||||
decodeResponseData(t, cleanupHealthResp, &cleanupHealthResult)
|
||||
if cleanupHealthResult.NodeID != createdNode.NodeID || cleanupHealthResult.DeletedCount != 1 {
|
||||
t.Fatalf("unexpected node health cleanup result: %+v", cleanupHealthResult)
|
||||
}
|
||||
|
||||
observabilityAfterCleanupResp := performJSONRequest(t, engine, adminToken, http.MethodGet, "/api/nodes/"+toString(createdNode.ID)+"/observability?hours=24&limit=20", nil)
|
||||
decodeResponseData(t, observabilityAfterCleanupResp, &observability)
|
||||
if len(observability.HealthEvents) != 0 {
|
||||
t.Fatalf("expected health events to be cleaned up, got %+v", observability.HealthEvents)
|
||||
}
|
||||
|
||||
restartResp := performJSONRequest(t, engine, adminToken, http.MethodPost, "/api/nodes/"+toString(createdNode.ID)+"/openresty-restart", nil)
|
||||
decodeResponseData(t, restartResp, &createdNode)
|
||||
|
||||
@@ -254,6 +254,7 @@ func ReportApplyLog(payload ApplyLogPayload) (*model.ApplyLog, error) {
|
||||
payload.Checksum = strings.TrimSpace(payload.Checksum)
|
||||
payload.MainConfigChecksum = strings.TrimSpace(payload.MainConfigChecksum)
|
||||
payload.RouteConfigChecksum = strings.TrimSpace(payload.RouteConfigChecksum)
|
||||
payload.Message = truncateForDatabase(payload.Message, 16000)
|
||||
if payload.NodeID == "" {
|
||||
return nil, errors.New("node_id 不能为空")
|
||||
}
|
||||
@@ -339,6 +340,17 @@ func ListNodeViews() ([]*NodeView, error) {
|
||||
return views, nil
|
||||
}
|
||||
|
||||
func truncateForDatabase(value string, max int) string {
|
||||
if max <= 0 {
|
||||
return ""
|
||||
}
|
||||
runes := []rune(strings.TrimSpace(value))
|
||||
if len(runes) <= max {
|
||||
return string(runes)
|
||||
}
|
||||
return string(runes[:max])
|
||||
}
|
||||
|
||||
const (
|
||||
defaultApplyLogPageSize = 20
|
||||
maxApplyLogPageSize = 200
|
||||
|
||||
@@ -6,10 +6,10 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"openflare/common"
|
||||
"openflare/model"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -61,14 +61,32 @@ type snapshotRoute struct {
|
||||
Domain string `json:"domain"`
|
||||
OriginURL string `json:"origin_url"`
|
||||
OriginHost string `json:"origin_host,omitempty"`
|
||||
Upstreams []string `json:"upstreams,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
EnableHTTPS bool `json:"enable_https"`
|
||||
CertID *uint `json:"cert_id,omitempty"`
|
||||
RedirectHTTP bool `json:"redirect_http"`
|
||||
CacheEnabled bool `json:"cache_enabled"`
|
||||
CachePolicy string `json:"cache_policy,omitempty"`
|
||||
CacheRules []string `json:"cache_rules,omitempty"`
|
||||
CustomHeaders []ProxyRouteCustomHeaderInput `json:"custom_headers,omitempty"`
|
||||
Remark string `json:"remark,omitempty"`
|
||||
}
|
||||
|
||||
type routeCacheConfig struct {
|
||||
Enabled bool
|
||||
Policy string
|
||||
Rules []string
|
||||
}
|
||||
|
||||
type routeUpstreamConfig struct {
|
||||
Name string
|
||||
Scheme string
|
||||
ProxyPassURI string
|
||||
Servers []string
|
||||
UsesNamedUpstream bool
|
||||
}
|
||||
|
||||
type openRestyConfigSnapshot struct {
|
||||
WorkerProcesses string `json:"worker_processes"`
|
||||
WorkerConnections int `json:"worker_connections"`
|
||||
@@ -94,7 +112,6 @@ type openRestyConfigSnapshot struct {
|
||||
GzipEnabled bool `json:"gzip_enabled"`
|
||||
GzipMinLength int `json:"gzip_min_length"`
|
||||
GzipCompLevel int `json:"gzip_comp_level"`
|
||||
Resolvers string `json:"resolvers,omitempty"`
|
||||
CacheEnabled bool `json:"cache_enabled"`
|
||||
CachePath string `json:"cache_path,omitempty"`
|
||||
CacheLevels string `json:"cache_levels"`
|
||||
@@ -136,6 +153,8 @@ var requiredMainConfigTemplatePlaceholders = []string{
|
||||
"{{OpenRestyWorkerProcesses}}",
|
||||
"{{OpenRestyWorkerConnections}}",
|
||||
"{{OpenRestyWorkerRlimitNofile}}",
|
||||
"{{OpenRestyConnectionUpgradeMap}}",
|
||||
"{{OpenRestyDefaultServerBlock}}",
|
||||
"{{OpenRestyAccessLogPath}}",
|
||||
"{{OpenRestyEventsUseDirective}}",
|
||||
"{{OpenRestyEventsMultiAcceptDirective}}",
|
||||
@@ -157,7 +176,6 @@ var requiredMainConfigTemplatePlaceholders = []string{
|
||||
"{{OpenRestyGzip}}",
|
||||
"{{OpenRestyGzipMinLength}}",
|
||||
"{{OpenRestyGzipCompLevel}}",
|
||||
"{{OpenRestyResolverDirective}}",
|
||||
"{{OpenRestyCacheBlock}}",
|
||||
"{{OpenRestyRouteConfigInclude}}",
|
||||
}
|
||||
@@ -389,14 +407,26 @@ func buildSnapshotRoutes(routes []*model.ProxyRoute) ([]snapshotRoute, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("路由 %s 自定义请求头无效", route.Domain)
|
||||
}
|
||||
upstreams, err := decodeStoredUpstreams(route.Upstreams, route.OriginURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("路由 %s 上游配置无效", route.Domain)
|
||||
}
|
||||
cacheRules, err := decodeStoredCacheRules(route.CacheRules)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("路由 %s 缓存规则无效", route.Domain)
|
||||
}
|
||||
items = append(items, snapshotRoute{
|
||||
Domain: route.Domain,
|
||||
OriginURL: route.OriginURL,
|
||||
OriginHost: route.OriginHost,
|
||||
Upstreams: upstreams,
|
||||
Enabled: route.Enabled,
|
||||
EnableHTTPS: route.EnableHTTPS,
|
||||
CertID: route.CertID,
|
||||
RedirectHTTP: route.RedirectHTTP,
|
||||
CacheEnabled: route.CacheEnabled,
|
||||
CachePolicy: route.CachePolicy,
|
||||
CacheRules: cacheRules,
|
||||
CustomHeaders: customHeaders,
|
||||
Remark: route.Remark,
|
||||
})
|
||||
@@ -433,14 +463,40 @@ func normalizeSnapshotRoutes(routes []snapshotRoute) []snapshotRoute {
|
||||
if err == nil {
|
||||
routes[index].CustomHeaders = normalizedHeaders
|
||||
}
|
||||
normalizedUpstreams, err := normalizeUpstreams(routes[index].OriginURL, routes[index].Upstreams)
|
||||
if err == nil {
|
||||
routes[index].OriginURL = normalizedUpstreams[0]
|
||||
routes[index].Upstreams = normalizedUpstreams
|
||||
}
|
||||
normalizedCacheRules, err := normalizeCacheRules(routes[index].CacheEnabled, routes[index].CachePolicy, routes[index].CacheRules)
|
||||
if err == nil {
|
||||
routes[index].CachePolicy = normalizeCachePolicy(routes[index].CacheEnabled, routes[index].CachePolicy)
|
||||
routes[index].CacheRules = normalizedCacheRules
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
func snapshotRouteConfigEqual(left snapshotRoute, right snapshotRoute) bool {
|
||||
if left.Domain != right.Domain || left.OriginURL != right.OriginURL || left.OriginHost != right.OriginHost || left.EnableHTTPS != right.EnableHTTPS || left.RedirectHTTP != right.RedirectHTTP || !uintPointerEqual(left.CertID, right.CertID) {
|
||||
if left.Domain != right.Domain || left.OriginURL != right.OriginURL || left.OriginHost != right.OriginHost || left.EnableHTTPS != right.EnableHTTPS || left.RedirectHTTP != right.RedirectHTTP || left.CacheEnabled != right.CacheEnabled || left.CachePolicy != right.CachePolicy || !uintPointerEqual(left.CertID, right.CertID) {
|
||||
return false
|
||||
}
|
||||
if len(left.Upstreams) != len(right.Upstreams) {
|
||||
return false
|
||||
}
|
||||
for index := range left.Upstreams {
|
||||
if left.Upstreams[index] != right.Upstreams[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if len(left.CacheRules) != len(right.CacheRules) {
|
||||
return false
|
||||
}
|
||||
for index := range left.CacheRules {
|
||||
if left.CacheRules[index] != right.CacheRules[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if len(left.CustomHeaders) != len(right.CustomHeaders) {
|
||||
return false
|
||||
}
|
||||
@@ -478,7 +534,6 @@ func buildOpenRestyConfigSnapshot() openRestyConfigSnapshot {
|
||||
GzipEnabled: common.OpenRestyGzipEnabled,
|
||||
GzipMinLength: common.OpenRestyGzipMinLength,
|
||||
GzipCompLevel: common.OpenRestyGzipCompLevel,
|
||||
Resolvers: common.OpenRestyResolvers,
|
||||
CacheEnabled: common.OpenRestyCacheEnabled,
|
||||
CachePath: common.OpenRestyCachePath,
|
||||
CacheLevels: common.OpenRestyCacheLevels,
|
||||
@@ -540,7 +595,6 @@ func diffOpenRestyOptionDetails(left openRestyConfigSnapshot, right openRestyCon
|
||||
appendIfChanged("OpenRestyGzipEnabled", fmt.Sprintf("%t", left.GzipEnabled), fmt.Sprintf("%t", right.GzipEnabled))
|
||||
appendIfChanged("OpenRestyGzipMinLength", fmt.Sprintf("%d", left.GzipMinLength), fmt.Sprintf("%d", right.GzipMinLength))
|
||||
appendIfChanged("OpenRestyGzipCompLevel", fmt.Sprintf("%d", left.GzipCompLevel), fmt.Sprintf("%d", right.GzipCompLevel))
|
||||
appendIfChanged("OpenRestyResolvers", left.Resolvers, right.Resolvers)
|
||||
appendIfChanged("OpenRestyCacheEnabled", fmt.Sprintf("%t", left.CacheEnabled), fmt.Sprintf("%t", right.CacheEnabled))
|
||||
appendIfChanged("OpenRestyCachePath", left.CachePath, right.CachePath)
|
||||
appendIfChanged("OpenRestyCacheLevels", left.CacheLevels, right.CacheLevels)
|
||||
@@ -587,7 +641,6 @@ func openRestyOptionKeys() []string {
|
||||
"OpenRestyGzipEnabled",
|
||||
"OpenRestyGzipMinLength",
|
||||
"OpenRestyGzipCompLevel",
|
||||
"OpenRestyResolvers",
|
||||
"OpenRestyCacheEnabled",
|
||||
"OpenRestyCachePath",
|
||||
"OpenRestyCacheLevels",
|
||||
@@ -609,8 +662,25 @@ func renderRouteConfig(routes []*model.ProxyRoute, cfg openRestyConfigSnapshot)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("路由 %s 自定义请求头无效", route.Domain)
|
||||
}
|
||||
upstreams, err := decodeStoredUpstreams(route.Upstreams, route.OriginURL)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("路由 %s 上游配置无效", route.Domain)
|
||||
}
|
||||
cacheRules, err := decodeStoredCacheRules(route.CacheRules)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("路由 %s 缓存规则无效", route.Domain)
|
||||
}
|
||||
cacheConfig := routeCacheConfig{
|
||||
Enabled: route.CacheEnabled,
|
||||
Policy: route.CachePolicy,
|
||||
Rules: cacheRules,
|
||||
}
|
||||
upstreamConfig := buildRouteUpstreamConfig(route, upstreams)
|
||||
if upstreamConfig.UsesNamedUpstream {
|
||||
builder.WriteString(renderNamedUpstreamBlock(upstreamConfig))
|
||||
}
|
||||
if !route.EnableHTTPS {
|
||||
builder.WriteString(renderHTTPProxyServer(route.Domain, route.OriginURL, route.OriginHost, customHeaders, cfg))
|
||||
builder.WriteString(renderHTTPProxyServer(route.Domain, route.OriginURL, route.OriginHost, customHeaders, cacheConfig, upstreamConfig, cfg))
|
||||
continue
|
||||
}
|
||||
if route.CertID == nil || *route.CertID == 0 {
|
||||
@@ -627,9 +697,9 @@ func renderRouteConfig(routes []*model.ProxyRoute, cfg openRestyConfigSnapshot)
|
||||
if route.RedirectHTTP {
|
||||
builder.WriteString(renderHTTPRedirectServer(route.Domain))
|
||||
} else {
|
||||
builder.WriteString(renderHTTPProxyServer(route.Domain, route.OriginURL, route.OriginHost, customHeaders, cfg))
|
||||
builder.WriteString(renderHTTPProxyServer(route.Domain, route.OriginURL, route.OriginHost, customHeaders, cacheConfig, upstreamConfig, cfg))
|
||||
}
|
||||
builder.WriteString(renderHTTPSServer(route.Domain, route.OriginURL, route.OriginHost, certificate.ID, customHeaders, cfg))
|
||||
builder.WriteString(renderHTTPSServer(route.Domain, route.OriginURL, route.OriginHost, certificate.ID, customHeaders, cacheConfig, upstreamConfig, cfg))
|
||||
}
|
||||
return builder.String(), dedupeSupportFiles(supportFiles), nil
|
||||
}
|
||||
@@ -664,6 +734,8 @@ func renderMainConfigTemplate(templateText string, cfg openRestyConfigSnapshot)
|
||||
"{{OpenRestyWorkerProcesses}}", cfg.WorkerProcesses,
|
||||
"{{OpenRestyWorkerConnections}}", fmt.Sprintf("%d", cfg.WorkerConnections),
|
||||
"{{OpenRestyWorkerRlimitNofile}}", fmt.Sprintf("%d", cfg.WorkerRlimitNofile),
|
||||
"{{OpenRestyConnectionUpgradeMap}}", renderConnectionUpgradeMap(),
|
||||
"{{OpenRestyDefaultServerBlock}}", renderDefaultServerBlock(),
|
||||
"{{OpenRestyAccessLogPath}}", nginxAccessLogPlaceholder,
|
||||
"{{OpenRestyEventsUseDirective}}", renderTemplateDirective(cfg.EventsUse != "", fmt.Sprintf("use %s;", cfg.EventsUse)),
|
||||
"{{OpenRestyEventsMultiAcceptDirective}}", renderTemplateDirective(cfg.EventsMultiAcceptEnabled, "multi_accept on;"),
|
||||
@@ -685,7 +757,7 @@ func renderMainConfigTemplate(templateText string, cfg openRestyConfigSnapshot)
|
||||
"{{OpenRestyGzip}}", onOff(cfg.GzipEnabled),
|
||||
"{{OpenRestyGzipMinLength}}", fmt.Sprintf("%d", cfg.GzipMinLength),
|
||||
"{{OpenRestyGzipCompLevel}}", fmt.Sprintf("%d", cfg.GzipCompLevel),
|
||||
"{{OpenRestyResolverDirective}}", renderResolverDirective(cfg.Resolvers),
|
||||
"{{OpenRestyResolverDirective}}", "",
|
||||
"{{OpenRestyCacheBlock}}", renderOpenRestyCacheTemplateBlock(cfg),
|
||||
"{{OpenRestyRouteConfigInclude}}", nginxRouteConfigPlaceholder,
|
||||
)
|
||||
@@ -764,25 +836,29 @@ func nextVersionNumber(now time.Time) (string, error) {
|
||||
return fmt.Sprintf("%s-%03d", prefix, count+1), nil
|
||||
}
|
||||
|
||||
func renderHTTPProxyServer(domain string, originURL string, originHost string, customHeaders []ProxyRouteCustomHeaderInput, cfg openRestyConfigSnapshot) string {
|
||||
return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n%s\n location / {\n%s%s }\n}\n\n", domain, renderExactHostGuard(domain), renderProxyHeaderBlock(originURL, originHost, customHeaders), renderProxyPassBlock(originURL, cfg))
|
||||
func renderHTTPProxyServer(domain string, originURL string, originHost string, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, upstreamConfig routeUpstreamConfig, cfg openRestyConfigSnapshot) string {
|
||||
return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n\n location / {\n%s%s%s }\n}\n\n", domain, renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig))
|
||||
}
|
||||
|
||||
func renderHTTPRedirectServer(domain string) string {
|
||||
return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n%s\n return 301 https://$host$request_uri;\n}\n\n", domain, renderExactHostGuard(domain))
|
||||
return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n\n return 301 https://$host$request_uri;\n}\n\n", domain)
|
||||
}
|
||||
|
||||
func renderHTTPSServer(domain string, originURL string, originHost string, certificateID uint, customHeaders []ProxyRouteCustomHeaderInput, cfg openRestyConfigSnapshot) string {
|
||||
func renderHTTPSServer(domain string, originURL string, originHost string, certificateID uint, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, upstreamConfig routeUpstreamConfig, cfg openRestyConfigSnapshot) string {
|
||||
certPath := fmt.Sprintf("%s/%s", nginxCertDirPlaceholder, certificateCertFileName(certificateID))
|
||||
keyPath := fmt.Sprintf("%s/%s", nginxCertDirPlaceholder, certificateKeyFileName(certificateID))
|
||||
return fmt.Sprintf("server {\n listen 443 ssl http2;\n server_name %s;\n ssl_certificate %s;\n ssl_certificate_key %s;\n%s\n location / {\n%s%s }\n}\n\n", domain, certPath, keyPath, renderExactHostGuard(domain), renderProxyHeaderBlock(originURL, originHost, customHeaders), renderProxyPassBlock(originURL, cfg))
|
||||
return fmt.Sprintf("server {\n listen 443 ssl;\n http2 on;\n server_name %s;\n ssl_certificate %s;\n ssl_certificate_key %s;\n\n location / {\n%s%s%s }\n}\n\n", domain, certPath, keyPath, renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig))
|
||||
}
|
||||
|
||||
func renderExactHostGuard(domain string) string {
|
||||
return fmt.Sprintf(" if ($host != %q) {\n return 404;\n }\n", domain)
|
||||
func renderConnectionUpgradeMap() string {
|
||||
return " map $http_upgrade $connection_upgrade {\n default upgrade;\n '' \"\";\n }\n\n"
|
||||
}
|
||||
|
||||
func renderProxyHeaderBlock(originURL string, originHost string, customHeaders []ProxyRouteCustomHeaderInput) string {
|
||||
func renderDefaultServerBlock() string {
|
||||
return " server {\n listen 80 default_server;\n server_name _;\n\n return 404;\n }\n\n"
|
||||
}
|
||||
|
||||
func renderProxyHeaderBlock(originURL string, originHost string, customHeaders []ProxyRouteCustomHeaderInput, upstreamConfig routeUpstreamConfig) string {
|
||||
var builder strings.Builder
|
||||
if strings.TrimSpace(originHost) != "" {
|
||||
builder.WriteString(fmt.Sprintf(" proxy_set_header Host %s;\n", quoteNginxHeaderValue(originHost)))
|
||||
@@ -798,75 +874,181 @@ func renderProxyHeaderBlock(originURL string, originHost string, customHeaders [
|
||||
builder.WriteString(" proxy_set_header X-Forwarded-Proto $scheme;\n")
|
||||
if common.OpenRestyWebsocketEnabled {
|
||||
builder.WriteString(" proxy_http_version 1.1;\n")
|
||||
builder.WriteString(" proxy_set_header Connection $connection_upgrade;\n")
|
||||
builder.WriteString(" proxy_set_header Upgrade $http_upgrade;\n")
|
||||
builder.WriteString(" proxy_set_header Connection $http_connection;\n")
|
||||
} else if upstreamConfig.UsesNamedUpstream {
|
||||
builder.WriteString(" proxy_http_version 1.1;\n")
|
||||
builder.WriteString(" proxy_set_header Connection \"\";\n")
|
||||
}
|
||||
for _, header := range customHeaders {
|
||||
builder.WriteString(fmt.Sprintf(" proxy_set_header %s %s;\n", header.Key, quoteNginxHeaderValue(header.Value)))
|
||||
}
|
||||
if common.OpenRestyCacheEnabled {
|
||||
builder.WriteString(" proxy_cache openflare_cache;\n")
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func renderProxyPassBlock(originURL string, cfg openRestyConfigSnapshot) string {
|
||||
func renderRouteCacheBlock(cacheConfig routeCacheConfig, cfg openRestyConfigSnapshot) string {
|
||||
if !cfg.CacheEnabled || !cacheConfig.Enabled {
|
||||
return ""
|
||||
}
|
||||
var builder strings.Builder
|
||||
builder.WriteString(" set $openflare_skip_cache 0;\n")
|
||||
builder.WriteString(" if ($request_method != GET) {\n set $openflare_skip_cache 1;\n }\n")
|
||||
builder.WriteString(" if ($http_authorization != \"\") {\n set $openflare_skip_cache 1;\n }\n")
|
||||
builder.WriteString(" if ($http_cookie ~* \"(session|sess|token|auth|jwt|logged_in|remember|laravel_session|connect\\\\.sid|_session)\") {\n set $openflare_skip_cache 1;\n }\n")
|
||||
builder.WriteString(" if ($http_cache_control ~* \"(no-cache|no-store|private)\") {\n set $openflare_skip_cache 1;\n }\n")
|
||||
if policyCondition := renderRouteCachePolicyCondition(cacheConfig); policyCondition != "" {
|
||||
builder.WriteString(policyCondition)
|
||||
}
|
||||
builder.WriteString(" proxy_cache openflare_cache;\n")
|
||||
builder.WriteString(" proxy_cache_methods GET;\n")
|
||||
builder.WriteString(" proxy_cache_bypass $openflare_skip_cache;\n")
|
||||
builder.WriteString(" proxy_no_cache $openflare_skip_cache;\n")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func renderRouteCachePolicyCondition(cacheConfig routeCacheConfig) string {
|
||||
switch cacheConfig.Policy {
|
||||
case proxyRouteCachePolicySuffix:
|
||||
return fmt.Sprintf(" if ($uri !~* %s) {\n set $openflare_skip_cache 1;\n }\n", quoteNginxStringLiteral(buildSuffixMatchPattern(cacheConfig.Rules)))
|
||||
case proxyRouteCachePolicyPathPrefix:
|
||||
return fmt.Sprintf(" if ($uri !~ %s) {\n set $openflare_skip_cache 1;\n }\n", quoteNginxStringLiteral(buildPathPrefixMatchPattern(cacheConfig.Rules)))
|
||||
case proxyRouteCachePolicyPathExact:
|
||||
return fmt.Sprintf(" if ($uri !~ %s) {\n set $openflare_skip_cache 1;\n }\n", quoteNginxStringLiteral(buildPathExactMatchPattern(cacheConfig.Rules)))
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func buildSuffixMatchPattern(rules []string) string {
|
||||
parts := make([]string, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
parts = append(parts, regexp.QuoteMeta(rule))
|
||||
}
|
||||
return fmt.Sprintf("\\.(?:%s)$", strings.Join(parts, "|"))
|
||||
}
|
||||
|
||||
func buildPathPrefixMatchPattern(rules []string) string {
|
||||
parts := make([]string, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
trimmed := strings.TrimRight(rule, "/")
|
||||
if trimmed == "" {
|
||||
trimmed = "/"
|
||||
}
|
||||
if trimmed == "/" {
|
||||
parts = append(parts, "/")
|
||||
continue
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%s(?:/|$)", regexp.QuoteMeta(trimmed)))
|
||||
}
|
||||
return fmt.Sprintf("^(?:%s)", strings.Join(parts, "|"))
|
||||
}
|
||||
|
||||
func buildPathExactMatchPattern(rules []string) string {
|
||||
parts := make([]string, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
parts = append(parts, regexp.QuoteMeta(rule))
|
||||
}
|
||||
return fmt.Sprintf("^(?:%s)$", strings.Join(parts, "|"))
|
||||
}
|
||||
|
||||
func renderProxyPassBlock(originURL string, upstreamConfig routeUpstreamConfig) string {
|
||||
parsed, err := url.Parse(originURL)
|
||||
if err != nil || parsed.Host == "" || parsed.Scheme == "" {
|
||||
return fmt.Sprintf(" proxy_pass %s;\n", originURL)
|
||||
}
|
||||
if !shouldUseRuntimeResolver(originURL, cfg.Resolvers) {
|
||||
return fmt.Sprintf(" proxy_pass %s;\n", originURL)
|
||||
if upstreamConfig.UsesNamedUpstream {
|
||||
return fmt.Sprintf(" proxy_pass %s://%s%s;\n", upstreamConfig.Scheme, upstreamConfig.Name, upstreamConfig.ProxyPassURI)
|
||||
}
|
||||
upstreamURL := fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host)
|
||||
basePath := strings.TrimRight(parsed.EscapedPath(), "/")
|
||||
if basePath == "" || basePath == "." {
|
||||
basePath = ""
|
||||
return fmt.Sprintf(" proxy_pass %s;\n", originURL)
|
||||
}
|
||||
|
||||
func buildRouteUpstreamConfig(route *model.ProxyRoute, upstreams []string) routeUpstreamConfig {
|
||||
if len(upstreams) == 0 {
|
||||
return routeUpstreamConfig{}
|
||||
}
|
||||
if parsed.RawQuery != "" {
|
||||
if basePath == "" {
|
||||
basePath = "/"
|
||||
if len(upstreams) == 1 {
|
||||
parsed, err := url.Parse(strings.TrimSpace(upstreams[0]))
|
||||
if err != nil || parsed.Host == "" || parsed.Scheme == "" {
|
||||
return routeUpstreamConfig{}
|
||||
}
|
||||
return routeUpstreamConfig{
|
||||
Name: buildRouteUpstreamName(route),
|
||||
Scheme: parsed.Scheme,
|
||||
ProxyPassURI: buildUpstreamProxyPassURI(parsed),
|
||||
Servers: []string{parsed.Host},
|
||||
UsesNamedUpstream: true,
|
||||
}
|
||||
basePath += "?" + parsed.RawQuery
|
||||
}
|
||||
var builder strings.Builder
|
||||
builder.WriteString(fmt.Sprintf(" set $openflare_upstream %s;\n", quoteNginxStringLiteral(upstreamURL)))
|
||||
if basePath != "" {
|
||||
builder.WriteString(fmt.Sprintf(" set $openflare_upstream_base_path %s;\n", quoteNginxStringLiteral(basePath)))
|
||||
builder.WriteString(" proxy_pass $openflare_upstream$openflare_upstream_base_path$request_uri;\n")
|
||||
return builder.String()
|
||||
servers := make([]string, 0, len(upstreams))
|
||||
var scheme string
|
||||
for _, upstream := range upstreams {
|
||||
parsed, err := url.Parse(strings.TrimSpace(upstream))
|
||||
if err != nil || parsed.Host == "" || parsed.Scheme == "" {
|
||||
return routeUpstreamConfig{}
|
||||
}
|
||||
if strings.TrimSpace(parsed.EscapedPath()) != "" && strings.TrimSpace(parsed.EscapedPath()) != "/" {
|
||||
return routeUpstreamConfig{}
|
||||
}
|
||||
if parsed.RawQuery != "" {
|
||||
return routeUpstreamConfig{}
|
||||
}
|
||||
if scheme == "" {
|
||||
scheme = parsed.Scheme
|
||||
} else if scheme != parsed.Scheme {
|
||||
return routeUpstreamConfig{}
|
||||
}
|
||||
servers = append(servers, parsed.Host)
|
||||
}
|
||||
return routeUpstreamConfig{
|
||||
Name: buildRouteUpstreamName(route),
|
||||
Scheme: scheme,
|
||||
Servers: servers,
|
||||
UsesNamedUpstream: true,
|
||||
}
|
||||
builder.WriteString(" proxy_pass $openflare_upstream$request_uri;\n")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func shouldUseRuntimeResolver(originURL string, resolvers string) bool {
|
||||
if strings.TrimSpace(resolvers) == "" {
|
||||
return false
|
||||
}
|
||||
return requiresRuntimeResolver(originURL)
|
||||
}
|
||||
|
||||
func requiresRuntimeResolver(originURL string) bool {
|
||||
parsed, err := url.Parse(strings.TrimSpace(originURL))
|
||||
if err != nil || parsed.Hostname() == "" {
|
||||
return false
|
||||
}
|
||||
return net.ParseIP(parsed.Hostname()) == nil
|
||||
}
|
||||
|
||||
func renderResolverDirective(value string) string {
|
||||
resolvers := splitResolverList(value)
|
||||
if len(resolvers) == 0 {
|
||||
func buildUpstreamProxyPassURI(parsed *url.URL) string {
|
||||
if parsed == nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(" resolver %s valid=30s ipv6=off;\n resolver_timeout 5s;\n", strings.Join(resolvers, " "))
|
||||
path := parsed.EscapedPath()
|
||||
if path == "/" {
|
||||
path = ""
|
||||
}
|
||||
if parsed.RawQuery == "" {
|
||||
return path
|
||||
}
|
||||
return fmt.Sprintf("%s?%s", path, parsed.RawQuery)
|
||||
}
|
||||
|
||||
func splitResolverList(value string) []string {
|
||||
return strings.FieldsFunc(strings.TrimSpace(value), func(r rune) bool {
|
||||
return r == ',' || r == '\n' || r == '\r' || r == '\t' || r == ' '
|
||||
})
|
||||
func buildRouteUpstreamName(route *model.ProxyRoute) string {
|
||||
sanitized := strings.Map(func(r rune) rune {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z':
|
||||
return r
|
||||
case r >= 'A' && r <= 'Z':
|
||||
return r + ('a' - 'A')
|
||||
case r >= '0' && r <= '9':
|
||||
return r
|
||||
default:
|
||||
return '_'
|
||||
}
|
||||
}, route.Domain)
|
||||
sanitized = strings.Trim(sanitized, "_")
|
||||
if sanitized == "" {
|
||||
sanitized = "backend"
|
||||
}
|
||||
return fmt.Sprintf("backend_%s_%d", sanitized, route.ID)
|
||||
}
|
||||
|
||||
func renderNamedUpstreamBlock(upstreamConfig routeUpstreamConfig) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(fmt.Sprintf("upstream %s {\n", upstreamConfig.Name))
|
||||
for _, server := range upstreamConfig.Servers {
|
||||
builder.WriteString(fmt.Sprintf(" server %s max_fails=3 fail_timeout=10s;\n", server))
|
||||
}
|
||||
builder.WriteString(" keepalive 128;\n}\n\n")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func resolveUpstreamServerName(originURL string, originHost string) string {
|
||||
|
||||
@@ -66,14 +66,29 @@ func TestCreateTLSCertificateAndRenderHTTPSConfig(t *testing.T) {
|
||||
if strings.Contains(result.Version.MainConfig, "resolver ") {
|
||||
t.Fatal("expected main config to omit resolver directive when no resolvers are configured")
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, "use epoll;") {
|
||||
t.Fatal("expected main config to default to epoll event model")
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, "multi_accept on;") {
|
||||
t.Fatal("expected main config to default multi_accept to on")
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, "keepalive_timeout 20;") {
|
||||
t.Fatal("expected main config to default keepalive_timeout to 20")
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, "proxy_connect_timeout 3;") {
|
||||
t.Fatal("expected main config to default proxy_connect_timeout to 3")
|
||||
}
|
||||
if strings.Contains(result.Version.MainConfig, "allow 127.0.0.1;") {
|
||||
t.Fatal("expected main config to avoid hard-coded allow rules on observability server")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "listen 443 ssl http2;") {
|
||||
t.Fatal("expected rendered config to include https server block with http2 enabled")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "listen 443 ssl;") {
|
||||
t.Fatal("expected rendered config to include https ssl listener")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, `if ($host != "app.example.com") {`) {
|
||||
t.Fatal("expected rendered config to reject unmatched host headers with 404")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "http2 on;") {
|
||||
t.Fatal("expected rendered config to enable http2 with dedicated directive")
|
||||
}
|
||||
if strings.Contains(result.Version.RenderedConfig, `if ($host != "app.example.com") {`) {
|
||||
t.Fatal("expected rendered config to avoid per-route host guard")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "return 301 https://$host$request_uri;") {
|
||||
t.Fatal("expected rendered config to include http redirect")
|
||||
@@ -138,14 +153,184 @@ func TestPublishConfigVersionRendersCustomHeaders(t *testing.T) {
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_set_header Upgrade $http_upgrade;") {
|
||||
t.Fatal("expected rendered config to forward websocket upgrade header")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_set_header Connection $http_connection;") {
|
||||
t.Fatal("expected rendered config to forward websocket connection header")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_set_header Connection $connection_upgrade;") {
|
||||
t.Fatal("expected rendered config to use normalized websocket connection header")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://origin.internal;") {
|
||||
t.Fatal("expected rendered config to keep direct proxy_pass when no resolvers are configured")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_custom_example_com_1 {") {
|
||||
t.Fatal("expected hostname origin to render named upstream")
|
||||
}
|
||||
if strings.Contains(result.Version.RenderedConfig, "proxy_pass $openflare_upstream$request_uri;") {
|
||||
t.Fatal("expected rendered config to avoid runtime-resolved proxy_pass when no resolvers are configured")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server origin.internal max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected hostname origin to render upstream server entry")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "keepalive 128;") {
|
||||
t.Fatal("expected named upstream to enable keepalive")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://backend_custom_example_com_1;") {
|
||||
t.Fatal("expected hostname origin to proxy through named upstream")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateProxyRouteRejectsCachePolicyWithoutRules(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "cache.example.com",
|
||||
OriginURL: "https://origin.internal",
|
||||
Enabled: true,
|
||||
CacheEnabled: true,
|
||||
CachePolicy: proxyRouteCachePolicySuffix,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "至少填写一个后缀") {
|
||||
t.Fatalf("expected cache rule validation error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishConfigVersionRendersRouteLevelCachePolicy(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
if err := model.UpdateOption("OpenRestyCacheEnabled", "true"); err != nil {
|
||||
t.Fatalf("UpdateOption OpenRestyCacheEnabled failed: %v", err)
|
||||
}
|
||||
if err := model.UpdateOption("OpenRestyCachePath", "/var/cache/openresty/openflare"); err != nil {
|
||||
t.Fatalf("UpdateOption OpenRestyCachePath failed: %v", err)
|
||||
}
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "static.example.com",
|
||||
OriginURL: "https://origin.internal",
|
||||
Enabled: true,
|
||||
CacheEnabled: true,
|
||||
CachePolicy: proxyRouteCachePolicySuffix,
|
||||
CacheRules: []string{"jpg", ".css", "js"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateProxyRoute cached failed: %v", err)
|
||||
}
|
||||
_, err = CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "nocache.example.com",
|
||||
OriginURL: "https://origin.internal",
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateProxyRoute uncached failed: %v", err)
|
||||
}
|
||||
|
||||
result, err := PublishConfigVersion("root")
|
||||
if err != nil {
|
||||
t.Fatalf("PublishConfigVersion failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, "proxy_cache_path /var/cache/openresty/openflare") {
|
||||
t.Fatal("expected main config to include cache zone when cache infra is enabled")
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, `proxy_cache_key "$scheme$host$request_uri";`) {
|
||||
t.Fatal("expected main config to default cache key to host dimension")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_cache_methods GET;") {
|
||||
t.Fatal("expected rendered config to only cache GET requests")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_cache_bypass $openflare_skip_cache;") {
|
||||
t.Fatal("expected rendered config to bypass cache when request is unsafe")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_no_cache $openflare_skip_cache;") {
|
||||
t.Fatal("expected rendered config to avoid storing unsafe requests in cache")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "if ($http_authorization != \"\")") {
|
||||
t.Fatal("expected rendered config to bypass authenticated requests")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "if ($request_method != GET)") {
|
||||
t.Fatal("expected rendered config to bypass non-GET requests")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "if ($uri !~* \"\\\\.(?:jpg|css|js)$\")") {
|
||||
t.Fatal("expected rendered config to render suffix cache matching rule")
|
||||
}
|
||||
if strings.Count(result.Version.RenderedConfig, "proxy_cache openflare_cache;") != 1 {
|
||||
t.Fatal("expected only cache-enabled route to include proxy_cache directive")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://backend_static_example_com_1;") {
|
||||
t.Fatal("expected cache-enabled hostname route to proxy through named upstream")
|
||||
}
|
||||
if !strings.Contains(result.Version.SnapshotJSON, `"cache_enabled":true`) {
|
||||
t.Fatal("expected snapshot to include route cache toggle")
|
||||
}
|
||||
if !strings.Contains(result.Version.SnapshotJSON, `"cache_policy":"suffix"`) {
|
||||
t.Fatal("expected snapshot to include route cache policy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishConfigVersionRendersMultipleUpstreams(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
route, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "lb.example.com",
|
||||
OriginURL: "http://10.0.0.11:39010",
|
||||
Upstreams: []string{"http://10.0.0.12:39010", "http://10.0.0.13:39010"},
|
||||
Enabled: true,
|
||||
OriginHost: "lb.example.com",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateProxyRoute failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(route.Upstreams, "10.0.0.12:39010") {
|
||||
t.Fatalf("expected route upstreams to persist, got %s", route.Upstreams)
|
||||
}
|
||||
|
||||
result, err := PublishConfigVersion("root")
|
||||
if err != nil {
|
||||
t.Fatalf("PublishConfigVersion failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_lb_example_com_1 {") {
|
||||
t.Fatal("expected rendered config to define upstream block for load balancing route")
|
||||
}
|
||||
if strings.Count(result.Version.RenderedConfig, "max_fails=3 fail_timeout=10s;") < 3 {
|
||||
t.Fatal("expected rendered config to include every upstream server")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server 10.0.0.11:39010 max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected rendered config to include primary upstream server")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server 10.0.0.12:39010 max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected rendered config to include secondary upstream server")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server 10.0.0.13:39010 max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected rendered config to include tertiary upstream server")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass http://backend_lb_example_com_1;") {
|
||||
t.Fatal("expected rendered config to proxy through load balancing upstream")
|
||||
}
|
||||
if !strings.Contains(result.Version.SnapshotJSON, `"upstreams":["http://10.0.0.11:39010","http://10.0.0.12:39010","http://10.0.0.13:39010"]`) {
|
||||
t.Fatal("expected snapshot to include upstream list")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishConfigVersionRendersHostnameLoadBalancingUpstream(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "hostname-lb.example.com",
|
||||
OriginURL: "http://c1:39010",
|
||||
Upstreams: []string{"http://c2:39010"},
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateProxyRoute failed: %v", err)
|
||||
}
|
||||
|
||||
result, err := PublishConfigVersion("root")
|
||||
if err != nil {
|
||||
t.Fatalf("PublishConfigVersion failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_hostname_lb_example_com_1 {") {
|
||||
t.Fatal("expected hostname load balancing route to define named upstream")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server c1:39010 max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected rendered config to include primary hostname upstream")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server c2:39010 max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected rendered config to include secondary hostname upstream")
|
||||
}
|
||||
if strings.Contains(result.Version.RenderedConfig, " resolve ") {
|
||||
t.Fatal("expected hostname upstreams to avoid resolver-based server parameters")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass http://backend_hostname_lb_example_com_1;") {
|
||||
t.Fatal("expected hostname load balancing route to proxy through named upstream")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,22 +360,46 @@ func TestPublishConfigVersionOverridesOriginHostHeader(t *testing.T) {
|
||||
if !strings.Contains(result.Version.RenderedConfig, `proxy_ssl_name "git.arctel.net";`) {
|
||||
t.Fatal("expected rendered config to set proxy ssl name from origin host override")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://git.arctel.net;") {
|
||||
t.Fatal("expected rendered config to keep direct proxy_pass for hostname origin when resolvers are blank")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_git_arctel_de_1 {") {
|
||||
t.Fatal("expected hostname origin to render named upstream")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://backend_git_arctel_de_1;") {
|
||||
t.Fatal("expected rendered config to proxy through named upstream for hostname origin")
|
||||
}
|
||||
if !strings.Contains(result.Version.SnapshotJSON, `"origin_host":"git.arctel.net"`) {
|
||||
t.Fatal("expected snapshot to include origin_host override")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishConfigVersionUsesRuntimeResolverWhenConfigured(t *testing.T) {
|
||||
func TestPublishConfigVersionUsesNamedUpstreamForOriginBasePath(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
if err := model.UpdateOption("OpenRestyResolvers", "1.1.1.1, 8.8.8.8"); err != nil {
|
||||
t.Fatalf("UpdateOption OpenRestyResolvers failed: %v", err)
|
||||
}
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "resolver.example.com",
|
||||
OriginURL: "https://origin.internal/api/",
|
||||
Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateProxyRoute failed: %v", err)
|
||||
}
|
||||
|
||||
result, err := PublishConfigVersion("root")
|
||||
if err != nil {
|
||||
t.Fatalf("PublishConfigVersion failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_resolver_example_com_1 {") {
|
||||
t.Fatal("expected hostname origin with base path to still render named upstream")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://backend_resolver_example_com_1/api/;") {
|
||||
t.Fatal("expected rendered config to preserve base path while proxying through named upstream")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishConfigVersionUsesNamedUpstreamForHostnameOrigins(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "resolver-upstream.example.com",
|
||||
OriginURL: "https://origin.internal",
|
||||
Enabled: true,
|
||||
})
|
||||
@@ -202,18 +411,18 @@ func TestPublishConfigVersionUsesRuntimeResolverWhenConfigured(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("PublishConfigVersion failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.Version.MainConfig, "resolver 1.1.1.1 8.8.8.8 valid=30s ipv6=off;") {
|
||||
t.Fatal("expected main config to render configured resolver directive")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_resolver_upstream_example_com_1 {") {
|
||||
t.Fatal("expected rendered config to define named upstream for hostname origin")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, `set $openflare_upstream "https://origin.internal";`) {
|
||||
t.Fatal("expected rendered config to use runtime upstream variable when resolvers are configured")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "server origin.internal max_fails=3 fail_timeout=10s;") {
|
||||
t.Fatal("expected rendered config to include hostname upstream server entry")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass $openflare_upstream$request_uri;") {
|
||||
t.Fatal("expected rendered config to proxy via runtime-resolved upstream variable when resolvers are configured")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass https://backend_resolver_upstream_example_com_1;") {
|
||||
t.Fatal("expected rendered config to proxy through named upstream for hostname origin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishConfigVersionKeepsDirectProxyPassForIPOrigins(t *testing.T) {
|
||||
func TestPublishConfigVersionUsesNamedUpstreamForIPOrigins(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
@@ -229,8 +438,11 @@ func TestPublishConfigVersionKeepsDirectProxyPassForIPOrigins(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("PublishConfigVersion failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass http://10.0.0.8:8080;") {
|
||||
t.Fatal("expected rendered config to keep direct proxy_pass for IP origin")
|
||||
if !strings.Contains(result.Version.RenderedConfig, "upstream backend_ip_origin_example_com_1 {") {
|
||||
t.Fatal("expected rendered config to define named upstream for static IP origins")
|
||||
}
|
||||
if !strings.Contains(result.Version.RenderedConfig, "proxy_pass http://backend_ip_origin_example_com_1;") {
|
||||
t.Fatal("expected rendered config to proxy through named upstream for IP origin")
|
||||
}
|
||||
if strings.Contains(result.Version.RenderedConfig, `set $openflare_upstream "http://10.0.0.8:8080"`) {
|
||||
t.Fatal("expected rendered config to avoid runtime resolver variables for IP origin")
|
||||
@@ -239,7 +451,6 @@ func TestPublishConfigVersionKeepsDirectProxyPassForIPOrigins(t *testing.T) {
|
||||
|
||||
func TestPreviewConfigVersionCanDisableWebsocketHeaders(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
Domain: "ws-off.example.com",
|
||||
OriginURL: "https://origin.internal",
|
||||
@@ -256,15 +467,15 @@ func TestPreviewConfigVersionCanDisableWebsocketHeaders(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("PreviewConfigVersion failed: %v", err)
|
||||
}
|
||||
if strings.Contains(preview.RenderedConfig, "proxy_http_version 1.1;") {
|
||||
t.Fatal("expected preview config to omit websocket proxy_http_version when disabled")
|
||||
if !strings.Contains(preview.RenderedConfig, "proxy_http_version 1.1;") {
|
||||
t.Fatal("expected preview config to keep HTTP/1.1 proxying for named upstream keepalive")
|
||||
}
|
||||
if !strings.Contains(preview.RenderedConfig, `proxy_set_header Connection "";`) {
|
||||
t.Fatal("expected preview config to clear connection header when websocket upgrades are disabled")
|
||||
}
|
||||
if strings.Contains(preview.RenderedConfig, "proxy_set_header Upgrade $http_upgrade;") {
|
||||
t.Fatal("expected preview config to omit websocket upgrade header when disabled")
|
||||
}
|
||||
if strings.Contains(preview.RenderedConfig, "proxy_set_header Connection $http_connection;") {
|
||||
t.Fatal("expected preview config to omit websocket connection header when disabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewAndDiffConfigVersion(t *testing.T) {
|
||||
@@ -411,7 +622,7 @@ func TestPreviewAndDiffConfigVersion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfigRejectsUnknownSubdomainHosts(t *testing.T) {
|
||||
func TestRenderConfigUsesDefaultServerFallback(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
_, err := CreateProxyRoute(ProxyRouteInput{
|
||||
@@ -431,11 +642,17 @@ func TestRenderConfigRejectsUnknownSubdomainHosts(t *testing.T) {
|
||||
if !strings.Contains(preview.RenderedConfig, `server_name git.arctel.net;`) {
|
||||
t.Fatal("expected rendered config to include exact server_name")
|
||||
}
|
||||
if !strings.Contains(preview.RenderedConfig, `if ($host != "git.arctel.net") {`) {
|
||||
t.Fatal("expected rendered config to guard against unknown subdomain host matches")
|
||||
if strings.Contains(preview.RenderedConfig, `if ($host != "git.arctel.net") {`) {
|
||||
t.Fatal("expected rendered config to avoid per-route host guard")
|
||||
}
|
||||
if !strings.Contains(preview.RenderedConfig, "return 404;") {
|
||||
t.Fatal("expected rendered config to return 404 when host does not exactly match route domain")
|
||||
if !strings.Contains(preview.MainConfig, "listen 80 default_server;") {
|
||||
t.Fatal("expected preview main config to include default http server")
|
||||
}
|
||||
if !strings.Contains(preview.MainConfig, "server_name _;") {
|
||||
t.Fatal("expected preview main config to include default server_name")
|
||||
}
|
||||
if !strings.Contains(preview.MainConfig, "return 404;") {
|
||||
t.Fatal("expected preview main config to return 404 for unmatched hosts")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,6 +700,12 @@ func TestOpenRestyMainConfigTemplateRenderAndValidate(t *testing.T) {
|
||||
if !strings.Contains(preview.MainConfig, "access_log __OPENFLARE_ACCESS_LOG__ openflare_json;") {
|
||||
t.Fatal("expected preview main config to preserve managed access log placeholder")
|
||||
}
|
||||
if !strings.Contains(preview.MainConfig, "map $http_upgrade $connection_upgrade {") {
|
||||
t.Fatal("expected preview main config to preserve managed websocket upgrade map")
|
||||
}
|
||||
if !strings.Contains(preview.MainConfig, "listen 80 default_server;") {
|
||||
t.Fatal("expected preview main config to preserve managed default server block")
|
||||
}
|
||||
|
||||
invalidTemplate := strings.ReplaceAll(
|
||||
common.OpenRestyMainConfigTemplate,
|
||||
@@ -501,6 +724,15 @@ func TestOpenRestyMainConfigTemplateRenderAndValidate(t *testing.T) {
|
||||
if err := ValidateOpenRestyMainConfigTemplate(invalidTemplate); err == nil {
|
||||
t.Fatal("expected template without managed access log placeholder to fail validation")
|
||||
}
|
||||
|
||||
invalidTemplate = strings.ReplaceAll(
|
||||
common.OpenRestyMainConfigTemplate,
|
||||
"{{OpenRestyConnectionUpgradeMap}}",
|
||||
"",
|
||||
)
|
||||
if err := ValidateOpenRestyMainConfigTemplate(invalidTemplate); err == nil {
|
||||
t.Fatal("expected template without managed websocket upgrade map placeholder to fail validation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRestyCommonRequestOptionsRender(t *testing.T) {
|
||||
|
||||
@@ -418,9 +418,9 @@ func normalizeAgentNodePayload(payload AgentNodePayload) AgentNodePayload {
|
||||
payload.AgentVersion = strings.TrimSpace(payload.AgentVersion)
|
||||
payload.NginxVersion = strings.TrimSpace(payload.NginxVersion)
|
||||
payload.CurrentVersion = strings.TrimSpace(payload.CurrentVersion)
|
||||
payload.LastError = strings.TrimSpace(payload.LastError)
|
||||
payload.LastError = truncateForDatabase(payload.LastError, 16000)
|
||||
payload.OpenrestyStatus = normalizeOpenrestyStatus(payload.OpenrestyStatus)
|
||||
payload.OpenrestyMessage = strings.TrimSpace(payload.OpenrestyMessage)
|
||||
payload.OpenrestyMessage = truncateForDatabase(payload.OpenrestyMessage, 16000)
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -444,11 +444,11 @@ func applyNodeRuntime(node *model.Node, payload AgentNodePayload, preserveName b
|
||||
node.AgentVersion = strings.TrimSpace(payload.AgentVersion)
|
||||
node.NginxVersion = strings.TrimSpace(payload.NginxVersion)
|
||||
node.OpenrestyStatus = normalizeOpenrestyStatus(payload.OpenrestyStatus)
|
||||
node.OpenrestyMessage = strings.TrimSpace(payload.OpenrestyMessage)
|
||||
node.OpenrestyMessage = truncateForDatabase(payload.OpenrestyMessage, 16000)
|
||||
node.Status = NodeStatusOnline
|
||||
node.CurrentVersion = strings.TrimSpace(payload.CurrentVersion)
|
||||
node.LastSeenAt = time.Now()
|
||||
node.LastError = strings.TrimSpace(payload.LastError)
|
||||
node.LastError = truncateForDatabase(payload.LastError, 16000)
|
||||
if !node.GeoManualOverride {
|
||||
applyGeoInfoFromIP(node, node.IP)
|
||||
}
|
||||
|
||||
@@ -42,6 +42,11 @@ type NodeObservabilityTrends struct {
|
||||
DiskIO24h []DiskIOTrendPoint `json:"disk_io_24h"`
|
||||
}
|
||||
|
||||
type NodeHealthEventCleanupResult struct {
|
||||
NodeID string `json:"node_id"`
|
||||
DeletedCount int64 `json:"deleted_count"`
|
||||
}
|
||||
|
||||
func GetNodeObservability(id uint, query NodeObservabilityQuery) (*NodeObservabilityView, error) {
|
||||
now := time.Now()
|
||||
node, err := model.GetNodeByID(id)
|
||||
@@ -105,6 +110,21 @@ func GetNodeObservability(id uint, query NodeObservabilityQuery) (*NodeObservabi
|
||||
}, nil
|
||||
}
|
||||
|
||||
func CleanupNodeHealthEvents(id uint) (*NodeHealthEventCleanupResult, error) {
|
||||
node, err := model.GetNodeByID(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deletedCount, err := model.DeleteNodeHealthEvents(node.NodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &NodeHealthEventCleanupResult{
|
||||
NodeID: node.NodeID,
|
||||
DeletedCount: deletedCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func latestMetricSnapshot(snapshots []*model.NodeMetricSnapshot) *model.NodeMetricSnapshot {
|
||||
for _, snapshot := range snapshots {
|
||||
if snapshot != nil {
|
||||
|
||||
@@ -1201,6 +1201,66 @@ func TestGetNodeObservabilityAllowsMissingProfile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupNodeHealthEvents(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
node := &model.Node{
|
||||
NodeID: "node-health-cleanup",
|
||||
Name: "health-cleanup-edge",
|
||||
IP: "10.0.0.72",
|
||||
AgentToken: "token-health-cleanup",
|
||||
AgentVersion: "v0.6.0",
|
||||
NginxVersion: "1.27.1.2",
|
||||
Status: NodeStatusOnline,
|
||||
}
|
||||
if err := node.Insert(); err != nil {
|
||||
t.Fatalf("failed to insert node: %v", err)
|
||||
}
|
||||
|
||||
resolvedAt := time.Now().Add(-4 * time.Minute)
|
||||
if err := model.DB.Create(&model.NodeHealthEvent{
|
||||
NodeID: node.NodeID,
|
||||
EventType: "sync_error",
|
||||
Severity: NodeHealthSeverityWarning,
|
||||
Status: NodeHealthEventStatusActive,
|
||||
Message: "checksum mismatch",
|
||||
FirstTriggeredAt: time.Now().Add(-2 * time.Minute),
|
||||
LastTriggeredAt: time.Now().Add(-time.Minute),
|
||||
ReportedAt: time.Now().Add(-time.Minute),
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("failed to insert first node health event: %v", err)
|
||||
}
|
||||
if err := model.DB.Create(&model.NodeHealthEvent{
|
||||
NodeID: node.NodeID,
|
||||
EventType: "openresty_down",
|
||||
Severity: NodeHealthSeverityCritical,
|
||||
Status: NodeHealthEventStatusResolved,
|
||||
Message: "openresty exited unexpectedly",
|
||||
FirstTriggeredAt: time.Now().Add(-10 * time.Minute),
|
||||
LastTriggeredAt: time.Now().Add(-5 * time.Minute),
|
||||
ReportedAt: time.Now().Add(-5 * time.Minute),
|
||||
ResolvedAt: &resolvedAt,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("failed to insert second node health event: %v", err)
|
||||
}
|
||||
|
||||
result, err := CleanupNodeHealthEvents(node.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CleanupNodeHealthEvents failed: %v", err)
|
||||
}
|
||||
if result.NodeID != node.NodeID || result.DeletedCount != 2 {
|
||||
t.Fatalf("unexpected cleanup result: %+v", result)
|
||||
}
|
||||
|
||||
events, err := model.ListNodeHealthEvents(node.NodeID, false, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list node health events after cleanup: %v", err)
|
||||
}
|
||||
if len(events) != 0 {
|
||||
t.Fatalf("expected node health events to be removed, got %+v", events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDashboardOverview(t *testing.T) {
|
||||
setupServiceTestDB(t)
|
||||
|
||||
|
||||
@@ -271,7 +271,7 @@ func reconcileNodeHealthEvents(tx *gorm.DB, nodeID string, events []AgentNodeHea
|
||||
triggeredAt := timeFromUnix(event.TriggeredAtUnix, reportedAt)
|
||||
if existing, ok := activeByType[eventType]; ok {
|
||||
existing.Severity = event.Severity
|
||||
existing.Message = strings.TrimSpace(event.Message)
|
||||
existing.Message = normalizeHealthEventMessage(event.Message)
|
||||
existing.LastTriggeredAt = triggeredAt
|
||||
existing.ReportedAt = reportedAt
|
||||
existing.RawJSON = marshalJSON(event)
|
||||
@@ -286,7 +286,7 @@ func reconcileNodeHealthEvents(tx *gorm.DB, nodeID string, events []AgentNodeHea
|
||||
EventType: eventType,
|
||||
Severity: event.Severity,
|
||||
Status: NodeHealthEventStatusActive,
|
||||
Message: strings.TrimSpace(event.Message),
|
||||
Message: normalizeHealthEventMessage(event.Message),
|
||||
FirstTriggeredAt: triggeredAt,
|
||||
LastTriggeredAt: triggeredAt,
|
||||
ReportedAt: reportedAt,
|
||||
@@ -330,6 +330,10 @@ func normalizeHealthSeverity(severity string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeHealthEventMessage(message string) string {
|
||||
return truncateForDatabase(message, 4096)
|
||||
}
|
||||
|
||||
func timeFromUnix(unixSeconds int64, fallback time.Time) time.Time {
|
||||
if unixSeconds <= 0 {
|
||||
return fallback
|
||||
|
||||
@@ -11,6 +11,13 @@ import (
|
||||
|
||||
var proxyHeaderKeyPattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
|
||||
const (
|
||||
proxyRouteCachePolicyURL = "url"
|
||||
proxyRouteCachePolicySuffix = "suffix"
|
||||
proxyRouteCachePolicyPathPrefix = "path_prefix"
|
||||
proxyRouteCachePolicyPathExact = "path_exact"
|
||||
)
|
||||
|
||||
type ProxyRouteCustomHeaderInput struct {
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
@@ -20,10 +27,14 @@ type ProxyRouteInput struct {
|
||||
Domain string `json:"domain"`
|
||||
OriginURL string `json:"origin_url"`
|
||||
OriginHost string `json:"origin_host"`
|
||||
Upstreams []string `json:"upstreams"`
|
||||
Enabled bool `json:"enabled"`
|
||||
EnableHTTPS bool `json:"enable_https"`
|
||||
CertID *uint `json:"cert_id"`
|
||||
RedirectHTTP bool `json:"redirect_http"`
|
||||
CacheEnabled bool `json:"cache_enabled"`
|
||||
CachePolicy string `json:"cache_policy"`
|
||||
CacheRules []string `json:"cache_rules"`
|
||||
CustomHeaders []ProxyRouteCustomHeaderInput `json:"custom_headers"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
@@ -77,10 +88,27 @@ func buildProxyRoute(route *model.ProxyRoute, input ProxyRouteInput) (*model.Pro
|
||||
originURL := strings.TrimSpace(input.OriginURL)
|
||||
originHost := strings.TrimSpace(input.OriginHost)
|
||||
remark := strings.TrimSpace(input.Remark)
|
||||
upstreams, err := normalizeUpstreams(originURL, input.Upstreams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cachePolicy := strings.TrimSpace(input.CachePolicy)
|
||||
cacheRules, err := normalizeCacheRules(input.CacheEnabled, cachePolicy, input.CacheRules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
customHeaders, err := normalizeCustomHeaders(input.CustomHeaders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cacheRulesJSON, err := json.Marshal(cacheRules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
upstreamsJSON, err := json.Marshal(upstreams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
customHeadersJSON, err := json.Marshal(customHeaders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -91,9 +119,6 @@ func buildProxyRoute(route *model.ProxyRoute, input ProxyRouteInput) (*model.Pro
|
||||
if strings.Contains(domain, "://") || strings.Contains(domain, "/") {
|
||||
return nil, errors.New("域名格式不合法")
|
||||
}
|
||||
if err := validateOriginURL(originURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateOriginHost(originHost); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -116,12 +141,16 @@ func buildProxyRoute(route *model.ProxyRoute, input ProxyRouteInput) (*model.Pro
|
||||
route = &model.ProxyRoute{}
|
||||
}
|
||||
route.Domain = domain
|
||||
route.OriginURL = originURL
|
||||
route.OriginURL = upstreams[0]
|
||||
route.OriginHost = originHost
|
||||
route.Upstreams = string(upstreamsJSON)
|
||||
route.Enabled = input.Enabled
|
||||
route.EnableHTTPS = input.EnableHTTPS
|
||||
route.CertID = input.CertID
|
||||
route.RedirectHTTP = input.RedirectHTTP
|
||||
route.CacheEnabled = input.CacheEnabled
|
||||
route.CachePolicy = normalizeCachePolicy(input.CacheEnabled, cachePolicy)
|
||||
route.CacheRules = string(cacheRulesJSON)
|
||||
route.CustomHeaders = string(customHeadersJSON)
|
||||
route.Remark = remark
|
||||
return route, nil
|
||||
@@ -155,6 +184,59 @@ func normalizeCustomHeaders(headers []ProxyRouteCustomHeaderInput) ([]ProxyRoute
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func normalizeUpstreams(originURL string, upstreams []string) ([]string, error) {
|
||||
candidates := make([]string, 0, len(upstreams)+1)
|
||||
if strings.TrimSpace(originURL) != "" {
|
||||
candidates = append(candidates, originURL)
|
||||
}
|
||||
candidates = append(candidates, upstreams...)
|
||||
trimmed := make([]string, 0, len(candidates))
|
||||
for _, candidate := range candidates {
|
||||
item := strings.TrimSpace(candidate)
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
trimmed = append(trimmed, item)
|
||||
}
|
||||
unique := make([]string, 0, len(trimmed))
|
||||
seen := make(map[string]struct{}, len(trimmed))
|
||||
for _, item := range trimmed {
|
||||
if _, ok := seen[item]; ok {
|
||||
continue
|
||||
}
|
||||
seen[item] = struct{}{}
|
||||
unique = append(unique, item)
|
||||
}
|
||||
normalized := make([]string, 0, len(unique))
|
||||
var scheme string
|
||||
multiUpstream := len(unique) > 1
|
||||
for _, item := range unique {
|
||||
if err := validateOriginURL(item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parsed, err := url.ParseRequestURI(item)
|
||||
if err != nil {
|
||||
return nil, errors.New("源站地址格式不合法")
|
||||
}
|
||||
if multiUpstream && parsed.Path != "" && parsed.Path != "/" {
|
||||
return nil, errors.New("多上游模式暂不支持带路径的源站地址")
|
||||
}
|
||||
if multiUpstream && parsed.RawQuery != "" {
|
||||
return nil, errors.New("多上游模式暂不支持带查询参数的源站地址")
|
||||
}
|
||||
if scheme == "" {
|
||||
scheme = parsed.Scheme
|
||||
} else if scheme != parsed.Scheme {
|
||||
return nil, errors.New("同一规则的多个上游必须使用相同协议")
|
||||
}
|
||||
normalized = append(normalized, item)
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
return nil, errors.New("至少填写一个上游地址")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func decodeStoredCustomHeaders(raw string) ([]ProxyRouteCustomHeaderInput, error) {
|
||||
text := strings.TrimSpace(raw)
|
||||
if text == "" {
|
||||
@@ -167,6 +249,120 @@ func decodeStoredCustomHeaders(raw string) ([]ProxyRouteCustomHeaderInput, error
|
||||
return normalizeCustomHeaders(headers)
|
||||
}
|
||||
|
||||
func normalizeCachePolicy(enabled bool, raw string) string {
|
||||
if !enabled {
|
||||
return ""
|
||||
}
|
||||
policy := strings.TrimSpace(raw)
|
||||
if policy == "" {
|
||||
return proxyRouteCachePolicyURL
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
func normalizeCacheRules(enabled bool, rawPolicy string, rules []string) ([]string, error) {
|
||||
if !enabled {
|
||||
return []string{}, nil
|
||||
}
|
||||
policy := normalizeCachePolicy(enabled, rawPolicy)
|
||||
switch policy {
|
||||
case proxyRouteCachePolicyURL:
|
||||
return []string{}, nil
|
||||
case proxyRouteCachePolicySuffix:
|
||||
return normalizeCacheSuffixRules(rules)
|
||||
case proxyRouteCachePolicyPathPrefix:
|
||||
return normalizeCachePathRules(rules, true)
|
||||
case proxyRouteCachePolicyPathExact:
|
||||
return normalizeCachePathRules(rules, false)
|
||||
default:
|
||||
return nil, errors.New("缓存策略不支持")
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeCacheSuffixRules(rules []string) ([]string, error) {
|
||||
normalized := make([]string, 0, len(rules))
|
||||
seen := make(map[string]struct{}, len(rules))
|
||||
for _, rule := range rules {
|
||||
item := strings.TrimSpace(strings.TrimPrefix(rule, "."))
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
if strings.ContainsAny(item, "/\\ \t\r\n") {
|
||||
return nil, errors.New("缓存后缀格式不合法")
|
||||
}
|
||||
if _, ok := seen[item]; ok {
|
||||
continue
|
||||
}
|
||||
seen[item] = struct{}{}
|
||||
normalized = append(normalized, item)
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
return nil, errors.New("按后缀缓存时至少填写一个后缀")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func normalizeCachePathRules(rules []string, allowPrefix bool) ([]string, error) {
|
||||
normalized := make([]string, 0, len(rules))
|
||||
seen := make(map[string]struct{}, len(rules))
|
||||
for _, rule := range rules {
|
||||
item := strings.TrimSpace(rule)
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(item, "/") || strings.Contains(item, "://") || strings.ContainsAny(item, " \t\r\n") {
|
||||
return nil, errors.New("缓存路径规则格式不合法")
|
||||
}
|
||||
if !allowPrefix && strings.HasSuffix(item, "/") && len(item) > 1 {
|
||||
item = strings.TrimRight(item, "/")
|
||||
}
|
||||
if _, ok := seen[item]; ok {
|
||||
continue
|
||||
}
|
||||
seen[item] = struct{}{}
|
||||
normalized = append(normalized, item)
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
if allowPrefix {
|
||||
return nil, errors.New("按路径前缀缓存时至少填写一个路径")
|
||||
}
|
||||
return nil, errors.New("按精确路径缓存时至少填写一个路径")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func decodeStoredCacheRules(raw string) ([]string, error) {
|
||||
text := strings.TrimSpace(raw)
|
||||
if text == "" {
|
||||
return []string{}, nil
|
||||
}
|
||||
var rules []string
|
||||
if err := json.Unmarshal([]byte(text), &rules); err != nil {
|
||||
return nil, errors.New("缓存规则格式不合法")
|
||||
}
|
||||
normalized := make([]string, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
item := strings.TrimSpace(rule)
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
normalized = append(normalized, item)
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func decodeStoredUpstreams(raw string, fallbackOriginURL string) ([]string, error) {
|
||||
text := strings.TrimSpace(raw)
|
||||
if text == "" {
|
||||
return normalizeUpstreams(fallbackOriginURL, nil)
|
||||
}
|
||||
var upstreams []string
|
||||
if err := json.Unmarshal([]byte(text), &upstreams); err != nil {
|
||||
return nil, errors.New("上游配置格式不合法")
|
||||
}
|
||||
return normalizeUpstreams(fallbackOriginURL, upstreams)
|
||||
}
|
||||
|
||||
func validateOriginURL(raw string) error {
|
||||
if raw == "" {
|
||||
return errors.New("源站地址不能为空")
|
||||
|
||||
@@ -85,3 +85,12 @@ export function getNodeObservability(
|
||||
`/nodes/${id}/observability${query ? `?${query}` : ''}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function cleanupNodeHealthEvents(id: number) {
|
||||
return apiRequest<{ node_id: string; deleted_count: number }>(
|
||||
`/nodes/${id}/observability/cleanup`,
|
||||
{
|
||||
method: 'POST',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import { ConfigVersionSnapshotModal } from '@/features/config-versions/component
|
||||
import type { ConfigVersionSummary } from '@/features/config-versions/types';
|
||||
import { getApplyLogs } from '@/features/apply-logs/api/apply-logs';
|
||||
import {
|
||||
cleanupNodeHealthEvents,
|
||||
deleteNode,
|
||||
getNodeAgentRelease,
|
||||
getNodeObservability,
|
||||
@@ -250,6 +251,8 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
const [healthEventFilter, setHealthEventFilter] =
|
||||
useState<HealthEventFilter>('all');
|
||||
const [activeTab, setActiveTab] = useState<NodeDetailTab>('dashboard');
|
||||
const [isHealthEventCleanupModalOpen, setHealthEventCleanupModalOpen] =
|
||||
useState(false);
|
||||
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
@@ -373,6 +376,27 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
},
|
||||
});
|
||||
|
||||
const cleanupHealthEventsMutation = useMutation({
|
||||
mutationFn: () => cleanupNodeHealthEvents(Number(nodeId)),
|
||||
onSuccess: async (result) => {
|
||||
setFeedback({
|
||||
tone: 'success',
|
||||
message:
|
||||
result.deleted_count > 0
|
||||
? `已清理 ${result.deleted_count} 条健康事件日志。`
|
||||
: '当前没有可清理的健康事件日志。',
|
||||
});
|
||||
setHealthEventCleanupModalOpen(false);
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['node-observability', nodeId] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['dashboard', 'overview'] }),
|
||||
]);
|
||||
},
|
||||
onError: (error) => {
|
||||
setFeedback({ tone: 'danger', message: getErrorMessage(error) });
|
||||
},
|
||||
});
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!node) {
|
||||
return;
|
||||
@@ -1215,6 +1239,20 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
<AppCard
|
||||
title="健康事件时间线"
|
||||
description="保留活动与已恢复事件,帮助判断问题是持续中、间歇性还是已经恢复。"
|
||||
action={
|
||||
<DangerButton
|
||||
type="button"
|
||||
disabled={
|
||||
cleanupHealthEventsMutation.isPending ||
|
||||
!observability?.health_events.length
|
||||
}
|
||||
onClick={() => setHealthEventCleanupModalOpen(true)}
|
||||
>
|
||||
{cleanupHealthEventsMutation.isPending
|
||||
? '清理中...'
|
||||
: '清理日志'}
|
||||
</DangerButton>
|
||||
}
|
||||
>
|
||||
{observability?.health_events.length ? (
|
||||
<div className="space-y-4">
|
||||
@@ -1703,6 +1741,49 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
}}
|
||||
/>
|
||||
|
||||
<AppModal
|
||||
isOpen={isHealthEventCleanupModalOpen}
|
||||
onClose={() => setHealthEventCleanupModalOpen(false)}
|
||||
title="清理健康事件日志"
|
||||
description={
|
||||
node
|
||||
? `确认清理节点“${node.name}”的健康事件时间线吗?已清理的历史记录将立即从当前页面移除,后续只有新的节点上报才会再次出现。`
|
||||
: '确认清理当前节点的健康事件时间线吗?'
|
||||
}
|
||||
footer={
|
||||
<div className="flex flex-wrap justify-end gap-3">
|
||||
<SecondaryButton
|
||||
type="button"
|
||||
onClick={() => setHealthEventCleanupModalOpen(false)}
|
||||
>
|
||||
取消
|
||||
</SecondaryButton>
|
||||
<DangerButton
|
||||
type="button"
|
||||
disabled={cleanupHealthEventsMutation.isPending}
|
||||
onClick={() => {
|
||||
setFeedback(null);
|
||||
cleanupHealthEventsMutation.mutate();
|
||||
}}
|
||||
>
|
||||
{cleanupHealthEventsMutation.isPending ? '清理中...' : '确认清理'}
|
||||
</DangerButton>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{cleanupHealthEventsMutation.isError ? (
|
||||
<ErrorState
|
||||
title="健康事件清理失败"
|
||||
description={getErrorMessage(cleanupHealthEventsMutation.error)}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-3 text-sm text-[var(--foreground-secondary)]">
|
||||
<p>该操作会删除当前节点已记录的全部健康事件,包括活动中与已恢复事件。</p>
|
||||
<p>这不会影响节点后续继续上报新的健康事件,但现有时间线与相关摘要会立即刷新。</p>
|
||||
</div>
|
||||
)}
|
||||
</AppModal>
|
||||
|
||||
<AppModal
|
||||
isOpen={isAgentUpdateModalOpen}
|
||||
onClose={() => setIsAgentUpdateModalOpen(false)}
|
||||
|
||||
@@ -34,16 +34,16 @@ const defaultPerformanceFields = {
|
||||
OpenRestyWorkerProcesses: 'auto',
|
||||
OpenRestyWorkerConnections: '4096',
|
||||
OpenRestyWorkerRlimitNofile: '65535',
|
||||
OpenRestyEventsUse: '',
|
||||
OpenRestyEventsMultiAcceptEnabled: false,
|
||||
OpenRestyKeepaliveTimeout: '65',
|
||||
OpenRestyEventsUse: 'epoll',
|
||||
OpenRestyEventsMultiAcceptEnabled: true,
|
||||
OpenRestyKeepaliveTimeout: '20',
|
||||
OpenRestyKeepaliveRequests: '1000',
|
||||
OpenRestyClientHeaderTimeout: '15',
|
||||
OpenRestyClientBodyTimeout: '15',
|
||||
OpenRestyClientMaxBodySize: '64m',
|
||||
OpenRestyLargeClientHeaderBuffers: '4 16k',
|
||||
OpenRestySendTimeout: '30',
|
||||
OpenRestyProxyConnectTimeout: '5',
|
||||
OpenRestyProxyConnectTimeout: '3',
|
||||
OpenRestyProxySendTimeout: '60',
|
||||
OpenRestyProxyReadTimeout: '60',
|
||||
OpenRestyWebsocketEnabled: true,
|
||||
@@ -55,13 +55,12 @@ const defaultPerformanceFields = {
|
||||
OpenRestyGzipEnabled: true,
|
||||
OpenRestyGzipMinLength: '1024',
|
||||
OpenRestyGzipCompLevel: '5',
|
||||
OpenRestyResolvers: '',
|
||||
OpenRestyCacheEnabled: false,
|
||||
OpenRestyCachePath: '',
|
||||
OpenRestyCacheLevels: '1:2',
|
||||
OpenRestyCacheInactive: '30m',
|
||||
OpenRestyCacheMaxSize: '1g',
|
||||
OpenRestyCacheKeyTemplate: '$scheme$proxy_host$request_uri',
|
||||
OpenRestyCacheKeyTemplate: '$scheme$host$request_uri',
|
||||
OpenRestyCacheLockEnabled: true,
|
||||
OpenRestyCacheLockTimeout: '5s',
|
||||
OpenRestyCacheUseStale:
|
||||
@@ -76,9 +75,9 @@ const performanceFieldTooltips: Record<string, string> = {
|
||||
worker_rlimit_nofile:
|
||||
'提升 worker 可打开的文件描述符上限,避免高并发下连接或文件句柄不足。',
|
||||
events_use:
|
||||
'指定事件驱动模型。Linux 常见是 epoll,留空时由 OpenResty 自动选择。',
|
||||
'指定事件驱动模型。默认使用 epoll,Linux 高并发场景通常优先选择它。',
|
||||
multi_accept:
|
||||
'开启后,worker 会尽可能一次接受多个新连接,适合高吞吐接入场景。',
|
||||
'默认开启。worker 会尽可能一次接受多个新连接,适合高吞吐接入场景。',
|
||||
keepalive_timeout: '客户端 Keep-Alive 空闲保持时间,单位秒。',
|
||||
keepalive_requests: '单个长连接允许复用的最大请求数。',
|
||||
client_header_timeout: '读取客户端请求头的超时时间,单位秒。',
|
||||
@@ -104,8 +103,6 @@ const performanceFieldTooltips: Record<string, string> = {
|
||||
gzip_min_length:
|
||||
'只有响应体超过该字节数时才会启用 gzip,避免对极小响应做无意义压缩。',
|
||||
gzip_comp_level: 'gzip 压缩等级,1 更省 CPU,9 压缩更高但更耗 CPU。',
|
||||
resolvers:
|
||||
'可选填写运行时 DNS 解析器 IP,支持逗号、空格或换行分隔;留空时不额外生成 resolver 指令。',
|
||||
proxy_cache_path: '缓存目录路径,对应 proxy_cache_path 指令中的磁盘位置。',
|
||||
levels: '缓存目录层级,例如 1:2,可控制缓存文件的目录分布。',
|
||||
inactive: '缓存对象在未命中访问时的失活时间,例如 30m。',
|
||||
@@ -206,12 +203,12 @@ export function PerformancePage() {
|
||||
optionMap.OpenRestyWorkerConnections ?? '4096',
|
||||
OpenRestyWorkerRlimitNofile:
|
||||
optionMap.OpenRestyWorkerRlimitNofile ?? '65535',
|
||||
OpenRestyEventsUse: optionMap.OpenRestyEventsUse ?? '',
|
||||
OpenRestyEventsUse: optionMap.OpenRestyEventsUse ?? 'epoll',
|
||||
OpenRestyEventsMultiAcceptEnabled: toBoolean(
|
||||
optionMap.OpenRestyEventsMultiAcceptEnabled,
|
||||
false,
|
||||
true,
|
||||
),
|
||||
OpenRestyKeepaliveTimeout: optionMap.OpenRestyKeepaliveTimeout ?? '65',
|
||||
OpenRestyKeepaliveTimeout: optionMap.OpenRestyKeepaliveTimeout ?? '20',
|
||||
OpenRestyKeepaliveRequests:
|
||||
optionMap.OpenRestyKeepaliveRequests ?? '1000',
|
||||
OpenRestyClientHeaderTimeout:
|
||||
@@ -222,7 +219,7 @@ export function PerformancePage() {
|
||||
optionMap.OpenRestyLargeClientHeaderBuffers ?? '4 16k',
|
||||
OpenRestySendTimeout: optionMap.OpenRestySendTimeout ?? '30',
|
||||
OpenRestyProxyConnectTimeout:
|
||||
optionMap.OpenRestyProxyConnectTimeout ?? '5',
|
||||
optionMap.OpenRestyProxyConnectTimeout ?? '3',
|
||||
OpenRestyProxySendTimeout: optionMap.OpenRestyProxySendTimeout ?? '60',
|
||||
OpenRestyProxyReadTimeout: optionMap.OpenRestyProxyReadTimeout ?? '60',
|
||||
OpenRestyWebsocketEnabled: toBoolean(
|
||||
@@ -244,14 +241,13 @@ export function PerformancePage() {
|
||||
OpenRestyGzipEnabled: toBoolean(optionMap.OpenRestyGzipEnabled, true),
|
||||
OpenRestyGzipMinLength: optionMap.OpenRestyGzipMinLength ?? '1024',
|
||||
OpenRestyGzipCompLevel: optionMap.OpenRestyGzipCompLevel ?? '5',
|
||||
OpenRestyResolvers: optionMap.OpenRestyResolvers ?? '',
|
||||
OpenRestyCacheEnabled: toBoolean(optionMap.OpenRestyCacheEnabled, false),
|
||||
OpenRestyCachePath: optionMap.OpenRestyCachePath ?? '',
|
||||
OpenRestyCacheLevels: optionMap.OpenRestyCacheLevels ?? '1:2',
|
||||
OpenRestyCacheInactive: optionMap.OpenRestyCacheInactive ?? '30m',
|
||||
OpenRestyCacheMaxSize: optionMap.OpenRestyCacheMaxSize ?? '1g',
|
||||
OpenRestyCacheKeyTemplate:
|
||||
optionMap.OpenRestyCacheKeyTemplate ?? '$scheme$proxy_host$request_uri',
|
||||
optionMap.OpenRestyCacheKeyTemplate ?? '$scheme$host$request_uri',
|
||||
OpenRestyCacheLockEnabled: toBoolean(
|
||||
optionMap.OpenRestyCacheLockEnabled,
|
||||
true,
|
||||
@@ -424,7 +420,6 @@ export function PerformancePage() {
|
||||
'OpenRestyProxyReadTimeout',
|
||||
performanceFields.OpenRestyProxyReadTimeout.trim(),
|
||||
],
|
||||
['OpenRestyResolvers', performanceFields.OpenRestyResolvers.trim()],
|
||||
[
|
||||
'OpenRestyWebsocketEnabled',
|
||||
String(performanceFields.OpenRestyWebsocketEnabled),
|
||||
@@ -943,23 +938,6 @@ export function PerformancePage() {
|
||||
}
|
||||
/>
|
||||
</ResourceField>
|
||||
<ResourceField
|
||||
label="resolver"
|
||||
tooltip={performanceFieldTooltips.resolvers}
|
||||
hint="留空时走 OpenResty 默认行为;填写时请使用 DNS 服务器 IP。"
|
||||
>
|
||||
<ResourceTextarea
|
||||
value={performanceFields.OpenRestyResolvers}
|
||||
onChange={(event) =>
|
||||
setPerformanceFields((previous) => ({
|
||||
...previous,
|
||||
OpenRestyResolvers: event.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder="例如:10.0.0.2, 1.1.1.1"
|
||||
rows={3}
|
||||
/>
|
||||
</ResourceField>
|
||||
<ToggleField
|
||||
label="websocket"
|
||||
tooltip={performanceFieldTooltips.websocket}
|
||||
|
||||
@@ -50,6 +50,8 @@ const customHeaderSchema = z.object({
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
const cachePolicyValues = ['url', 'suffix', 'path_prefix', 'path_exact'] as const;
|
||||
|
||||
const proxyRouteSchema = z
|
||||
.object({
|
||||
domain: z.string().trim().min(1, '请输入域名'),
|
||||
@@ -87,10 +89,14 @@ const proxyRouteSchema = z
|
||||
})()),
|
||||
'请输入合法的回源主机名',
|
||||
),
|
||||
upstreams_text: z.string(),
|
||||
enabled: z.boolean(),
|
||||
enable_https: z.boolean(),
|
||||
cert_id: z.string(),
|
||||
redirect_http: z.boolean(),
|
||||
cache_enabled: z.boolean(),
|
||||
cache_policy: z.enum(cachePolicyValues),
|
||||
cache_rules_text: z.string(),
|
||||
custom_headers: z.array(customHeaderSchema).min(1),
|
||||
remark: z.string().max(255, '备注不能超过 255 个字符'),
|
||||
})
|
||||
@@ -103,6 +109,26 @@ const proxyRouteSchema = z
|
||||
});
|
||||
}
|
||||
|
||||
const upstreams = parseUpstreamsText(value.origin_url, value.upstreams_text);
|
||||
if (upstreams.length === 0) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['origin_url'],
|
||||
message: '至少需要一个上游地址',
|
||||
});
|
||||
}
|
||||
|
||||
if (value.cache_enabled) {
|
||||
const cacheRules = parseCacheRulesText(value.cache_rules_text);
|
||||
if (value.cache_policy !== 'url' && cacheRules.length === 0) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['cache_rules_text'],
|
||||
message: '当前缓存策略至少需要填写一条规则',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
value.custom_headers.forEach((header, index) => {
|
||||
const key = header.key.trim();
|
||||
const headerValue = header.value.trim();
|
||||
@@ -148,10 +174,14 @@ const defaultValues: ProxyRouteFormValues = {
|
||||
domain: '',
|
||||
origin_url: '',
|
||||
origin_host: '',
|
||||
upstreams_text: '',
|
||||
enabled: true,
|
||||
enable_https: false,
|
||||
cert_id: '',
|
||||
redirect_http: false,
|
||||
cache_enabled: false,
|
||||
cache_policy: 'url',
|
||||
cache_rules_text: '',
|
||||
custom_headers: [{ key: '', value: '' }],
|
||||
remark: '',
|
||||
};
|
||||
@@ -195,6 +225,71 @@ function parseCustomHeaders(rawValue: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseCacheRules(rawValue: string) {
|
||||
if (!rawValue) {
|
||||
return [] as string[];
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawValue) as string[];
|
||||
return Array.isArray(parsed) ? parsed.filter(Boolean) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function parseCacheRulesText(value: string) {
|
||||
return value
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseUpstreams(rawValue: string) {
|
||||
if (!rawValue) {
|
||||
return [] as string[];
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawValue) as string[];
|
||||
return Array.isArray(parsed) ? parsed.filter(Boolean) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function parseUpstreamsText(primary: string, value: string) {
|
||||
return [primary.trim(), ...value.split(/\r?\n/)]
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function buildCachePolicyLabel(policy: string) {
|
||||
switch (policy) {
|
||||
case 'suffix':
|
||||
return '按后缀';
|
||||
case 'path_prefix':
|
||||
return '按前缀';
|
||||
case 'path_exact':
|
||||
return '按路径';
|
||||
default:
|
||||
return '按 URL';
|
||||
}
|
||||
}
|
||||
|
||||
function getCacheRulesHint(policy: string) {
|
||||
switch (policy) {
|
||||
case 'suffix':
|
||||
return '每行一个后缀,例如:jpg、css、js。';
|
||||
case 'path_prefix':
|
||||
return '每行一个路径前缀,例如:/assets、/static/images。';
|
||||
case 'path_exact':
|
||||
return '每行一个精确路径,例如:/robots.txt、/manifest.json。';
|
||||
default:
|
||||
return '按 URL 缓存时无需额外规则,系统会按请求 URL 粒度缓存。';
|
||||
}
|
||||
}
|
||||
|
||||
function buildCertificateLabel(certificate: TlsCertificateItem) {
|
||||
return certificate.not_after
|
||||
? `${certificate.name}(到期:${formatDateTime(certificate.not_after)})`
|
||||
@@ -206,11 +301,17 @@ function toPayload(values: ProxyRouteFormValues): ProxyRouteMutationPayload {
|
||||
domain: values.domain.trim(),
|
||||
origin_url: values.origin_url.trim(),
|
||||
origin_host: values.origin_host.trim(),
|
||||
upstreams: parseUpstreamsText(values.origin_url, values.upstreams_text).slice(1),
|
||||
enabled: values.enabled,
|
||||
enable_https: values.enable_https,
|
||||
cert_id:
|
||||
values.enable_https && values.cert_id ? Number(values.cert_id) : null,
|
||||
redirect_http: values.enable_https ? values.redirect_http : false,
|
||||
cache_enabled: values.cache_enabled,
|
||||
cache_policy: values.cache_enabled ? values.cache_policy : 'url',
|
||||
cache_rules: values.cache_enabled
|
||||
? parseCacheRulesText(values.cache_rules_text)
|
||||
: [],
|
||||
custom_headers: values.custom_headers
|
||||
.map((item) => ({ key: item.key.trim(), value: item.value.trim() }))
|
||||
.filter((item) => item.key || item.value),
|
||||
@@ -220,15 +321,21 @@ function toPayload(values: ProxyRouteFormValues): ProxyRouteMutationPayload {
|
||||
|
||||
function toFormValues(route: ProxyRouteItem): ProxyRouteFormValues {
|
||||
const headers = parseCustomHeaders(route.custom_headers);
|
||||
const cacheRules = parseCacheRules(route.cache_rules);
|
||||
const upstreams = parseUpstreams(route.upstreams);
|
||||
|
||||
return {
|
||||
domain: route.domain,
|
||||
origin_url: route.origin_url,
|
||||
origin_host: route.origin_host || '',
|
||||
upstreams_text: upstreams.slice(1).join('\n'),
|
||||
enabled: route.enabled,
|
||||
enable_https: route.enable_https,
|
||||
cert_id: route.cert_id ? String(route.cert_id) : '',
|
||||
redirect_http: route.redirect_http,
|
||||
cache_enabled: route.cache_enabled,
|
||||
cache_policy: (route.cache_policy || 'url') as ProxyRouteFormValues['cache_policy'],
|
||||
cache_rules_text: cacheRules.join('\n'),
|
||||
custom_headers: headers.length > 0 ? headers : [{ key: '', value: '' }],
|
||||
remark: route.remark || '',
|
||||
};
|
||||
@@ -288,6 +395,14 @@ export function ProxyRoutesPage() {
|
||||
control: form.control,
|
||||
name: 'redirect_http',
|
||||
});
|
||||
const watchedCacheEnabled = useWatch({
|
||||
control: form.control,
|
||||
name: 'cache_enabled',
|
||||
});
|
||||
const watchedCachePolicy = useWatch({
|
||||
control: form.control,
|
||||
name: 'cache_policy',
|
||||
});
|
||||
const watchedCertId = useWatch({ control: form.control, name: 'cert_id' });
|
||||
|
||||
const routesQuery = useQuery({
|
||||
@@ -514,6 +629,7 @@ export function ProxyRoutesPage() {
|
||||
<th className="px-3 py-3 font-medium">域名</th>
|
||||
<th className="px-3 py-3 font-medium">源站地址</th>
|
||||
<th className="px-3 py-3 font-medium">HTTPS</th>
|
||||
<th className="px-3 py-3 font-medium">缓存</th>
|
||||
<th className="px-3 py-3 font-medium">请求头</th>
|
||||
<th className="px-3 py-3 font-medium">状态</th>
|
||||
<th className="px-3 py-3 font-medium">备注</th>
|
||||
@@ -524,6 +640,8 @@ export function ProxyRoutesPage() {
|
||||
<tbody className="divide-y divide-[var(--border-default)]">
|
||||
{routes.map((route) => {
|
||||
const headers = parseCustomHeaders(route.custom_headers);
|
||||
const cacheRules = parseCacheRules(route.cache_rules);
|
||||
const upstreams = parseUpstreams(route.upstreams);
|
||||
|
||||
return (
|
||||
<tr key={route.id} className="align-top">
|
||||
@@ -536,6 +654,9 @@ export function ProxyRoutesPage() {
|
||||
<p className="text-xs text-[var(--foreground-muted)]">
|
||||
回源主机名: {route.origin_host || '$host'}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--foreground-muted)]">
|
||||
上游数量: {Math.max(upstreams.length, 1)}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-4">
|
||||
@@ -554,6 +675,23 @@ export function ProxyRoutesPage() {
|
||||
<StatusBadge label="HTTP" variant="warning" />
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-4">
|
||||
{route.cache_enabled ? (
|
||||
<div className="space-y-2">
|
||||
<StatusBadge
|
||||
label={buildCachePolicyLabel(route.cache_policy)}
|
||||
variant="success"
|
||||
/>
|
||||
<p className="text-xs text-[var(--foreground-muted)]">
|
||||
{cacheRules.length > 0
|
||||
? `${cacheRules.length} 条规则`
|
||||
: '按 URL 粒度缓存'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<StatusBadge label="关闭" variant="warning" />
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-4">
|
||||
<StatusBadge
|
||||
label={
|
||||
@@ -669,6 +807,17 @@ export function ProxyRoutesPage() {
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<ResourceField
|
||||
label="附加上游"
|
||||
hint="可选。每行一个上游地址,用于同一规则下的负载均衡;需与主上游保持相同协议,且不能带路径或查询参数。"
|
||||
error={form.formState.errors.upstreams_text?.message}
|
||||
>
|
||||
<ResourceTextarea
|
||||
placeholder={'https://origin-b.internal\nhttps://origin-c.internal'}
|
||||
{...form.register('upstreams_text')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<ToggleField
|
||||
label="启用规则"
|
||||
@@ -739,6 +888,74 @@ export function ProxyRoutesPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[0.8fr_1.2fr]">
|
||||
<ToggleField
|
||||
label="启用规则缓存"
|
||||
description="仅对当前规则生效;系统会自动绕过非 GET、Authorization 和常见登录态 Cookie 请求。"
|
||||
checked={watchedCacheEnabled}
|
||||
onChange={(checked) => {
|
||||
form.setValue('cache_enabled', checked, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
if (!checked) {
|
||||
form.setValue('cache_policy', 'url', {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
form.setValue('cache_rules_text', '', {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<ResourceField
|
||||
label="缓存策略"
|
||||
hint="按 URL 会缓存所有符合安全条件的 URL;其余策略会先匹配规则再决定是否缓存。"
|
||||
>
|
||||
<ResourceSelect
|
||||
value={watchedCachePolicy}
|
||||
disabled={!watchedCacheEnabled}
|
||||
onChange={(event) =>
|
||||
form.setValue(
|
||||
'cache_policy',
|
||||
event.target.value as ProxyRouteFormValues['cache_policy'],
|
||||
{
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="url">按 URL 缓存</option>
|
||||
<option value="suffix">按后缀匹配缓存</option>
|
||||
<option value="path_prefix">按路径前缀缓存</option>
|
||||
<option value="path_exact">按精确路径缓存</option>
|
||||
</ResourceSelect>
|
||||
</ResourceField>
|
||||
</div>
|
||||
|
||||
<ResourceField
|
||||
label="缓存规则"
|
||||
hint={getCacheRulesHint(watchedCachePolicy)}
|
||||
error={form.formState.errors.cache_rules_text?.message}
|
||||
>
|
||||
<ResourceTextarea
|
||||
placeholder={
|
||||
watchedCachePolicy === 'suffix'
|
||||
? 'jpg\ncss\njs'
|
||||
: watchedCachePolicy === 'path_prefix'
|
||||
? '/assets\n/static/images'
|
||||
: watchedCachePolicy === 'path_exact'
|
||||
? '/robots.txt\n/manifest.json'
|
||||
: '按 URL 缓存无需填写规则'
|
||||
}
|
||||
disabled={!watchedCacheEnabled || watchedCachePolicy === 'url'}
|
||||
{...form.register('cache_rules_text')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
|
||||
@@ -3,32 +3,40 @@ export interface ProxyRouteCustomHeader {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface ProxyRouteItem {
|
||||
id: number;
|
||||
domain: string;
|
||||
origin_url: string;
|
||||
origin_host: string;
|
||||
enabled: boolean;
|
||||
enable_https: boolean;
|
||||
cert_id: number | null;
|
||||
redirect_http: boolean;
|
||||
custom_headers: string;
|
||||
remark: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
export interface ProxyRouteItem {
|
||||
id: number;
|
||||
domain: string;
|
||||
origin_url: string;
|
||||
origin_host: string;
|
||||
upstreams: string;
|
||||
enabled: boolean;
|
||||
enable_https: boolean;
|
||||
cert_id: number | null;
|
||||
redirect_http: boolean;
|
||||
cache_enabled: boolean;
|
||||
cache_policy: string;
|
||||
cache_rules: string;
|
||||
custom_headers: string;
|
||||
remark: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ProxyRouteMutationPayload {
|
||||
domain: string;
|
||||
origin_url: string;
|
||||
origin_host: string;
|
||||
enabled: boolean;
|
||||
enable_https: boolean;
|
||||
cert_id: number | null;
|
||||
redirect_http: boolean;
|
||||
custom_headers: ProxyRouteCustomHeader[];
|
||||
remark: string;
|
||||
}
|
||||
origin_url: string;
|
||||
origin_host: string;
|
||||
upstreams: string[];
|
||||
enabled: boolean;
|
||||
enable_https: boolean;
|
||||
cert_id: number | null;
|
||||
redirect_http: boolean;
|
||||
cache_enabled: boolean;
|
||||
cache_policy: string;
|
||||
cache_rules: string[];
|
||||
custom_headers: ProxyRouteCustomHeader[];
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface TlsCertificateItem {
|
||||
id: number;
|
||||
|
||||
@@ -78,14 +78,14 @@ const defaultOperationFields = {
|
||||
OpenRestyWorkerProcesses: 'auto',
|
||||
OpenRestyWorkerConnections: '4096',
|
||||
OpenRestyWorkerRlimitNofile: '65535',
|
||||
OpenRestyEventsUse: '',
|
||||
OpenRestyEventsMultiAcceptEnabled: false,
|
||||
OpenRestyKeepaliveTimeout: '65',
|
||||
OpenRestyEventsUse: 'epoll',
|
||||
OpenRestyEventsMultiAcceptEnabled: true,
|
||||
OpenRestyKeepaliveTimeout: '20',
|
||||
OpenRestyKeepaliveRequests: '1000',
|
||||
OpenRestyClientHeaderTimeout: '15',
|
||||
OpenRestyClientBodyTimeout: '15',
|
||||
OpenRestySendTimeout: '30',
|
||||
OpenRestyProxyConnectTimeout: '5',
|
||||
OpenRestyProxyConnectTimeout: '3',
|
||||
OpenRestyProxySendTimeout: '60',
|
||||
OpenRestyProxyReadTimeout: '60',
|
||||
OpenRestyProxyBufferingEnabled: true,
|
||||
@@ -100,7 +100,7 @@ const defaultOperationFields = {
|
||||
OpenRestyCacheLevels: '1:2',
|
||||
OpenRestyCacheInactive: '30m',
|
||||
OpenRestyCacheMaxSize: '1g',
|
||||
OpenRestyCacheKeyTemplate: '$scheme$proxy_host$request_uri',
|
||||
OpenRestyCacheKeyTemplate: '$scheme$host$request_uri',
|
||||
OpenRestyCacheLockEnabled: true,
|
||||
OpenRestyCacheLockTimeout: '5s',
|
||||
OpenRestyCacheUseStale:
|
||||
@@ -348,12 +348,12 @@ export function SettingsPage() {
|
||||
optionMap.OpenRestyWorkerConnections ?? '4096',
|
||||
OpenRestyWorkerRlimitNofile:
|
||||
optionMap.OpenRestyWorkerRlimitNofile ?? '65535',
|
||||
OpenRestyEventsUse: optionMap.OpenRestyEventsUse ?? '',
|
||||
OpenRestyEventsUse: optionMap.OpenRestyEventsUse ?? 'epoll',
|
||||
OpenRestyEventsMultiAcceptEnabled: toBoolean(
|
||||
optionMap.OpenRestyEventsMultiAcceptEnabled,
|
||||
false,
|
||||
true,
|
||||
),
|
||||
OpenRestyKeepaliveTimeout: optionMap.OpenRestyKeepaliveTimeout ?? '65',
|
||||
OpenRestyKeepaliveTimeout: optionMap.OpenRestyKeepaliveTimeout ?? '20',
|
||||
OpenRestyKeepaliveRequests:
|
||||
optionMap.OpenRestyKeepaliveRequests ?? '1000',
|
||||
OpenRestyClientHeaderTimeout:
|
||||
@@ -361,7 +361,7 @@ export function SettingsPage() {
|
||||
OpenRestyClientBodyTimeout: optionMap.OpenRestyClientBodyTimeout ?? '15',
|
||||
OpenRestySendTimeout: optionMap.OpenRestySendTimeout ?? '30',
|
||||
OpenRestyProxyConnectTimeout:
|
||||
optionMap.OpenRestyProxyConnectTimeout ?? '5',
|
||||
optionMap.OpenRestyProxyConnectTimeout ?? '3',
|
||||
OpenRestyProxySendTimeout: optionMap.OpenRestyProxySendTimeout ?? '60',
|
||||
OpenRestyProxyReadTimeout: optionMap.OpenRestyProxyReadTimeout ?? '60',
|
||||
OpenRestyProxyBufferingEnabled: toBoolean(
|
||||
@@ -381,7 +381,7 @@ export function SettingsPage() {
|
||||
OpenRestyCacheInactive: optionMap.OpenRestyCacheInactive ?? '30m',
|
||||
OpenRestyCacheMaxSize: optionMap.OpenRestyCacheMaxSize ?? '1g',
|
||||
OpenRestyCacheKeyTemplate:
|
||||
optionMap.OpenRestyCacheKeyTemplate ?? '$scheme$proxy_host$request_uri',
|
||||
optionMap.OpenRestyCacheKeyTemplate ?? '$scheme$host$request_uri',
|
||||
OpenRestyCacheLockEnabled: toBoolean(
|
||||
optionMap.OpenRestyCacheLockEnabled,
|
||||
true,
|
||||
|
||||
Reference in New Issue
Block a user