Fix monitor

This commit is contained in:
世界 2023-08-07 19:54:17 +08:00
parent 59b86002c4
commit 0a68b9f1d8
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
9 changed files with 80 additions and 87 deletions

View file

@ -3,7 +3,6 @@
package tun
import (
"context"
"errors"
"net"
"net/netip"
@ -11,7 +10,7 @@ import (
"time"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/logger"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/common/x/list"
)
@ -33,17 +32,10 @@ func (m *networkUpdateMonitor) emit() {
callbacks := m.callbacks.Array()
m.access.Unlock()
for _, callback := range callbacks {
err := callback()
if err != nil {
m.NewError(context.Background(), err)
}
callback()
}
}
func (m *networkUpdateMonitor) NewError(ctx context.Context, err error) {
m.errorHandler.NewError(ctx, err)
}
type defaultInterfaceMonitor struct {
options DefaultInterfaceMonitorOptions
networkAddresses []networkAddress
@ -54,6 +46,7 @@ type defaultInterfaceMonitor struct {
element *list.Element[NetworkUpdateCallback]
access sync.Mutex
callbacks list.List[DefaultInterfaceUpdateCallback]
logger logger.Logger
}
type networkAddress struct {
@ -62,34 +55,35 @@ type networkAddress struct {
addresses []netip.Prefix
}
func NewDefaultInterfaceMonitor(networkMonitor NetworkUpdateMonitor, options DefaultInterfaceMonitorOptions) (DefaultInterfaceMonitor, error) {
func NewDefaultInterfaceMonitor(networkMonitor NetworkUpdateMonitor, logger logger.Logger, options DefaultInterfaceMonitorOptions) (DefaultInterfaceMonitor, error) {
return &defaultInterfaceMonitor{
options: options,
networkMonitor: networkMonitor,
defaultInterfaceIndex: -1,
logger: logger,
}, nil
}
func (m *defaultInterfaceMonitor) Start() error {
err := m.checkUpdate()
if err != nil {
m.networkMonitor.NewError(context.Background(), err)
m.logger.Error("initialize default interface: ", err)
}
m.element = m.networkMonitor.RegisterCallback(m.delayCheckUpdate)
return nil
}
func (m *defaultInterfaceMonitor) delayCheckUpdate() error {
func (m *defaultInterfaceMonitor) delayCheckUpdate() {
time.Sleep(time.Second)
err := m.updateInterfaces()
if err != nil {
m.networkMonitor.NewError(context.Background(), E.Cause(err, "update interfaces"))
m.logger.Error("update interfaces: ", err)
}
err = m.checkUpdate()
if errors.Is(err, ErrNoRoute) {
m.defaultInterfaceIndex = -1
m.emit(EventNoRoute)
}
return err
}
func (m *defaultInterfaceMonitor) updateInterfaces() error {
@ -180,9 +174,6 @@ func (m *defaultInterfaceMonitor) emit(event int) {
callbacks := m.callbacks.Array()
m.access.Unlock()
for _, callback := range callbacks {
err := callback(event)
if err != nil {
m.networkMonitor.NewError(context.Background(), err)
}
callback(event)
}
}