Files
proxy/server/fwd/fwd.go

113 lines
2.0 KiB
Go
Raw Normal View History

package fwd
import (
"context"
"log/slog"
"proxy-server/pkg/utils"
"proxy-server/server/fwd/core"
2025-02-27 23:11:36 +08:00
"sync"
)
type Config struct {
Id *int32
}
type Service struct {
Config *Config
ctx context.Context
cancel context.CancelFunc
userConnMap core.ConnMap
2025-02-27 23:11:36 +08:00
fwdLesWg utils.CountWaitGroup
ctrlConnWg utils.CountWaitGroup
dataConnWg utils.CountWaitGroup
userConnWg utils.CountWaitGroup
fwdPortMap map[uint16]int32 // 转发端口映射key 为端口号value 为边缘节点 ID
}
func New(config *Config) *Service {
2025-02-27 18:07:00 +08:00
if config == nil {
config = &Config{}
}
2025-02-27 23:11:36 +08:00
ctx, cancel := context.WithCancel(context.Background())
return &Service{
Config: config,
ctx: ctx,
cancel: cancel,
fwdPortMap: make(map[uint16]int32),
}
}
2025-05-14 15:13:44 +08:00
func (s *Service) Run() error {
slog.Info("启动 fwd 服务")
2025-03-06 14:35:21 +08:00
errQuit := make(chan struct{}, 2)
2025-02-27 23:11:36 +08:00
defer close(errQuit)
2025-02-27 23:11:36 +08:00
wg := sync.WaitGroup{}
// 控制通道监听
2025-02-27 23:11:36 +08:00
wg.Add(1)
go func() {
defer wg.Done()
err := s.startCtrlTun()
if err != nil {
slog.Error("fwd 控制通道监听发生错误", "err", err)
2025-02-27 23:11:36 +08:00
errQuit <- struct{}{}
return
}
}()
// 数据通道监听
2025-02-27 23:11:36 +08:00
wg.Add(1)
go func() {
defer wg.Done()
err := s.startDataTun()
if err != nil {
slog.Error("fwd 数据通道监听发生错误", "err", err)
2025-02-27 23:11:36 +08:00
errQuit <- struct{}{}
return
}
2025-02-27 23:11:36 +08:00
}()
// 等待退出
2025-02-27 23:11:36 +08:00
select {
case <-s.ctx.Done():
slog.Info("fwd 服务主动退出")
2025-02-27 23:11:36 +08:00
case <-errQuit:
slog.Warn("fwd 服务异常退出")
2025-05-14 15:13:44 +08:00
s.Stop()
}
wg.Wait()
s.dataConnWg.Wait()
s.ctrlConnWg.Wait()
s.fwdLesWg.Wait()
s.userConnWg.Wait()
// 清理资源
s.userConnMap.Range(func(key string, value *core.Conn) bool {
utils.Close(value)
return true
})
s.userConnMap.Clear()
s.ctrlConnWg.Wait()
slog.Debug("控制通道连接已关闭")
s.dataConnWg.Wait()
slog.Debug("数据通道连接已关闭")
s.fwdLesWg.Wait()
slog.Debug("转发服务已关闭")
wg.Wait()
slog.Info("fwd 服务已退出")
2025-05-14 15:13:44 +08:00
return nil
}
func (s *Service) Stop() {
s.cancel()
2025-02-27 18:07:00 +08:00
}