Fix endpoint lifecycle ordering and device reconfiguration

This commit is contained in:
世界
2026-11-24 22:45:20 +08:00
parent 37fffa325b
commit 4913f787fb
11 changed files with 138 additions and 91 deletions
+1
View File
@@ -12,6 +12,7 @@ type Endpoint interface {
Type() string
Tag() string
Outbound
IsEndpoint()
}
type EndpointRegistry interface {
+3
View File
@@ -41,3 +41,6 @@ func (a *Adapter) Network() []string {
func (a *Adapter) Dependencies() []string {
return a.dependencies
}
func (a *Adapter) IsEndpoint() {
}
+32 -35
View File
@@ -3,6 +3,7 @@ package outbound
import (
"context"
"os"
"slices"
"strings"
"sync"
@@ -62,16 +63,26 @@ func (m *Manager) Start(stage adapter.StartStage, scope *adapter.Scope) error {
}
outbounds := m.outbounds
m.access.Unlock()
if stage == adapter.StartStateStart {
return m.startOutbounds(scope, append(outbounds, common.Map(m.endpoint.Endpoints(), func(it adapter.Endpoint) adapter.Outbound { return it })...))
sortedOutbounds, err := sortOutbounds(slices.Concat(outbounds, common.Map(m.endpoint.Endpoints(), func(it adapter.Endpoint) adapter.Outbound { return it })))
if err != nil {
return err
}
for _, outbound := range outbounds {
for _, outbound := range sortedOutbounds {
if endpoint, isEndpoint := outbound.(adapter.Endpoint); isEndpoint {
if stage == adapter.StartStateStart {
err = m.endpoint.StartEndpoint(endpoint)
if err != nil {
return err
}
}
continue
}
lifecycle, isLifecycle := outbound.(adapter.Lifecycle)
if !isLifecycle {
continue
}
name := "outbound/" + outbound.Type() + "[" + outbound.Tag() + "]"
err := scope.Start(name, lifecycle, stage)
err = scope.Start(name, lifecycle, stage)
if err != nil {
return err
}
@@ -79,54 +90,40 @@ func (m *Manager) Start(stage adapter.StartStage, scope *adapter.Scope) error {
return nil
}
func (m *Manager) startOutbounds(scope *adapter.Scope, outbounds []adapter.Outbound) error {
started := make(map[string]bool)
func sortOutbounds(outbounds []adapter.Outbound) ([]adapter.Outbound, error) {
sortedOutbounds := make([]adapter.Outbound, 0, len(outbounds))
sorted := make(map[string]bool)
for {
canContinue := false
startOne:
for _, outboundToStart := range outbounds {
outboundTag := outboundToStart.Tag()
if started[outboundTag] {
sortOne:
for _, outboundToSort := range outbounds {
outboundTag := outboundToSort.Tag()
if sorted[outboundTag] {
continue
}
dependencies := outboundToStart.Dependencies()
dependencies := outboundToSort.Dependencies()
for _, dependency := range dependencies {
if !started[dependency] {
continue startOne
if !sorted[dependency] {
continue sortOne
}
}
started[outboundTag] = true
sorted[outboundTag] = true
canContinue = true
if endpoint, isEndpoint := outboundToStart.(adapter.Endpoint); isEndpoint {
err := m.endpoint.StartEndpoint(endpoint)
if err != nil {
return err
}
continue
}
lifecycle, isLifecycle := outboundToStart.(adapter.Lifecycle)
if !isLifecycle {
continue
}
name := "outbound/" + outboundToStart.Type() + "[" + outboundTag + "]"
err := scope.Start(name, lifecycle, adapter.StartStateStart)
if err != nil {
return err
}
sortedOutbounds = append(sortedOutbounds, outboundToSort)
}
if len(started) == len(outbounds) {
if len(sorted) == len(outbounds) {
break
}
if canContinue {
continue
}
currentOutbound := common.Find(outbounds, func(it adapter.Outbound) bool {
return !started[it.Tag()]
return !sorted[it.Tag()]
})
var lintOutbound func(oTree []string, oCurrent adapter.Outbound) error
lintOutbound = func(oTree []string, oCurrent adapter.Outbound) error {
problemOutboundTag := common.Find(oCurrent.Dependencies(), func(it string) bool {
return !started[it]
return !sorted[it]
})
if common.Contains(oTree, problemOutboundTag) {
return E.New("circular outbound dependency: ", strings.Join(oTree, " -> "), " -> ", problemOutboundTag)
@@ -139,9 +136,9 @@ func (m *Manager) startOutbounds(scope *adapter.Scope, outbounds []adapter.Outbo
}
return lintOutbound(append(oTree, problemOutboundTag), problemOutbound)
}
return lintOutbound([]string{currentOutbound.Tag()}, currentOutbound)
return nil, lintOutbound([]string{currentOutbound.Tag()}, currentOutbound)
}
return nil
return sortedOutbounds, nil
}
func (m *Manager) Outbounds() []adapter.Outbound {
+22 -24
View File
@@ -60,12 +60,13 @@ func (m *TransportManager) Start(stage adapter.StartStage, scope *adapter.Scope)
}
transports := m.transports
m.access.Unlock()
if stage == adapter.StartStateStart {
return m.startTransports(scope, transports)
sortedTransports, err := m.sortTransports(transports)
if err != nil {
return err
}
for _, transport := range transports {
for _, transport := range sortedTransports {
name := "dns/" + transport.Type() + "[" + transport.Tag() + "]"
err := scope.Start(name, transport, stage)
err = scope.Start(name, transport, stage)
if err != nil {
return err
}
@@ -73,43 +74,40 @@ func (m *TransportManager) Start(stage adapter.StartStage, scope *adapter.Scope)
return nil
}
func (m *TransportManager) startTransports(scope *adapter.Scope, transports []adapter.DNSTransport) error {
started := make(map[string]bool)
func (m *TransportManager) sortTransports(transports []adapter.DNSTransport) ([]adapter.DNSTransport, error) {
sortedTransports := make([]adapter.DNSTransport, 0, len(transports))
sorted := make(map[string]bool)
for {
canContinue := false
startOne:
for _, transportToStart := range transports {
transportTag := transportToStart.Tag()
if started[transportTag] {
sortOne:
for _, transportToSort := range transports {
transportTag := transportToSort.Tag()
if sorted[transportTag] {
continue
}
dependencies := transportToStart.Dependencies()
dependencies := transportToSort.Dependencies()
for _, dependency := range dependencies {
if !started[dependency] {
continue startOne
if !sorted[dependency] {
continue sortOne
}
}
started[transportTag] = true
sorted[transportTag] = true
canContinue = true
name := "dns/" + transportToStart.Type() + "[" + transportTag + "]"
err := scope.Start(name, transportToStart, adapter.StartStateStart)
if err != nil {
return err
}
sortedTransports = append(sortedTransports, transportToSort)
}
if len(started) == len(transports) {
if len(sorted) == len(transports) {
break
}
if canContinue {
continue
}
currentTransport := common.Find(transports, func(it adapter.DNSTransport) bool {
return !started[it.Tag()]
return !sorted[it.Tag()]
})
var lintTransport func(oTree []string, oCurrent adapter.DNSTransport) error
lintTransport = func(oTree []string, oCurrent adapter.DNSTransport) error {
problemTransportTag := common.Find(oCurrent.Dependencies(), func(it string) bool {
return !started[it]
return !sorted[it]
})
if common.Contains(oTree, problemTransportTag) {
return E.New("circular server dependency: ", strings.Join(oTree, " -> "), " -> ", problemTransportTag)
@@ -122,9 +120,9 @@ func (m *TransportManager) startTransports(scope *adapter.Scope, transports []ad
}
return lintTransport(append(oTree, problemTransportTag), problemTransport)
}
return lintTransport([]string{currentTransport.Tag()}, currentTransport)
return nil, lintTransport([]string{currentTransport.Tag()}, currentTransport)
}
return nil
return sortedTransports, nil
}
func (m *TransportManager) Transports() []adapter.DNSTransport {
+4 -4
View File
@@ -478,10 +478,10 @@ func (e *Endpoint) readLoop(ctx context.Context) {
err = e.device.WriteInboundBuffers(packetBuffers)
buf.ReleaseMulti(packetBuffers)
if err != nil {
err = E.Cause(err, "write packet to device")
e.logger.Error(err)
e.setTerminalError(err)
return
if E.IsCanceled(err) || ctx.Err() != nil {
return
}
e.logger.Debug(E.Cause(err, "write packet to device"))
}
}
}
+4 -4
View File
@@ -654,10 +654,10 @@ func (c *ClientEndpoint) readLoop(ctx context.Context) {
err = c.device.WriteInboundBuffers(packetBuffers)
buf.ReleaseMulti(packetBuffers)
if err != nil {
err = E.Cause(err, "write packet to device")
c.logger.Error(err)
c.setTerminalError(err)
return
if E.IsCanceled(err) || ctx.Err() != nil {
return
}
c.logger.Debug(E.Cause(err, "write packet to device"))
}
}
}
+4 -2
View File
@@ -627,8 +627,10 @@ func (s *ServerEndpoint) readLoop(ctx context.Context) {
err = s.device.WriteInboundBuffers(packetBuffers)
buf.ReleaseMulti(packetBuffers)
if err != nil {
s.logger.Error(E.Cause(err, "write packet to device"))
return
if E.IsCanceled(err) || ctx.Err() != nil {
return
}
s.logger.Debug(E.Cause(err, "write packet to device"))
}
}
}
+3 -3
View File
@@ -202,7 +202,7 @@ func (w *Endpoint) DetachReturn(returnPath tun.Return) error {
func (w *Endpoint) JudgeFlow(network uint8, source netip.AddrPort, destination netip.AddrPort, firstPacket []byte) tun.FlowVerdict {
for _, localPrefix := range w.localAddresses {
if localPrefix.Contains(destination.Addr()) {
if destination.Addr() == localPrefix.Addr() {
return tun.FlowVerdict{Action: tun.ActionAccept}
}
}
@@ -235,7 +235,7 @@ func (w *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.
metadata.InboundType = w.Type()
metadata.Source = source
for _, localPrefix := range w.localAddresses {
if localPrefix.Contains(destination.Addr) {
if destination.Addr == localPrefix.Addr() {
metadata.OriginDestination = destination
if destination.Addr.Is4() {
destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
@@ -258,7 +258,7 @@ func (w *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn,
metadata.Source = source
metadata.Destination = destination
for _, localPrefix := range w.localAddresses {
if localPrefix.Contains(destination.Addr) {
if destination.Addr == localPrefix.Addr() {
metadata.OriginDestination = destination
if destination.Addr.Is4() {
metadata.Destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
+32 -9
View File
@@ -29,13 +29,15 @@ const (
type systemDevice struct {
baseDevice
stateAccess sync.RWMutex
options DeviceOptions
dialer N.Dialer
device tun.Tun
inet4Address netip.Addr
inet6Address netip.Addr
closed bool
stateAccess sync.RWMutex
options DeviceOptions
dialer N.Dialer
device tun.Tun
readLoopDone chan struct{}
reconfiguring bool
inet4Address netip.Addr
inet6Address netip.Addr
closed bool
}
func newSystemDevice(options DeviceOptions) (*systemDevice, error) {
@@ -87,7 +89,13 @@ func (d *systemDevice) startLocked() error {
}
d.device = tunInterface
d.options.Logger.Info("started at ", d.options.Name)
go d.readLoop(tunInterface, int(d.options.MTU))
readLoopDone := make(chan struct{})
d.readLoopDone = readLoopDone
mtu := int(d.options.MTU)
go func() {
d.readLoop(tunInterface, mtu)
close(readLoopDone)
}()
return nil
}
@@ -239,8 +247,15 @@ func (d *systemDevice) UpdateConfiguration(configuration Configuration) error {
}
if !slices.Equal(previousConfiguration.Addresses, configuration.Addresses) ||
previousMTU != updatedMTU {
d.device.Close()
oldDevice := d.device
readLoopDone := d.readLoopDone
d.device = nil
d.reconfiguring = true
d.stateAccess.Unlock()
oldDevice.Close()
<-readLoopDone
d.stateAccess.Lock()
d.reconfiguring = false
return d.startLocked()
}
return nil
@@ -253,8 +268,12 @@ func (d *systemDevice) WriteInboundBuffers(packetBuffers []*buf.Buffer) error {
func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error {
d.stateAccess.RLock()
tunInterface := d.device
reconfiguring := d.reconfiguring
d.stateAccess.RUnlock()
if tunInterface == nil {
if reconfiguring {
return nil
}
return E.New("system device is not ready")
}
linuxTUN, isLinuxTUN := tunInterface.(tun.LinuxTUN)
@@ -296,8 +315,12 @@ func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error {
func (d *systemDevice) writePacket(packet []byte) error {
d.stateAccess.RLock()
tunInterface := d.device
reconfiguring := d.reconfiguring
d.stateAccess.RUnlock()
if tunInterface == nil {
if reconfiguring {
return nil
}
return E.New("system device is not ready")
}
if tun.PacketOffset == 0 {
+32 -9
View File
@@ -29,13 +29,15 @@ const (
type systemDevice struct {
baseDevice
stateAccess sync.RWMutex
options DeviceOptions
dialer N.Dialer
device tun.Tun
inet4Address netip.Addr
inet6Address netip.Addr
closed bool
stateAccess sync.RWMutex
options DeviceOptions
dialer N.Dialer
device tun.Tun
readLoopDone chan struct{}
reconfiguring bool
inet4Address netip.Addr
inet6Address netip.Addr
closed bool
}
func newSystemDevice(options DeviceOptions) (*systemDevice, error) {
@@ -87,7 +89,13 @@ func (d *systemDevice) startLocked() error {
}
d.device = tunInterface
d.options.Logger.Info("started at ", d.options.Name)
go d.readLoop(tunInterface, int(d.options.MTU))
readLoopDone := make(chan struct{})
d.readLoopDone = readLoopDone
mtu := int(d.options.MTU)
go func() {
d.readLoop(tunInterface, mtu)
close(readLoopDone)
}()
return nil
}
@@ -254,8 +262,15 @@ func (d *systemDevice) UpdateConfiguration(configuration Configuration) error {
}
if !slices.Equal(previousConfiguration.Address, configuration.Address) ||
previousMTU != updatedMTU {
d.device.Close()
oldDevice := d.device
readLoopDone := d.readLoopDone
d.device = nil
d.reconfiguring = true
d.stateAccess.Unlock()
oldDevice.Close()
<-readLoopDone
d.stateAccess.Lock()
d.reconfiguring = false
return d.startLocked()
}
return nil
@@ -274,8 +289,12 @@ func (d *systemDevice) WriteInboundBuffers(packetBuffers []*buf.Buffer) error {
func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error {
d.stateAccess.RLock()
tunInterface := d.device
reconfiguring := d.reconfiguring
d.stateAccess.RUnlock()
if tunInterface == nil {
if reconfiguring {
return nil
}
return E.New("system device is not ready")
}
linuxTUN, isLinuxTUN := tunInterface.(tun.LinuxTUN)
@@ -317,8 +336,12 @@ func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error {
func (d *systemDevice) writePacket(packet []byte) error {
d.stateAccess.RLock()
tunInterface := d.device
reconfiguring := d.reconfiguring
d.stateAccess.RUnlock()
if tunInterface == nil {
if reconfiguring {
return nil
}
return E.New("system device is not ready")
}
if tun.PacketOffset == 0 {
+1 -1
View File
@@ -170,7 +170,7 @@ func (w *systemStackDevice) writeStack(packet []byte) bool {
destination = netip.AddrFrom16(header.IPv6(packet).DestinationAddress().As16())
}
for _, prefix := range w.options.Address {
if prefix.Contains(destination) {
if destination == prefix.Addr() {
return false
}
}