Don't leave connections half-opened

This commit is contained in:
Simon Ser 2020-02-18 16:54:06 +01:00
parent 286fb4b18c
commit 8997a70acb
No known key found for this signature in database
GPG Key ID: 0FDE7BE0E88F5E48

View File

@ -134,25 +134,26 @@ func (s *Server) Run() {
upstream := &s.Upstreams[i] upstream := &s.Upstreams[i]
// TODO: retry connecting // TODO: retry connecting
go func() { go func() {
conn, err := connectToUpstream(u, upstream) uc, err := connectToUpstream(u, upstream)
if err != nil { if err != nil {
s.Logger.Printf("failed to connect to upstream server %q: %v", upstream.Addr, err) s.Logger.Printf("failed to connect to upstream server %q: %v", upstream.Addr, err)
return return
} }
conn.register() uc.register()
u.lock.Lock() u.lock.Lock()
u.upstreamConns = append(u.upstreamConns, conn) u.upstreamConns = append(u.upstreamConns, uc)
u.lock.Unlock() u.lock.Unlock()
if err := conn.readMessages(); err != nil { if err := uc.readMessages(); err != nil {
conn.logger.Printf("failed to handle messages: %v", err) uc.logger.Printf("failed to handle messages: %v", err)
} }
uc.Close()
u.lock.Lock() u.lock.Lock()
for i, c := range u.upstreamConns { for i := range u.upstreamConns {
if c == conn { if u.upstreamConns[i] == uc {
u.upstreamConns = append(u.upstreamConns[:i], u.upstreamConns[i+1:]...) u.upstreamConns = append(u.upstreamConns[:i], u.upstreamConns[i+1:]...)
break break
} }
@ -176,19 +177,20 @@ func (s *Server) Serve(ln net.Listener) error {
return fmt.Errorf("failed to accept connection: %v", err) return fmt.Errorf("failed to accept connection: %v", err)
} }
conn := newDownstreamConn(s, netConn) dc := newDownstreamConn(s, netConn)
go func() { go func() {
s.lock.Lock() s.lock.Lock()
s.downstreamConns = append(s.downstreamConns, conn) s.downstreamConns = append(s.downstreamConns, dc)
s.lock.Unlock() s.lock.Unlock()
if err := conn.readMessages(); err != nil { if err := dc.readMessages(); err != nil {
conn.logger.Printf("failed to handle messages: %v", err) dc.logger.Printf("failed to handle messages: %v", err)
} }
dc.Close()
s.lock.Lock() s.lock.Lock()
for i, c := range s.downstreamConns { for i := range s.downstreamConns {
if c == conn { if s.downstreamConns[i] == dc {
s.downstreamConns = append(s.downstreamConns[:i], s.downstreamConns[i+1:]...) s.downstreamConns = append(s.downstreamConns[:i], s.downstreamConns[i+1:]...)
break break
} }