dae/component/outbound/dialer/dialer.go

95 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/mzz2017/softwind/netproxy"
2023-01-23 18:54:21 +07:00
"github.com/sirupsen/logrus"
"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
netproxy.Dialer
2023-02-28 20:25:15 +07:00
property Property
collectionFineMu sync.Mutex
collections [6]*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
CheckDnsOptionRaw CheckDnsOptionRaw // Lazy parse
CheckInterval time.Duration
CheckTolerance time.Duration
CheckDnsTcp bool
AllowInsecure bool
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
}
2023-02-28 20:25:15 +07:00
type Property struct {
Name string
Address string
Protocol string
Link string
}
type AliveDialerSetSet map[*AliveDialerSet]int
2023-01-28 14:47:43 +07:00
// NewDialer is for register in general.
2023-02-28 20:25:15 +07:00
func NewDialer(dialer netproxy.Dialer, option *GlobalOption, iOption InstanceOption, property Property) *Dialer {
var collections [6]*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,
2023-02-28 20:25:15 +07:00
property: property,
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()
return nil
}
2023-02-28 20:25:15 +07:00
func (d *Dialer) Property() Property {
return d.property
2023-01-23 18:54:21 +07:00
}