@@ -1518,14 +1518,11 @@ func (a *agent) runCoordinator(ctx context.Context, tClient tailnetproto.DRPCTai
1518
1518
a .logger .Info (ctx ,"connected to coordination RPC" )
1519
1519
1520
1520
// This allows the Close() routine to wait for the coordinator to gracefully disconnect.
1521
- a . closeMutex . Lock ()
1522
- if a . isClosed () {
1523
- return nil
1521
+ disconnected := a . setCoordDisconnected ()
1522
+ if disconnected == nil {
1523
+ return nil // already closed by something else
1524
1524
}
1525
- disconnected := make (chan struct {})
1526
- a .coordDisconnected = disconnected
1527
1525
defer close (disconnected )
1528
- a .closeMutex .Unlock ()
1529
1526
1530
1527
ctrl := tailnet .NewAgentCoordinationController (a .logger ,network )
1531
1528
coordination := ctrl .New (coordinate )
@@ -1547,6 +1544,17 @@ func (a *agent) runCoordinator(ctx context.Context, tClient tailnetproto.DRPCTai
1547
1544
return <- errCh
1548
1545
}
1549
1546
1547
+ func (a * agent )setCoordDisconnected ()chan struct {} {
1548
+ a .closeMutex .Lock ()
1549
+ defer a .closeMutex .Unlock ()
1550
+ if a .isClosed () {
1551
+ return nil
1552
+ }
1553
+ disconnected := make (chan struct {})
1554
+ a .coordDisconnected = disconnected
1555
+ return disconnected
1556
+ }
1557
+
1550
1558
// runDERPMapSubscriber runs a coordinator and returns if a reconnect should occur.
1551
1559
func (a * agent )runDERPMapSubscriber (ctx context.Context ,tClient tailnetproto.DRPCTailnetClient24 ,network * tailnet.Conn )error {
1552
1560
defer a .logger .Debug (ctx ,"disconnected from derp map RPC" )