Improve monitor api

This commit is contained in:
世界 2022-08-04 21:06:56 +08:00
parent 2a1554dfd3
commit 7ee0d19103
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
8 changed files with 110 additions and 192 deletions

View file

@ -13,6 +13,7 @@ import (
"golang.org/x/net/route"
"golang.org/x/sys/unix"
"syscall"
)
type networkUpdateMonitor struct {
@ -29,30 +30,6 @@ func NewNetworkUpdateMonitor(errorHandler E.Handler) (NetworkUpdateMonitor, erro
}, nil
}
func (m *networkUpdateMonitor) RegisterCallback(callback NetworkUpdateCallback) *list.Element[NetworkUpdateCallback] {
m.access.Lock()
defer m.access.Unlock()
return m.callbacks.PushBack(callback)
}
func (m *networkUpdateMonitor) UnregisterCallback(element *list.Element[NetworkUpdateCallback]) {
m.access.Lock()
defer m.access.Unlock()
m.callbacks.Remove(element)
}
func (m *networkUpdateMonitor) emit() {
m.access.Lock()
callbacks := m.callbacks.Array()
m.access.Unlock()
for _, callback := range callbacks {
err := callback()
if err != nil {
m.errorHandler.NewError(context.Background(), err)
}
}
}
func (m *networkUpdateMonitor) Start() error {
routeSocket, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, 0)
if err != nil {
@ -88,7 +65,7 @@ func (m *networkUpdateMonitor) loopUpdate() {
}
m.emit()
}
if !E.IsClosed(err) {
if err != syscall.EAGAIN {
m.errorHandler.NewError(context.Background(), err)
}
}
@ -97,43 +74,6 @@ func (m *networkUpdateMonitor) Close() error {
return common.Close(common.PtrOrNil(m.routeSocket))
}
type defaultInterfaceMonitor struct {
defaultInterfaceName string
defaultInterfaceIndex int
networkMonitor NetworkUpdateMonitor
element *list.Element[NetworkUpdateCallback]
callback DefaultInterfaceUpdateCallback
}
func NewDefaultInterfaceMonitor(networkMonitor NetworkUpdateMonitor, callback DefaultInterfaceUpdateCallback) (DefaultInterfaceMonitor, error) {
return &defaultInterfaceMonitor{
networkMonitor: networkMonitor,
callback: callback,
}, nil
}
func (m *defaultInterfaceMonitor) Start() error {
err := m.checkUpdate()
if err != nil {
return err
}
m.element = m.networkMonitor.RegisterCallback(m.checkUpdate)
return nil
}
func (m *defaultInterfaceMonitor) Close() error {
m.networkMonitor.UnregisterCallback(m.element)
return nil
}
func (m *defaultInterfaceMonitor) DefaultInterfaceName() string {
return m.defaultInterfaceName
}
func (m *defaultInterfaceMonitor) DefaultInterfaceIndex() int {
return m.defaultInterfaceIndex
}
func (m *defaultInterfaceMonitor) checkUpdate() error {
ribMessage, err := route.FetchRIB(unix.AF_UNSPEC, route.RIBTypeRoute, 0)
if err != nil {
@ -163,7 +103,7 @@ func (m *defaultInterfaceMonitor) checkUpdate() error {
if oldInterface == m.defaultInterfaceName && oldIndex == m.defaultInterfaceIndex {
return nil
}
m.callback()
m.emit()
return nil
}
}