Skip to content

Commit

Permalink
fix: remove conn if fails to connect
Browse files Browse the repository at this point in the history
  • Loading branch information
tinyzimmer committed Nov 7, 2023
1 parent e229ad9 commit 4d2f975
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
33 changes: 21 additions & 12 deletions pkg/cmd/daemoncmd/connmgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,28 +251,37 @@ func (m *ConnManager) NewConn(ctx context.Context, req *v1.ConnectRequest) (id s

// Disconnect disconnects the connection for the given ID.
func (m *ConnManager) Disconnect(ctx context.Context, connID string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.mu.RLock()
conn, ok := m.conns[connID]
m.mu.RUnlock()
if !ok {
return ErrNotConnected
}
if !conn.MeshNode().Started() {
// This means disconnect was called before the node
// was started, very likely by the client. We'll end
// up with a stale port assignment for now.
delete(m.conns, connID)
m.RemoveConn(connID)
return ErrNotConnected
}
wgport, err := conn.MeshNode().Network().WireGuard().ListenPort()
if err != nil {
return err
}
delete(m.conns, connID)
delete(m.ports, uint16(wgport))
defer m.RemoveConn(connID)
return conn.Stop(ctx)
}

// RemoveConn removes the connection for the given ID.
func (m *ConnManager) RemoveConn(connID string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.conns, connID)
delete(m.ports, m.portByConnID(connID))
}

func (m *ConnManager) portByConnID(connID string) uint16 {
for port, id := range m.ports {
if id == connID {
return port
}
}
return 0
}

func (m *ConnManager) listConnIDs() []string {
ids := make([]string, 0, len(m.conns))
for id := range m.conns {
Expand Down
1 change: 1 addition & 0 deletions pkg/cmd/daemoncmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func (app *AppDaemon) Connect(ctx context.Context, req *v1.ConnectRequest) (*v1.
app.log.Info("Starting node", "id", connID)
err = node.Start(ctx)
if err != nil {
defer app.connmgr.RemoveConn(connID)
return nil, status.Errorf(codes.Internal, "failed to start node: %v", err)
}
return &v1.ConnectResponse{
Expand Down

0 comments on commit 4d2f975

Please sign in to comment.