备份、隧道生命周期、日志、会话与设置项存在一批「静默失效」问题,本次一并收敛。 正确性: - 备份归档补上 session_secret 与 frp 配置。缺密钥时换机恢复后库里所有凭据都解不开, 界面表现为「配置都在、一执行就报解密失败」;同时支持口令加密(scrypt + AES-256-GCM)。 - 修复「立即备份」必失败:tar 头用的是遍历时的文件尺寸,而 logs、frpc 配置在打包期间 还在增长,读出的字节多于声明值导致 archive/tar 报错、整份备份作废。改为打开后重新 取尺寸并用 LimitReader 兜住,被截短时补零保持条目结构完整。 - 数据库改用 VACUUM INTO 生成一致性快照。直接打包正在写入的 SQLite 文件可能得到 结构完整但内容自相矛盾的副本,恢复后才暴露。 - Cloudflare 启动改用 StartAuto,Shutdown 显式 StopAll,子进程绑定应用 ctx。此前 重启会把用户手动停掉的隧道重新拉起,退出也可能留下孤儿进程。 - Nginx 访问/错误日志加轮转(200MB 阈值、gzip 归档、USR1 重开),读取改为从文件尾 分块倒读,并跨当日归档统计。此前日志只增不减,读接口每次全量扫描。 - 过期会话改由日任务清理;删除反代规则时同步清掉流量累计,避免同名规则重建继承旧读数。 - 启动加就绪门:Nginx bootstrap 完成后再放行 FRP 对账、Agent 隧道与 Cloudflare 自启。 设置项: - 新增设置项注册表(internal/settings/registry.go),白名单与默认值从它派生, 并记录每个键的消费者,防止再出现「界面能改、后端没人读」的黑洞设置。 - 接上三个此前不生效的设置项:timezone(启动与保存时应用到 time.Local)、 theme(后端为权威源,挂载时覆盖本地偏好、顶栏切换回写)、log_retention_days (控制日志归档保留天数)。 工程质量: - gofmt 全量格式化 23 个历史文件,CI 增加格式化门禁。 - 前端引入 ESLint(flat config)与 lint 脚本,CI 增加 lint 步骤;顺带修掉 logDisplay 的 let→const 与 LogsView 模板内直接改 prop 两处问题。 - 删除无引用的 pnpm-lock.yaml,prototype/ 加入忽略列表。 - 打包版本对齐:Docker manifest 同步到 2.0.0,CI 校验 VERSION 与 package.json 一致。 验证:gofmt 0 文件、go vet、go test ./...、npm run lint/typecheck/test/build 全绿。 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
package cloudflared
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/havline/havline/internal/config"
|
||||
"github.com/havline/havline/internal/db"
|
||||
"github.com/havline/havline/internal/secret"
|
||||
)
|
||||
|
||||
// newTestService 装配一个只依赖 SQLite 的 Service,cloudflared 二进制不存在时 Start 会失败,
|
||||
// 正好用来验证「哪些隧道会被尝试拉起」而不真的启动进程。
|
||||
func newTestService(t *testing.T) (*Service, *Store) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
conn, err := db.Open(filepath.Join(dir, "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { conn.Close() })
|
||||
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
box, err := secret.NewBox("cloudflared-lifecycle-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := NewStore(conn)
|
||||
svc := NewService(config.Config{DataDir: dir}, store, box, slog.New(slog.NewTextHandler(io.Discard, nil)), nil)
|
||||
if err := svc.EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return svc, store
|
||||
}
|
||||
|
||||
// createTunnel 直接落库造一条隧道,跳过需要 Cloudflare API 的 Create。
|
||||
func createTunnel(t *testing.T, store *Store, name string, autoStart bool) Tunnel {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
tunnel, err := store.Create(ctx, CreateInput{
|
||||
Name: name,
|
||||
Mode: ModeAccountLocal,
|
||||
Network: DefaultNetworkSettings(),
|
||||
AutoStart: autoStart,
|
||||
}, "11111111-1111-1111-1111-111111111111", "acc-tag", "", "",
|
||||
filepath.Join(dir, "config.yml"), filepath.Join(dir, "creds.json"), filepath.Join(dir, "cloudflared.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tunnel
|
||||
}
|
||||
|
||||
// TestStartAutoSkipsNonAutoStart:应用启动只应拉起 auto_start 的隧道。
|
||||
// 之前启动路径错用了 StartAll,用户手动停掉的隧道会在重启后自己回来。
|
||||
func TestStartAutoSkipsNonAutoStart(t *testing.T) {
|
||||
tunnels := []Tunnel{
|
||||
{ID: 1, Name: "自动", AutoStart: true},
|
||||
{ID: 2, Name: "手动", AutoStart: false},
|
||||
{ID: 3, Name: "也自动", AutoStart: true},
|
||||
}
|
||||
targets := autoStartTargets(tunnels)
|
||||
if len(targets) != 2 {
|
||||
t.Fatalf("应只挑出 2 条 auto_start 隧道,实际 %d:%#v", len(targets), targets)
|
||||
}
|
||||
for _, tunnel := range targets {
|
||||
if !tunnel.AutoStart {
|
||||
t.Fatalf("挑出了未勾选 auto_start 的隧道:%#v", tunnel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartAutoRespectsGlobalSwitch:全局总开关关闭时一条都不启动。
|
||||
func TestStartAutoRespectsGlobalSwitch(t *testing.T) {
|
||||
svc, store := newTestService(t)
|
||||
ctx := context.Background()
|
||||
tunnel := createTunnel(t, store, "自动", true)
|
||||
if _, err := svc.SetEnabled(ctx, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
svc.StartAuto(ctx)
|
||||
|
||||
got, err := store.Get(ctx, tunnel.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Status == "failed" {
|
||||
t.Fatalf("全局停用时不应尝试启动隧道,实际 %q", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStopAllMarksStopped:StopAll 应把所有隧道的运行态改写为 stopped,
|
||||
// 供应用退出与「全局停用」两条路径复用。
|
||||
func TestStopAllMarksStopped(t *testing.T) {
|
||||
svc, store := newTestService(t)
|
||||
ctx := context.Background()
|
||||
first := createTunnel(t, store, "一", true)
|
||||
second := createTunnel(t, store, "二", true)
|
||||
for _, id := range []int64{first.ID, second.ID} {
|
||||
if err := store.SetRuntime(ctx, id, "connected", "", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
svc.StopAll(ctx)
|
||||
|
||||
for _, id := range []int64{first.ID, second.ID} {
|
||||
got, err := store.Get(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Status != "stopped" {
|
||||
t.Fatalf("隧道 %d 应为 stopped,实际 %q", id, got.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestManagerStopIsIdempotent:没有子进程时 Stop 不应报错(退出路径会无差别调用)。
|
||||
func TestManagerStopIsIdempotent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
m := NewManager(config.Config{DataDir: dir}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err := m.Stop(42); err != nil {
|
||||
t.Fatalf("停止不存在的隧道不应报错:%v", err)
|
||||
}
|
||||
if status := m.Status(42); status.Status != "stopped" || status.Running {
|
||||
t.Fatalf("未运行的隧道状态应为 stopped:%#v", status)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package cloudflared
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
@@ -35,12 +36,31 @@ type Manager struct {
|
||||
logger *slog.Logger
|
||||
mu sync.Mutex
|
||||
processes map[int64]*processState
|
||||
// baseCtx 是应用级 ctx:应用退出时用它连带结束未显式 Stop 的子进程。
|
||||
// 不能用请求 ctx——HTTP 请求一结束子进程就会被杀掉。
|
||||
baseCtx context.Context
|
||||
}
|
||||
|
||||
func NewManager(cfg config.Config, logger *slog.Logger) *Manager {
|
||||
return &Manager{cfg: cfg, logger: logger, processes: map[int64]*processState{}}
|
||||
}
|
||||
|
||||
// SetBaseContext 注入应用级 ctx,供子进程生命周期绑定。
|
||||
func (m *Manager) SetBaseContext(ctx context.Context) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.baseCtx = ctx
|
||||
}
|
||||
|
||||
func (m *Manager) lifecycleContext() context.Context {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.baseCtx == nil {
|
||||
return context.Background()
|
||||
}
|
||||
return m.baseCtx
|
||||
}
|
||||
|
||||
func buildRunArgs(tunnel Tunnel, configPath, token string) []string {
|
||||
args := []string{"tunnel"}
|
||||
if tunnel.Mode == ModeTokenRemote {
|
||||
@@ -116,7 +136,7 @@ func (m *Manager) Start(tunnel Tunnel, binaryPath, configPath, token string) err
|
||||
m.remove(tunnel.ID)
|
||||
return err
|
||||
}
|
||||
cmd := exec.Command(binaryPath, buildRunArgs(tunnel, configPath, token)...)
|
||||
cmd := exec.CommandContext(m.lifecycleContext(), binaryPath, buildRunArgs(tunnel, configPath, token)...)
|
||||
cmd.Env = buildEnv(tunnel.Network)
|
||||
cmd.SysProcAttr = hideWindowAttr()
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
|
||||
@@ -47,6 +47,11 @@ func (s *Service) EnsureDirs() error {
|
||||
return os.MkdirAll(filepath.Join(s.cfg.DataDir, "cloudflared", "bin"), 0o755)
|
||||
}
|
||||
|
||||
// SetBaseContext 注入应用级 ctx:应用退出时 cloudflared 子进程随之结束。
|
||||
func (s *Service) SetBaseContext(ctx context.Context) {
|
||||
s.manager.SetBaseContext(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context) ([]Tunnel, error) {
|
||||
items, err := s.store.List(ctx)
|
||||
if err != nil {
|
||||
@@ -752,6 +757,18 @@ func (s *Service) IngressCandidates(ctx context.Context) ([]string, error) {
|
||||
return hosts, nil
|
||||
}
|
||||
|
||||
// autoStartTargets 从隧道列表里挑出启动时应被拉起的隧道。
|
||||
// 单独抽出来是为了能用纯函数覆盖「只启动 auto_start」这条语义。
|
||||
func autoStartTargets(tunnels []Tunnel) []Tunnel {
|
||||
out := make([]Tunnel, 0, len(tunnels))
|
||||
for _, tunnel := range tunnels {
|
||||
if tunnel.AutoStart {
|
||||
out = append(out, tunnel)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// StartAuto 在应用启动时拉起标记了 auto_start 的隧道。
|
||||
func (s *Service) StartAuto(ctx context.Context) {
|
||||
settings, err := s.store.GetSettingsRaw(ctx)
|
||||
@@ -767,10 +784,7 @@ func (s *Service) StartAuto(ctx context.Context) {
|
||||
s.logger.Warn("读取 Cloudflare 隧道失败", "error", err.Error())
|
||||
return
|
||||
}
|
||||
for _, tunnel := range tunnels {
|
||||
if !tunnel.AutoStart {
|
||||
continue
|
||||
}
|
||||
for _, tunnel := range autoStartTargets(tunnels) {
|
||||
if _, err := s.Start(ctx, tunnel.ID); err != nil {
|
||||
s.logger.Warn("自动启动 Cloudflare 隧道失败", "tunnel_id", tunnel.ID, "error", err.Error())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user