dae/component/outbound/dialer/dialer.go

98 lines
1.9 KiB
Go
Raw Normal View History

2023-01-23 18:54:21 +07:00
package dialer
import (
"context"
2023-01-23 18:54:21 +07:00
"fmt"
"github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"sync"
"time"
)
var (
UnexpectedFieldErr = fmt.Errorf("unexpected field")
InvalidParameterErr = fmt.Errorf("invalid parameters")
2023-01-23 18:54:21 +07:00
)
type Dialer struct {
2023-01-28 00:50:21 +07:00
*GlobalOption
2023-01-28 14:47:43 +07:00
instanceOption InstanceOption
2023-01-23 18:54:21 +07:00
proxy.Dialer
name string
protocol string
link string
collectionFineMu sync.Mutex
collections [4]*collection
2023-01-23 18:54:21 +07:00
tickerMu sync.Mutex
ticker *time.Ticker
checkCh chan time.Time
ctx context.Context
cancel context.CancelFunc
2023-01-23 18:54:21 +07:00
}
2023-01-28 00:50:21 +07:00
type GlobalOption struct {
Log *logrus.Logger
TcpCheckOptionRaw TcpCheckOptionRaw // Lazy parse
UdpCheckOptionRaw UdpCheckOptionRaw // Lazy parse
CheckInterval time.Duration
2023-01-28 00:50:21 +07:00
}
2023-01-28 14:47:43 +07:00
type InstanceOption struct {
CheckEnabled bool
2023-01-23 18:54:21 +07:00
}
type AliveDialerSetSet map[*AliveDialerSet]int
2023-01-28 14:47:43 +07:00
// NewDialer is for register in general.
func NewDialer(dialer proxy.Dialer, option *GlobalOption, iOption InstanceOption, name string, protocol string, link string) *Dialer {
var collections [4]*collection
for i := range collections {
collections[i] = newCollection()
}
ctx, cancel := context.WithCancel(context.Background())
2023-01-23 18:54:21 +07:00
d := &Dialer{
GlobalOption: option,
instanceOption: iOption,
Dialer: dialer,
name: name,
protocol: protocol,
link: link,
collectionFineMu: sync.Mutex{},
collections: collections,
tickerMu: sync.Mutex{},
ticker: nil,
checkCh: make(chan time.Time, 1),
ctx: ctx,
cancel: cancel,
2023-01-23 18:54:21 +07:00
}
if iOption.CheckEnabled {
2023-01-28 14:47:43 +07:00
go d.aliveBackground()
}
2023-01-23 18:54:21 +07:00
return d
}
func (d *Dialer) Close() error {
d.cancel()
2023-01-23 18:54:21 +07:00
d.tickerMu.Lock()
if d.ticker != nil {
d.ticker.Stop()
}
2023-01-23 18:54:21 +07:00
d.tickerMu.Unlock()
close(d.checkCh)
2023-01-23 18:54:21 +07:00
return nil
}
func (d *Dialer) Name() string {
return d.name
}
func (d *Dialer) Protocol() string {
return d.protocol
}
func (d *Dialer) Link() string {
return d.link
}