On client CloseWrite, do CloseWrite instead of Close for backend
Co-authored-by: Mathieu Lonjaret <mathieu.lonjaret@gmail.com>
This commit is contained in:
parent
401b3afa3b
commit
b55be9fdea
25 changed files with 393 additions and 36 deletions
|
@ -3,28 +3,32 @@ package tcp
|
|||
import (
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/containous/traefik/v2/pkg/log"
|
||||
)
|
||||
|
||||
// Proxy forwards a TCP request to a TCP service
|
||||
type Proxy struct {
|
||||
target *net.TCPAddr
|
||||
target *net.TCPAddr
|
||||
terminationDelay time.Duration
|
||||
}
|
||||
|
||||
// NewProxy creates a new Proxy
|
||||
func NewProxy(address string) (*Proxy, error) {
|
||||
func NewProxy(address string, terminationDelay time.Duration) (*Proxy, error) {
|
||||
tcpAddr, err := net.ResolveTCPAddr("tcp", address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Proxy{target: tcpAddr}, nil
|
||||
return &Proxy{target: tcpAddr, terminationDelay: terminationDelay}, nil
|
||||
}
|
||||
|
||||
// ServeTCP forwards the connection to a service
|
||||
func (p *Proxy) ServeTCP(conn net.Conn) {
|
||||
func (p *Proxy) ServeTCP(conn WriteCloser) {
|
||||
log.Debugf("Handling connection from %s", conn.RemoteAddr())
|
||||
|
||||
// needed because of e.g. server.trackedConnection
|
||||
defer conn.Close()
|
||||
|
||||
connBackend, err := net.DialTCP("tcp", nil, p.target)
|
||||
|
@ -32,19 +36,35 @@ func (p *Proxy) ServeTCP(conn net.Conn) {
|
|||
log.Errorf("Error while connection to backend: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// maybe not needed, but just in case
|
||||
defer connBackend.Close()
|
||||
|
||||
errChan := make(chan error, 1)
|
||||
go connCopy(conn, connBackend, errChan)
|
||||
go connCopy(connBackend, conn, errChan)
|
||||
errChan := make(chan error)
|
||||
go p.connCopy(conn, connBackend, errChan)
|
||||
go p.connCopy(connBackend, conn, errChan)
|
||||
|
||||
err = <-errChan
|
||||
if err != nil {
|
||||
log.Errorf("Error during connection: %v", err)
|
||||
log.WithoutContext().Errorf("Error during connection: %v", err)
|
||||
}
|
||||
|
||||
<-errChan
|
||||
}
|
||||
|
||||
func connCopy(dst, src net.Conn, errCh chan error) {
|
||||
func (p Proxy) connCopy(dst, src WriteCloser, errCh chan error) {
|
||||
_, err := io.Copy(dst, src)
|
||||
errCh <- err
|
||||
|
||||
errClose := dst.CloseWrite()
|
||||
if errClose != nil {
|
||||
log.WithoutContext().Errorf("Error while terminating connection: %v", errClose)
|
||||
}
|
||||
|
||||
if p.terminationDelay >= 0 {
|
||||
err := dst.SetReadDeadline(time.Now().Add(p.terminationDelay))
|
||||
if err != nil {
|
||||
log.WithoutContext().Errorf("Error while setting deadline: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue