From b86b7222cb0d5f36a53b6f04ef593bd1f5cf36b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=98=89=E4=BC=9F?= <8473136@qq.com> Date: Fri, 27 Mar 2026 17:27:53 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Cloudflare=20tunnel=20support.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/application/server/service.go | 14 - .../application/tunnel/cloudflare/provider.go | 229 +++++++++++++ .../service.go => tunnel/frp/provider.go} | 321 +++++++----------- internal/application/tunnel/provider.go | 26 ++ internal/application/tunnel/sse.go | 78 +++++ internal/domain/proxy/model.go | 2 +- internal/domain/proxy/repository.go | 1 + internal/domain/server/model.go | 7 - internal/domain/server/repository.go | 3 - internal/domain/tunnel/model.go | 9 + internal/domain/tunnel/repository.go | 8 + pkg/binary/manager.go | 170 ++++++++++ pkg/binary/resolver.go | 129 +++++++ 13 files changed, 772 insertions(+), 225 deletions(-) create mode 100644 internal/application/tunnel/cloudflare/provider.go rename internal/application/{frpc/service.go => tunnel/frp/provider.go} (50%) create mode 100644 internal/application/tunnel/provider.go create mode 100644 internal/application/tunnel/sse.go create mode 100644 internal/domain/tunnel/model.go create mode 100644 internal/domain/tunnel/repository.go create mode 100644 pkg/binary/manager.go create mode 100644 pkg/binary/resolver.go diff --git a/internal/application/server/service.go b/internal/application/server/service.go index 6d2b195..7f9388f 100644 --- a/internal/application/server/service.go +++ b/internal/application/server/service.go @@ -15,20 +15,6 @@ func NewService(app core.App, repo serverdomain.Repository) *Service { return &Service{app: app, repo: repo} } -func (s *Service) GetServerCountByStatus(status serverdomain.ServerStatus) (int64, error) { - return s.repo.CountByBootStatus(status) -} - -func (s *Service) UpdateServerBootStatus(serverID string, status serverdomain.ServerStatus) error { - return s.repo.UpdateBootStatus(serverID, status) -} - -func (s *Service) ResetAllServerStatus() { - if err := s.repo.ResetAllBootStatus(); err != nil { - s.app.Logger().Error("ResetAllServerStatus failed", "error", err) - } -} - func (s *Service) GetMaxLatency() (int64, error) { return s.repo.GetMaxLatency() } diff --git a/internal/application/tunnel/cloudflare/provider.go b/internal/application/tunnel/cloudflare/provider.go new file mode 100644 index 0000000..f8e52e0 --- /dev/null +++ b/internal/application/tunnel/cloudflare/provider.go @@ -0,0 +1,229 @@ +// Package cloudflare manages cloudflared daemon processes, one per integration. +// It implements tunnel.Provider. +package cloudflare + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "sync" + "time" + + "podux/internal/application/integration" + "podux/internal/application/tunnel" + proxydomain "podux/internal/domain/proxy" + tunneldomain "podux/internal/domain/tunnel" + "podux/pkg/binary" + + "github.com/pocketbase/pocketbase/core" +) + +// Provider manages cloudflared tunnel daemon processes, one per integration. +// It implements tunnel.Provider. +type Provider struct { + app core.App + proxyRepo proxydomain.Repository + tunnelRepo tunneldomain.Repository + mu sync.RWMutex + processes map[string]*os.Process + cancelFns map[string]context.CancelFunc +} + +func NewProvider(app core.App, proxyRepo proxydomain.Repository, tunnelRepo tunneldomain.Repository) *Provider { + return &Provider{ + app: app, + proxyRepo: proxyRepo, + tunnelRepo: tunnelRepo, + processes: make(map[string]*os.Process), + cancelFns: make(map[string]context.CancelFunc), + } +} + +func (p *Provider) logDir(id string) string { + return filepath.Join("pb_data", "cloudflare", id) +} + +func (p *Provider) logPath(id string) string { + return filepath.Join(p.logDir(id), "cloudflared.log") +} + +// Launch starts cloudflared for the given integration ID. Implements tunnel.Provider. +func (p *Provider) Launch(id string) error { + if p.IsRunning(id) { + return fmt.Errorf("cloudflared already running for integration %s", id) + } + + p.app.Logger().Info("launching cloudflared", "integrationId", id) + + // 1. Load integration record and tunnel token from metadata. + record, err := p.app.FindRecordById("fh_integrations", id) + if err != nil { + return fmt.Errorf("find integration: %w", err) + } + + var meta integration.IntegrationMeta + if rawMeta := record.Get("metadata"); rawMeta != nil { + b, _ := json.Marshal(rawMeta) + _ = json.Unmarshal(b, &meta) + } + if meta.Tunnel == nil || meta.Tunnel.Token == "" { + return fmt.Errorf("integration %s has no tunnel token; create a cloudflare proxy first", id) + } + token := meta.Tunnel.Token + + // 2. Ensure cloudflared binary is installed. + binDir, err := binary.DefaultBinDir() + if err != nil { + return fmt.Errorf("resolve bin dir: %w", err) + } + mgr := binary.New("cloudflared", "latest", binDir) + installCtx, installCancel := context.WithTimeout(context.Background(), 120*time.Second) + defer installCancel() + if err := mgr.EnsureInstalled(installCtx); err != nil { + return fmt.Errorf("install cloudflared: %w", err) + } + + // 3. Prepare log file. + if err := os.MkdirAll(p.logDir(id), 0755); err != nil { + return fmt.Errorf("create log dir: %w", err) + } + logFile, err := os.OpenFile(p.logPath(id), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) + if err != nil { + return fmt.Errorf("open log file: %w", err) + } + + // 4. Start cloudflared process. + runCtx, runCancel := context.WithCancel(context.Background()) + cmd := exec.CommandContext(runCtx, mgr.GetPath(), "tunnel", "--no-autoupdate", "run", "--token", token) + cmd.Stdout = logFile + cmd.Stderr = logFile + + if err := cmd.Start(); err != nil { + runCancel() + logFile.Close() + return fmt.Errorf("start cloudflared: %w", err) + } + + p.mu.Lock() + p.processes[id] = cmd.Process + p.cancelFns[id] = runCancel + p.mu.Unlock() + + p.app.Logger().Info("cloudflared started", "integrationId", id, "pid", cmd.Process.Pid) + + // 5. Monitor process exit and update statuses. + go func() { + defer logFile.Close() + if err := cmd.Wait(); err != nil && runCtx.Err() == nil { + p.app.Logger().Error("cloudflared exited unexpectedly", "integrationId", id, "error", err) + } else { + p.app.Logger().Info("cloudflared stopped", "integrationId", id) + } + p.cleanup(id) + }() + + // Mark tunnel active and proxies online after a brief startup window. + go func() { + time.Sleep(3 * time.Second) + if p.IsRunning(id) { + p.tunnelRepo.UpdateStatusByIntegrationID(id, tunneldomain.TunnelStatusActive) + p.proxyRepo.UpdateBootStatusByIntegrationID(id, proxydomain.ProxyBootStatusOnline) + } + }() + + return nil +} + +// Terminate stops the cloudflared process for the given integration ID. Implements tunnel.Provider. +func (p *Provider) Terminate(id string) error { + p.app.Logger().Info("terminating cloudflared", "integrationId", id) + + p.mu.RLock() + cancel, exists := p.cancelFns[id] + p.mu.RUnlock() + if !exists { + return nil + } + + cancel() + p.app.Logger().Info("cloudflared stop signal sent", "integrationId", id) + return nil +} + +// Reload is a no-op for cloudflared: tunnels with config_src=cloudflare +// automatically poll for ingress changes from the Cloudflare API. +// Implements tunnel.Provider. +func (p *Provider) Reload(id string) error { + p.app.Logger().Debug("cloudflare tunnel reload is a no-op (cloudflare-managed config)", "integrationId", id) + return nil +} + +// IsRunning reports whether cloudflared is running for the given integration. Implements tunnel.Provider. +func (p *Provider) IsRunning(id string) bool { + p.mu.RLock() + _, exists := p.processes[id] + p.mu.RUnlock() + return exists +} + +// AutoStart starts cloudflared for all active integrations that have a tunnel token. +// Implements tunnel.Provider. +func (p *Provider) AutoStart() { + p.app.Logger().Info("waiting 10s before auto-starting cloudflare tunnels") + time.Sleep(10 * time.Second) + + records, err := p.app.FindRecordsByFilter( + "fh_integrations", + `integrationsType = "cloudflare" && status = "active"`, + "-created", 0, 0, nil, + ) + if err != nil { + p.app.Logger().Error("cloudflare auto-start: failed to list integrations", "error", err) + return + } + + count := 0 + for _, record := range records { + var meta integration.IntegrationMeta + if rawMeta := record.Get("metadata"); rawMeta != nil { + b, _ := json.Marshal(rawMeta) + _ = json.Unmarshal(b, &meta) + } + if meta.Tunnel == nil || meta.Tunnel.Token == "" { + continue + } + + integrationId := record.Id + p.app.Logger().Info("auto-starting cloudflare tunnel", "integrationId", integrationId) + + go func(id string, delay int) { + time.Sleep(time.Duration(delay) * 500 * time.Millisecond) + if err := p.Launch(id); err != nil { + p.app.Logger().Error("cloudflare auto-start failed", "integrationId", id, "error", err) + } + }(integrationId, count) + + count++ + time.Sleep(1 * time.Second) + } + + p.app.Logger().Info("cloudflare auto-start initiated", "count", count) +} + +// StreamLog streams the cloudflared log file via SSE. Implements tunnel.Provider. +func (p *Provider) StreamLog(id string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) { + tunnel.StreamLogFile(ctx, w, flusher, p.logPath(id), 50) +} + +func (p *Provider) cleanup(id string) { + p.mu.Lock() + delete(p.processes, id) + delete(p.cancelFns, id) + p.mu.Unlock() + p.tunnelRepo.UpdateStatusByIntegrationID(id, tunneldomain.TunnelStatusInactive) + p.proxyRepo.UpdateBootStatusByIntegrationID(id, proxydomain.ProxyBootStatusOffline) +} diff --git a/internal/application/frpc/service.go b/internal/application/tunnel/frp/provider.go similarity index 50% rename from internal/application/frpc/service.go rename to internal/application/tunnel/frp/provider.go index cdb7a46..8434f40 100644 --- a/internal/application/frpc/service.go +++ b/internal/application/tunnel/frp/provider.go @@ -1,12 +1,12 @@ -package frpc +// Package frp manages frp client processes, one per server. +// It implements tunnel.Provider. +package frp import ( - "bufio" "context" "encoding/json" "errors" "fmt" - "io" "net/http" "os" "os/signal" @@ -16,9 +16,10 @@ import ( "syscall" "time" + "podux/internal/application/tunnel" proxydomain "podux/internal/domain/proxy" serverdomain "podux/internal/domain/server" - "podux/pkg/utils" + tunneldomain "podux/internal/domain/tunnel" "github.com/fatedier/frp/client" frpcsource "github.com/fatedier/frp/pkg/config/source" @@ -30,73 +31,69 @@ import ( var validServerID = regexp.MustCompile(`^[a-z0-9]{15}$`) var sensitiveRegex = regexp.MustCompile(`"(?i)(token|password|sk|pwd|secretkey|httpuser|httppwd|oidctoken|oidcclientsecret)":"(?:[^"\\]|\\.)*"`) -type Service struct { +// Provider manages frp client processes, one per server. It implements tunnel.Provider. +type Provider struct { mu sync.RWMutex app core.App processes map[string]*client.Service statusMonitors map[string]context.CancelFunc serverRepo serverdomain.Repository proxyRepo proxydomain.Repository + tunnelRepo tunneldomain.Repository } -func NewService(app core.App, serverRepo serverdomain.Repository, proxyRepo proxydomain.Repository) *Service { - return &Service{ +func NewProvider(app core.App, serverRepo serverdomain.Repository, proxyRepo proxydomain.Repository, tunnelRepo tunneldomain.Repository) *Provider { + return &Provider{ app: app, processes: make(map[string]*client.Service), statusMonitors: make(map[string]context.CancelFunc), serverRepo: serverRepo, proxyRepo: proxyRepo, + tunnelRepo: tunnelRepo, } } -func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) { - if !validServerID.MatchString(*id) { +func (p *Provider) genCommonCfgs(id string) (*v1.ClientCommonConfig, error) { + if !validServerID.MatchString(id) { return nil, errors.New("invalid server id") } cfg := &v1.ClientCommonConfig{} - record, err := fs.app.FindRecordById("fh_servers", *id) + record, err := p.app.FindRecordById("fh_servers", id) if err != nil { return nil, err } - // basic config cfg.ServerAddr = record.GetString("serverAddr") cfg.ServerPort = record.GetInt("serverPort") cfg.User = record.GetString("user") - logDirPath := filepath.Join("pb_data", "frpc", *id) + logDirPath := filepath.Join("pb_data", "frpc", id) if err := os.MkdirAll(logDirPath, 0755); err != nil { return nil, err } - // log config logStr := record.GetString("log") - mainPath := fs.getFrpMainPath(id) + mainPath := p.mainPath(id) var logConfig v1.LogConfig - err = json.Unmarshal([]byte(logStr), &logConfig) - if err != nil { + if err = json.Unmarshal([]byte(logStr), &logConfig); err != nil { return nil, err } logPath := filepath.Join(mainPath, "logs", "frpc.log") logConfig.To = logPath cfg.Log = logConfig - // auth config authStr := record.GetString("auth") var authConfig v1.AuthClientConfig - err = json.Unmarshal([]byte(authStr), &authConfig) - if err != nil { + if err = json.Unmarshal([]byte(authStr), &authConfig); err != nil { return nil, err } if authConfig.Method != "none" && authConfig.Method != "" { cfg.Auth = authConfig } - // transport config transportStr := record.GetString("transport") var transportConfig v1.ClientTransportConfig - err = json.Unmarshal([]byte(transportStr), &transportConfig) - if err != nil { + if err = json.Unmarshal([]byte(transportStr), &transportConfig); err != nil { return nil, err } cfg.Transport = transportConfig @@ -136,21 +133,19 @@ func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) { } } - // metadata config metadataStr := record.GetString("metadatas") var metadataConfig map[string]string - err = json.Unmarshal([]byte(metadataStr), &metadataConfig) - if err != nil { + if err = json.Unmarshal([]byte(metadataStr), &metadataConfig); err != nil { return nil, err } cfg.Metadatas = metadataConfig return cfg, nil } -func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error) { - proxies, err := fs.proxyRepo.FindEnabledByServerID(*serverId) +func (p *Provider) genProxyCfgs(serverId string) ([]v1.ProxyConfigurer, error) { + proxies, err := p.proxyRepo.FindEnabledByServerID(serverId) if err != nil { - fs.app.Logger().Error("genProxyCfgs", "err", err) + p.app.Logger().Error("genProxyCfgs", "err", err) return nil, err } @@ -161,7 +156,6 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error) return nil, err } - // Convert to map to manipulate fields var proxyData map[string]interface{} if err := json.Unmarshal(jsonData, &proxyData); err != nil { return nil, err @@ -172,7 +166,6 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error) } proxyData["name"] = proxyMap.Name + "-" + proxyMap.Id - // Remove empty plugin map so frp doesn't try to parse a typeless plugin if plugin, ok := proxyData["plugin"].(map[string]interface{}); ok { if _, hasType := plugin["type"]; !hasType { delete(proxyData, "plugin") @@ -222,28 +215,26 @@ func handleTermSignal(svr *client.Service) { svr.GracefulClose(500 * time.Millisecond) } -func (fs *Service) LaunchFrpc(serverId *string) error { - fs.app.Logger().Info("Launch frpc", "id", *serverId) - cfg, err := fs.genCommonCfgs(serverId) +// Launch starts the frp client for the given server ID. Implements tunnel.Provider. +func (p *Provider) Launch(id string) error { + p.app.Logger().Info("Launch frpc", "id", id) + cfg, err := p.genCommonCfgs(id) if err != nil { return err } - proxyCfgs, err := fs.genProxyCfgs(serverId) + proxyCfgs, err := p.genProxyCfgs(id) if err != nil { return err } - fs.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs)) + p.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs)) - // Print frp configurations in logs with sensitive data masked commonCfgBytes, _ := json.Marshal(cfg) proxyCfgsBytes, _ := json.Marshal(proxyCfgs) - safeCommon := sensitiveRegex.ReplaceAll(commonCfgBytes, []byte(`"${1}":"***"`)) safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`)) - - fs.app.Logger().Info("FRP Configuration", "common", string(safeCommon), "proxies", string(safeProxies)) + p.app.Logger().Info("FRP Configuration", "common", string(safeCommon), "proxies", string(safeProxies)) cfg.Complete() log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor) @@ -257,58 +248,53 @@ func (fs *Service) LaunchFrpc(serverId *string) error { ConfigSourceAggregator: frpcsource.NewAggregator(configSrc), }) if err != nil { - fs.app.Logger().Error("NewService", "err", err) + p.app.Logger().Error("NewService", "err", err) return err } - shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic" - if shouldGracefulClose { + if cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic" { go handleTermSignal(svr) } - ctx, cancel := context.WithCancel(context.Background()) - fs.mu.Lock() - fs.processes[*serverId] = svr - fs.statusMonitors[*serverId] = cancel - fs.mu.Unlock() - fs.serverRepo.UpdateBootStatus(*serverId, serverdomain.ServerStatusRunning) + ctx, cancel := context.WithCancel(context.Background()) + p.mu.Lock() + p.processes[id] = svr + p.statusMonitors[id] = cancel + p.mu.Unlock() done := make(chan error, 1) - go func() { - fs.app.Logger().Info("Frpc service starting execution", "id", *serverId) + p.app.Logger().Info("Frpc service starting execution", "id", id) err := svr.Run(ctx) if err != nil { - fs.app.Logger().Error("Frpc service exited with error", "id", *serverId, "error", err) + p.app.Logger().Error("Frpc service exited with error", "id", id, "error", err) } else { - fs.app.Logger().Info("Frpc service exited normally", "id", *serverId) + p.app.Logger().Info("Frpc service exited normally", "id", id) } done <- err }() - go fs.monitorServiceStatus(serverId, svr, ctx, done) - + go p.monitorServiceStatus(id, svr, ctx, done) return nil } -// monitorServiceStatus monitors service status and updates the database. -func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error) { +func (p *Provider) monitorServiceStatus(id string, svr *client.Service, ctx context.Context, done <-chan error) { time.Sleep(2 * time.Second) select { case err := <-done: - fs.app.Logger().Error("Service exited during startup", "id", *id, "error", err) - fs.destroying(id) + p.app.Logger().Error("Service exited during startup", "id", id, "error", err) + p.destroying(id) return case <-ctx.Done(): - fs.app.Logger().Info("Service context cancelled during startup", "id", *id) - fs.destroying(id) + p.app.Logger().Info("Service context cancelled during startup", "id", id) + p.destroying(id) return default: - fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusRunning) - fs.app.Logger().Info("Service is running", "id", *id) + p.tunnelRepo.UpdateStatusByServerID(id, tunneldomain.TunnelStatusActive) + p.app.Logger().Info("Service is running", "id", id) } - go fs.monitorProxyStatus(id, svr, ctx) + go p.monitorProxyStatus(id, svr, ctx) ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() @@ -317,34 +303,33 @@ func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx con select { case err := <-done: if err != nil { - fs.app.Logger().Error("Service exited with error", "id", *id, "error", err) + p.app.Logger().Error("Service exited with error", "id", id, "error", err) } else { - fs.app.Logger().Info("Service exited normally", "id", *id) + p.app.Logger().Info("Service exited normally", "id", id) } - fs.destroying(id) + p.destroying(id) return case <-ctx.Done(): - fs.app.Logger().Info("Service stopped by user", "id", *id) - fs.destroying(id) + p.app.Logger().Info("Service stopped by user", "id", id) + p.destroying(id) return case <-ticker.C: - fs.app.Logger().Debug("Service status check", "id", *id, "status", "running") + p.app.Logger().Debug("Service status check", "id", id, "status", "running") } } } -func (fs *Service) destroying(id *string) { - fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusStopped) - fs.proxyRepo.UpdateBootStatusByServerID(*id, proxydomain.ProxyBootStatusOffline) - fs.mu.Lock() - delete(fs.processes, *id) - delete(fs.statusMonitors, *id) - fs.mu.Unlock() +func (p *Provider) destroying(id string) { + p.tunnelRepo.UpdateStatusByServerID(id, tunneldomain.TunnelStatusInactive) + p.proxyRepo.UpdateBootStatusByServerID(id, proxydomain.ProxyBootStatusOffline) + p.mu.Lock() + delete(p.processes, id) + delete(p.statusMonitors, id) + p.mu.Unlock() } -// monitorProxyStatus monitors proxy status from frp and updates the database. -func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context) { - fs.app.Logger().Info("Starting proxy status monitoring", "serverId", *serverId) +func (p *Provider) monitorProxyStatus(serverId string, svr *client.Service, ctx context.Context) { + p.app.Logger().Info("Starting proxy status monitoring", "serverId", serverId) statusExporter := svr.StatusExporter() @@ -354,19 +339,19 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx for { select { case <-ctx.Done(): - fs.app.Logger().Info("Proxy status monitoring stopped", "serverId", *serverId) + p.app.Logger().Info("Proxy status monitoring stopped", "serverId", serverId) return case <-ticker.C: - proxies, err := fs.proxyRepo.FindByServerID(*serverId) + proxies, err := p.proxyRepo.FindByServerID(serverId) if err != nil { - fs.app.Logger().Error("Failed to get proxies", "serverId", *serverId, "error", err) + p.app.Logger().Error("Failed to get proxies", "serverId", serverId, "error", err) continue } for _, proxy := range proxies { baseName := proxy.Name + "-" + proxy.Id status, exists := statusExporter.GetProxyStatus(baseName) - fs.app.Logger().Info("proxy status check", "baseName", baseName, "exists", exists, "phase", func() string { + p.app.Logger().Info("proxy status check", "baseName", baseName, "exists", exists, "phase", func() string { if status != nil { return status.Phase } @@ -383,149 +368,70 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx default: bootStatus = proxydomain.ProxyBootStatusOffline } - fs.proxyRepo.UpdateBootStatus(proxy.Id, bootStatus) + p.proxyRepo.UpdateBootStatus(proxy.Id, bootStatus) } else { - // Proxy is not in frp (disabled or removed) — mark as offline - fs.proxyRepo.UpdateBootStatus(proxy.Id, proxydomain.ProxyBootStatusOffline) + p.proxyRepo.UpdateBootStatus(proxy.Id, proxydomain.ProxyBootStatusOffline) } } } } } -// TerminateFrpc stops the specified frpc service. -func (fs *Service) TerminateFrpc(id *string) error { - fs.app.Logger().Info("Stop frpc", "id", *id) +// Terminate stops the frp client for the given server ID. Implements tunnel.Provider. +func (p *Provider) Terminate(id string) error { + p.app.Logger().Info("Stop frpc", "id", id) - fs.mu.RLock() - cancel, exists := fs.statusMonitors[*id] - fs.mu.RUnlock() + p.mu.RLock() + cancel, exists := p.statusMonitors[id] + p.mu.RUnlock() if !exists { return nil } cancel() - - fs.app.Logger().Info("Frpc stop signal sent", "id", *id) + p.app.Logger().Info("Frpc stop signal sent", "id", id) return nil } -func (fs *Service) getFrpMainPath(id *string) string { - return filepath.Join("pb_data", "frpc", *id) -} +// Reload hot-reloads the proxy configuration for the given server. Implements tunnel.Provider. +func (p *Provider) Reload(id string) error { + p.app.Logger().Info("Reload frpc", "id", id) -// StreamLog streams the frpc log file via SSE. -// It sends the last 50 lines as initial content, then tails new lines every 500ms. -func (fs *Service) StreamLog(serverId string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) { - if !validServerID.MatchString(serverId) { - fmt.Fprintf(w, "data: [invalid server id]\n\n") - flusher.Flush() - return - } - mainPath := fs.getFrpMainPath(&serverId) - logPath := filepath.Join(mainPath, "logs", "frpc.log") - - file, err := os.Open(logPath) - if err != nil { - fs.app.Logger().Warn("Log file not found", "serverId", serverId, "path", logPath, "error", err) - fmt.Fprintf(w, "data: [No log file found]\n\n") - flusher.Flush() - return - } - defer file.Close() - - initialLines := utils.ReadLastNLines(file, 50) - fs.app.Logger().Info("Streaming log file", "serverId", serverId, "initialLines", len(initialLines)) - for _, line := range initialLines { - fmt.Fprintf(w, "data: %s\n\n", line) - } - flusher.Flush() - - offset, err := file.Seek(0, io.SeekEnd) - if err != nil { - return - } - - ticker := time.NewTicker(500 * time.Millisecond) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - fi, err := os.Stat(logPath) - if err != nil { - continue - } - - if fi.Size() < offset { - file.Close() - file, err = os.Open(logPath) - if err != nil { - continue - } - offset = 0 - } - - file.Seek(offset, io.SeekStart) - scanner := bufio.NewScanner(file) - hasData := false - for scanner.Scan() { - line := scanner.Text() - if line != "" { - fmt.Fprintf(w, "data: %s\n\n", line) - hasData = true - } - } - newOffset, _ := file.Seek(0, io.SeekCurrent) - offset = newOffset - - if hasData { - flusher.Flush() - } - } - } -} - -func (fs *Service) ReloadFrpc(serverId *string) error { - fs.app.Logger().Info("Reload frpc", "id", *serverId) - - proxyCfgs, err := fs.genProxyCfgs(serverId) + proxyCfgs, err := p.genProxyCfgs(id) if err != nil { return err } proxyCfgsBytes, _ := json.Marshal(proxyCfgs) safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`)) - fs.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies)) + p.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies)) - fs.mu.RLock() - svr := fs.processes[*serverId] - fs.mu.RUnlock() + p.mu.RLock() + svr := p.processes[id] + p.mu.RUnlock() // TODO 2026-02-08 reload visitorCfgs svr.UpdateAllConfigurer(proxyCfgs, nil) return nil } -// IsServerRunning checks if a server is currently running. -func (fs *Service) IsServerRunning(serverId string) bool { - fs.mu.RLock() - _, exists := fs.processes[serverId] - fs.mu.RUnlock() +// IsRunning reports whether the frp client for the given server is active. Implements tunnel.Provider. +func (p *Provider) IsRunning(id string) bool { + p.mu.RLock() + _, exists := p.processes[id] + p.mu.RUnlock() return exists } -// AutoStartServers automatically starts all servers with autoConnection=true. -func (fs *Service) AutoStartServers() { - fs.app.Logger().Info("Auto-starting servers with autoConnection enabled") - fs.app.Logger().Info("Waiting for 10 seconds before auto-starting servers") +// AutoStart starts all servers configured with autoConnection=true. Implements tunnel.Provider. +func (p *Provider) AutoStart() { + p.app.Logger().Info("Auto-starting servers with autoConnection enabled") + p.app.Logger().Info("Waiting for 10 seconds before auto-starting servers") time.Sleep(10 * time.Second) - records, err := fs.serverRepo.FindAllWithAutoConnect() + records, err := p.serverRepo.FindAllWithAutoConnect() if err != nil { - fs.app.Logger().Error("Failed to find auto-connection servers", "error", err) + p.app.Logger().Error("Failed to find auto-connection servers", "error", err) return } @@ -534,22 +440,37 @@ func (fs *Service) AutoStartServers() { serverId := record.ID serverName := record.ServerName - fs.app.Logger().Info("Auto-starting server", "id", serverId, "name", serverName) + p.app.Logger().Info("Auto-starting server", "id", serverId, "name", serverName) - go func(id string) { - time.Sleep(time.Duration(count) * 500 * time.Millisecond) - - if err := fs.LaunchFrpc(&id); err != nil { - fs.app.Logger().Error("Failed to auto-start server", "id", id, "error", err) + go func(id string, delay int) { + time.Sleep(time.Duration(delay) * 500 * time.Millisecond) + if err := p.Launch(id); err != nil { + p.app.Logger().Error("Failed to auto-start server", "id", id, "error", err) } else { - fs.app.Logger().Info("Successfully auto-started server", "id", id) + p.app.Logger().Info("Successfully auto-started server", "id", id) } - }(serverId) + }(serverId, count) count++ - fs.app.Logger().Info("Waiting for 1s before auto-starting next server") + p.app.Logger().Info("Waiting for 1s before auto-starting next server") time.Sleep(1 * time.Second) } - fs.app.Logger().Info("Auto-start initiated for servers", "count", count) + p.app.Logger().Info("Auto-start initiated for servers", "count", count) } + +// StreamLog streams the frpc log file via SSE. Implements tunnel.Provider. +func (p *Provider) StreamLog(id string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) { + if !validServerID.MatchString(id) { + fmt.Fprintf(w, "data: [invalid server id]\n\n") + flusher.Flush() + return + } + logPath := filepath.Join(p.mainPath(id), "logs", "frpc.log") + tunnel.StreamLogFile(ctx, w, flusher, logPath, 50) +} + +func (p *Provider) mainPath(id string) string { + return filepath.Join("pb_data", "frpc", id) +} + diff --git a/internal/application/tunnel/provider.go b/internal/application/tunnel/provider.go new file mode 100644 index 0000000..2e66621 --- /dev/null +++ b/internal/application/tunnel/provider.go @@ -0,0 +1,26 @@ +// Package tunnel defines the common Provider interface implemented by all +// tunnel backends (frpc, cloudflare). +package tunnel + +import ( + "context" + "net/http" +) + +// Provider defines the lifecycle interface for a tunnel backend. +// Each implementation manages a set of running tunnel processes, +// keyed by an entity ID (serverId for frpc, integrationId for cloudflare). +type Provider interface { + // Launch starts the tunnel for the given entity ID. + Launch(id string) error + // Terminate stops the tunnel for the given entity ID. + Terminate(id string) error + // Reload reloads the proxy configuration without a full restart. + Reload(id string) error + // IsRunning reports whether the tunnel for the given entity is active. + IsRunning(id string) bool + // AutoStart starts all tunnels configured for automatic connection. + AutoStart() + // StreamLog tails the tunnel log via Server-Sent Events. + StreamLog(id string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) +} diff --git a/internal/application/tunnel/sse.go b/internal/application/tunnel/sse.go new file mode 100644 index 0000000..b60592d --- /dev/null +++ b/internal/application/tunnel/sse.go @@ -0,0 +1,78 @@ +package tunnel + +import ( + "bufio" + "context" + "fmt" + "io" + "net/http" + "os" + "time" + + "podux/pkg/utils" +) + +// WriteSSEHeaders sets the standard response headers for a Server-Sent Events stream. +func WriteSSEHeaders(w http.ResponseWriter) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") +} + +// StreamLogFile tails logPath via SSE. It first sends up to initialLines of +// recent history, then polls for new content every 500 ms until ctx is done. +func StreamLogFile(ctx context.Context, w http.ResponseWriter, flusher http.Flusher, logPath string, initialLines int) { + file, err := os.Open(logPath) + if err != nil { + fmt.Fprintf(w, "data: [No log file found]\n\n") + flusher.Flush() + return + } + defer file.Close() + + for _, line := range utils.ReadLastNLines(file, initialLines) { + fmt.Fprintf(w, "data: %s\n\n", line) + } + flusher.Flush() + + offset, err := file.Seek(0, io.SeekEnd) + if err != nil { + return + } + + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + fi, err := os.Stat(logPath) + if err != nil { + continue + } + if fi.Size() < offset { + file.Close() + file, err = os.Open(logPath) + if err != nil { + continue + } + offset = 0 + } + file.Seek(offset, io.SeekStart) + scanner := bufio.NewScanner(file) + hasData := false + for scanner.Scan() { + if line := scanner.Text(); line != "" { + fmt.Fprintf(w, "data: %s\n\n", line) + hasData = true + } + } + offset, _ = file.Seek(0, io.SeekCurrent) + if hasData { + flusher.Flush() + } + } + } +} diff --git a/internal/domain/proxy/model.go b/internal/domain/proxy/model.go index 67f8cbc..7e3b2fb 100644 --- a/internal/domain/proxy/model.go +++ b/internal/domain/proxy/model.go @@ -2,7 +2,7 @@ package proxy import "podux/pkg/types" -// Proxy represents a frpc proxy configuration record. +// Proxy represents a proxy configuration record. type Proxy struct { Id string `db:"id" json:"id"` ServerId string `db:"serverId" json:"serverId"` diff --git a/internal/domain/proxy/repository.go b/internal/domain/proxy/repository.go index 6ecc25f..800f39a 100644 --- a/internal/domain/proxy/repository.go +++ b/internal/domain/proxy/repository.go @@ -7,6 +7,7 @@ type Repository interface { CountByType() (map[string]int64, error) UpdateBootStatus(id string, status ProxyBootStatus) error UpdateBootStatusByServerID(serverID string, status ProxyBootStatus) error + UpdateBootStatusByIntegrationID(integrationID string, status ProxyBootStatus) error ResetAllBootStatus() error FindByServerID(serverID string) ([]Proxy, error) FindEnabledByServerID(serverID string) ([]Proxy, error) diff --git a/internal/domain/server/model.go b/internal/domain/server/model.go index 610f3a4..1dd8469 100644 --- a/internal/domain/server/model.go +++ b/internal/domain/server/model.go @@ -1,12 +1,5 @@ package server -type ServerStatus string - -const ( - ServerStatusRunning ServerStatus = "running" - ServerStatusStopped ServerStatus = "stopped" -) - // ServerRecord is a lightweight struct for DB scanning operations. type ServerRecord struct { ID string `db:"id"` diff --git a/internal/domain/server/repository.go b/internal/domain/server/repository.go index bd7a0cb..8c92df2 100644 --- a/internal/domain/server/repository.go +++ b/internal/domain/server/repository.go @@ -2,9 +2,6 @@ package server // Repository defines persistence operations for the server domain. type Repository interface { - CountByBootStatus(status ServerStatus) (int64, error) - UpdateBootStatus(id string, status ServerStatus) error - ResetAllBootStatus() error GetMaxLatency() (int64, error) FindAllWithAutoConnect() ([]ServerRecord, error) } diff --git a/internal/domain/tunnel/model.go b/internal/domain/tunnel/model.go new file mode 100644 index 0000000..f90d1fe --- /dev/null +++ b/internal/domain/tunnel/model.go @@ -0,0 +1,9 @@ +package tunnel + +type TunnelStatus string + +const ( + TunnelStatusActive TunnelStatus = "active" + TunnelStatusInactive TunnelStatus = "inactive" + TunnelStatusError TunnelStatus = "error" +) diff --git a/internal/domain/tunnel/repository.go b/internal/domain/tunnel/repository.go new file mode 100644 index 0000000..d5ed0ad --- /dev/null +++ b/internal/domain/tunnel/repository.go @@ -0,0 +1,8 @@ +package tunnel + +type Repository interface { + UpdateStatusByServerID(serverID string, status TunnelStatus) error + UpdateStatusByIntegrationID(integrationID string, status TunnelStatus) error + ResetAllStatus() error + CountByStatus(status TunnelStatus) (int64, error) +} diff --git a/pkg/binary/manager.go b/pkg/binary/manager.go new file mode 100644 index 0000000..ff01c34 --- /dev/null +++ b/pkg/binary/manager.go @@ -0,0 +1,170 @@ +// Package binary manages the download and installation of external executables +// (cloudflared, frpc, rathole) into a local bin directory. +package binary + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" +) + +// BinaryManager handles downloading and installing a single external binary. +type BinaryManager struct { + Name string // "cloudflared" | "frpc" | "rathole" + Version string // "latest" or a specific tag, e.g. "v1.2.3" + BinDir string // directory where the binary will be stored +} + +// New creates a BinaryManager. Use DefaultBinDir() to obtain the standard location. +func New(name, version, binDir string) *BinaryManager { + return &BinaryManager{Name: name, Version: version, BinDir: binDir} +} + +// DefaultBinDir returns ~/.podux/bin, creating the directory if it does not exist. +func DefaultBinDir() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("determine home directory: %w", err) + } + dir := filepath.Join(home, ".podux", "bin") + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", fmt.Errorf("create bin dir %s: %w", dir, err) + } + return dir, nil +} + +// GetPath returns the absolute path of the binary. +// On Windows the ".exe" suffix is appended automatically. +func (m *BinaryManager) GetPath() string { + name := m.Name + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(m.BinDir, name) +} + +// EnsureInstalled downloads and installs the binary only when it is not already +// present. It is safe to call repeatedly; subsequent calls are no-ops. +func (m *BinaryManager) EnsureInstalled(ctx context.Context) error { + if _, err := os.Stat(m.GetPath()); err == nil { + return nil // already installed + } + return m.download(ctx) +} + +// Update downloads the binary unconditionally, replacing any existing version. +func (m *BinaryManager) Update(ctx context.Context) error { + return m.download(ctx) +} + +// download resolves the version, fetches the asset, extracts it if needed, +// and places the binary at GetPath() with executable permissions. +func (m *BinaryManager) download(ctx context.Context) error { + if err := os.MkdirAll(m.BinDir, 0o755); err != nil { + return fmt.Errorf("create bin dir: %w", err) + } + + s, ok := specs[m.Name] + if !ok { + return fmt.Errorf("unknown binary %q (supported: cloudflared, frpc, rathole)", m.Name) + } + + // Resolve "latest" to the actual tag via the GitHub API. + version := m.Version + if version == "" || version == "latest" { + var err error + version, err = githubLatestTag(ctx, s.githubOwner, s.githubRepo) + if err != nil { + return fmt.Errorf("resolve latest version for %s: %w", m.Name, err) + } + } + + assetFilename, entryPath, err := s.resolveAsset(version, runtime.GOOS, runtime.GOARCH) + if err != nil { + return err + } + + downloadURL := fmt.Sprintf( + "https://github.com/%s/%s/releases/download/%s/%s", + s.githubOwner, s.githubRepo, version, assetFilename, + ) + + // Download to a temporary file in the same directory so the final rename + // is atomic (same filesystem). + tmpFile, err := os.CreateTemp(m.BinDir, ".download-*") + if err != nil { + return fmt.Errorf("create temp file: %w", err) + } + tmpPath := tmpFile.Name() + defer func() { + tmpFile.Close() + os.Remove(tmpPath) // clean up on error; harmless if already renamed + }() + + if err := fetchURL(ctx, downloadURL, tmpFile); err != nil { + return fmt.Errorf("download %s: %w", downloadURL, err) + } + tmpFile.Close() + + dest := m.GetPath() + + if entryPath != "" { + // Asset is an archive; extract the binary from it. + if err := extractEntry(tmpPath, entryPath, dest); err != nil { + return fmt.Errorf("extract %s from archive: %w", entryPath, err) + } + } else { + // Asset is a raw binary; rename or copy into place. + if err := os.Rename(tmpPath, dest); err != nil { + // Rename can fail across mount points; fall back to copy. + if err2 := copyFile(tmpPath, dest); err2 != nil { + return fmt.Errorf("install binary: %w", err2) + } + } + } + + return os.Chmod(dest, 0o755) +} + +// fetchURL downloads url into w, following redirects. +func fetchURL(ctx context.Context, url string, w io.Writer) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + req.Header.Set("User-Agent", "podux") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("HTTP %d from %s", resp.StatusCode, url) + } + _, err = io.Copy(w, resp.Body) + return err +} + +// copyFile copies src to dst. +func copyFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, in) + return err +} diff --git a/pkg/binary/resolver.go b/pkg/binary/resolver.go new file mode 100644 index 0000000..dbc8570 --- /dev/null +++ b/pkg/binary/resolver.go @@ -0,0 +1,129 @@ +package binary + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" +) + +type binarySpec struct { + githubOwner string + githubRepo string + // resolveAsset returns (assetFilename, entryPath). + // entryPath is the path of the binary inside the archive; empty means the asset is a raw binary. + resolveAsset func(version, goos, goarch string) (assetFilename, entryPath string, err error) +} + +var specs = map[string]binarySpec{ + "cloudflared": { + githubOwner: "cloudflare", + githubRepo: "cloudflared", + resolveAsset: func(version, goos, goarch string) (string, string, error) { + switch goos + "/" + goarch { + case "linux/amd64": + return "cloudflared-linux-amd64", "", nil + case "linux/arm64": + return "cloudflared-linux-arm64", "", nil + case "darwin/amd64": + return "cloudflared-darwin-amd64.tgz", "cloudflared", nil + case "darwin/arm64": + return "cloudflared-darwin-arm64.tgz", "cloudflared", nil + case "windows/amd64": + return "cloudflared-windows-amd64.exe", "", nil + default: + return "", "", fmt.Errorf("cloudflared: unsupported platform %s/%s", goos, goarch) + } + }, + }, + "frpc": { + githubOwner: "fatedier", + githubRepo: "frp", + resolveAsset: func(version, goos, goarch string) (string, string, error) { + ver := strings.TrimPrefix(version, "v") + + var osStr, archStr string + switch goos { + case "linux": + osStr = "linux" + case "darwin": + osStr = "darwin" + case "windows": + osStr = "windows" + default: + return "", "", fmt.Errorf("frpc: unsupported OS %s", goos) + } + switch goarch { + case "amd64": + archStr = "amd64" + case "arm64": + archStr = "arm64" + case "arm": + archStr = "arm" + default: + return "", "", fmt.Errorf("frpc: unsupported arch %s", goarch) + } + + asset := fmt.Sprintf("frp_%s_%s_%s.tar.gz", ver, osStr, archStr) + binName := "frpc" + if goos == "windows" { + binName = "frpc.exe" + } + entry := fmt.Sprintf("frp_%s_%s_%s/%s", ver, osStr, archStr, binName) + return asset, entry, nil + }, + }, + "rathole": { + githubOwner: "rapiz1", + githubRepo: "rathole", + resolveAsset: func(version, goos, goarch string) (string, string, error) { + switch goos + "/" + goarch { + case "linux/amd64": + return "rathole-x86_64-unknown-linux-musl.zip", "rathole", nil + case "linux/arm64": + return "rathole-aarch64-unknown-linux-musl.zip", "rathole", nil + case "darwin/amd64": + return "rathole-x86_64-apple-darwin.zip", "rathole", nil + case "darwin/arm64": + return "rathole-aarch64-apple-darwin.zip", "rathole", nil + case "windows/amd64": + return "rathole-x86_64-pc-windows-msvc.zip", "rathole.exe", nil + default: + return "", "", fmt.Errorf("rathole: unsupported platform %s/%s", goos, goarch) + } + }, + }, +} + +// githubLatestTag returns the tag_name of the latest GitHub release. +func githubLatestTag(ctx context.Context, owner, repo string) (string, error) { + url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", err + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("User-Agent", "podux") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", fmt.Errorf("GitHub API request failed: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("GitHub API returned HTTP %d", resp.StatusCode) + } + + var release struct { + TagName string `json:"tag_name"` + } + if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { + return "", fmt.Errorf("decode GitHub response: %w", err) + } + if release.TagName == "" { + return "", fmt.Errorf("empty tag_name from GitHub API") + } + return release.TagName, nil +}