introduce net.Conn deadlines to avoid hung connections (#4164)

fixes #4133
This commit is contained in:
Harshavardhana
2022-07-27 08:21:05 -07:00
committed by GitHub
parent 9de421ffd4
commit c7570bd54a
7 changed files with 271 additions and 33 deletions
+7 -5
View File
@@ -184,11 +184,13 @@ func probeS3Signature(ctx context.Context, accessKey, secretKey, url string, pee
// Test s3 connection for API auto probe
s3Config := &Config{
// S3 connection parameters
Insecure: globalInsecure,
AccessKey: accessKey,
SecretKey: secretKey,
HostURL: urlJoinPath(url, probeBucketName),
Debug: globalDebug,
Insecure: globalInsecure,
AccessKey: accessKey,
SecretKey: secretKey,
HostURL: urlJoinPath(url, probeBucketName),
Debug: globalDebug,
ConnReadDeadline: globalConnReadDeadline,
ConnWriteDeadline: globalConnWriteDeadline,
}
if peerCert != nil {
configurePeerCertificate(s3Config, peerCert)
+29 -6
View File
@@ -38,6 +38,7 @@ import (
"sync"
"time"
"github.com/minio/mc/pkg/deadlineconn"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
@@ -88,6 +89,29 @@ const (
AmzObjectLockLegalHold = "X-Amz-Object-Lock-Legal-Hold"
)
type dialContext func(ctx context.Context, network, addr string) (net.Conn, error)
// newCustomDialContext setups a custom dialer for any external communication and proxies.
func newCustomDialContext(c *Config) dialContext {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
}
conn, err := dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
dconn := deadlineconn.New(conn).
WithReadDeadline(c.ConnReadDeadline).
WithWriteDeadline(c.ConnWriteDeadline)
return dconn, nil
}
}
var timeSentinel = time.Unix(0, 0).UTC()
// newFactory encloses New function with client cache.
@@ -145,12 +169,11 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
}).DialContext,
MaxIdleConnsPerHost: 256,
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
+13 -11
View File
@@ -209,17 +209,19 @@ type ClientContent struct {
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
type Config struct {
AccessKey string
SecretKey string
SessionToken string
Signature string
HostURL string
AppName string
AppVersion string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
Transport *http.Transport
AccessKey string
SecretKey string
SessionToken string
Signature string
HostURL string
AppName string
AppVersion string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
ConnReadDeadline time.Duration
ConnWriteDeadline time.Duration
Transport *http.Transport
}
// SelectObjectOpts - opts entered for select API
+14
View File
@@ -18,6 +18,8 @@
package cmd
import (
"time"
"github.com/minio/cli"
)
@@ -48,6 +50,18 @@ var globalFlags = []cli.Flag{
Name: "insecure",
Usage: "disable SSL certificate verification",
},
cli.DurationFlag{
Name: "conn-read-deadline",
Usage: "custom connection READ deadline",
Hidden: true,
Value: 10 * time.Minute,
},
cli.DurationFlag{
Name: "conn-write-deadline",
Usage: "custom connection WRITE deadline",
Hidden: true,
Value: 10 * time.Minute,
},
}
// Flags common across all I/O commands such as cp, mirror, stat, pipe etc.
+14 -11
View File
@@ -22,6 +22,7 @@ import (
"context"
"crypto/x509"
"net/url"
"time"
"github.com/minio/cli"
"github.com/minio/pkg/console"
@@ -65,6 +66,9 @@ var (
globalDevMode = false // dev flag set via command line
globalSubnetProxyURL *url.URL // Proxy to be used for communication with subnet
globalConnReadDeadline time.Duration
globalConnWriteDeadline time.Duration
globalContext, globalCancel = context.WithCancel(context.Background())
)
@@ -77,7 +81,14 @@ var (
)
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
func setGlobals(quiet, debug, json, noColor, insecure, devMode bool) {
func setGlobalsFromContext(ctx *cli.Context) error {
quiet := ctx.IsSet("quiet") || ctx.GlobalIsSet("quiet")
debug := ctx.IsSet("debug") || ctx.GlobalIsSet("debug")
json := ctx.IsSet("json") || ctx.GlobalIsSet("json")
noColor := ctx.IsSet("no-color") || ctx.GlobalIsSet("no-color")
insecure := ctx.IsSet("insecure") || ctx.GlobalIsSet("insecure")
devMode := ctx.IsSet("dev") || ctx.GlobalIsSet("dev")
globalQuiet = globalQuiet || quiet
globalDebug = globalDebug || debug
globalJSONLine = !isTerminal() && json
@@ -90,17 +101,9 @@ func setGlobals(quiet, debug, json, noColor, insecure, devMode bool) {
if globalNoColor || globalQuiet {
console.SetColorOff()
}
}
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
func setGlobalsFromContext(ctx *cli.Context) error {
quiet := ctx.IsSet("quiet") || ctx.GlobalIsSet("quiet")
debug := ctx.IsSet("debug") || ctx.GlobalIsSet("debug")
json := ctx.IsSet("json") || ctx.GlobalIsSet("json")
noColor := ctx.IsSet("no-color") || ctx.GlobalIsSet("no-color")
insecure := ctx.IsSet("insecure") || ctx.GlobalIsSet("insecure")
devMode := ctx.IsSet("dev") || ctx.GlobalIsSet("dev")
globalConnReadDeadline = ctx.Duration("conn-read-deadline")
globalConnWriteDeadline = ctx.Duration("conn-write-deadline")
setGlobals(quiet, debug, json, noColor, insecure, devMode)
return nil
}
+77
View File
@@ -0,0 +1,77 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Package deadlineconn implements net.Conn wrapper with configured deadlines.
package deadlineconn
import (
"net"
"time"
)
// DeadlineConn - is a generic stream-oriented network connection supporting buffered reader and read/write timeout.
type DeadlineConn struct {
net.Conn
readDeadline time.Duration // sets the read deadline on a connection.
writeDeadline time.Duration // sets the write deadline on a connection.
}
// Sets read deadline
func (c *DeadlineConn) setReadDeadline() {
if c.readDeadline > 0 {
c.SetReadDeadline(time.Now().UTC().Add(c.readDeadline))
}
}
func (c *DeadlineConn) setWriteDeadline() {
if c.writeDeadline > 0 {
c.SetWriteDeadline(time.Now().UTC().Add(c.writeDeadline))
}
}
// Read - reads data from the connection using wrapped buffered reader.
func (c *DeadlineConn) Read(b []byte) (n int, err error) {
c.setReadDeadline()
n, err = c.Conn.Read(b)
return n, err
}
// Write - writes data to the connection.
func (c *DeadlineConn) Write(b []byte) (n int, err error) {
c.setWriteDeadline()
n, err = c.Conn.Write(b)
return n, err
}
// WithReadDeadline sets a new read side net.Conn deadline.
func (c *DeadlineConn) WithReadDeadline(d time.Duration) *DeadlineConn {
c.readDeadline = d
return c
}
// WithWriteDeadline sets a new write side net.Conn deadline.
func (c *DeadlineConn) WithWriteDeadline(d time.Duration) *DeadlineConn {
c.writeDeadline = d
return c
}
// New - creates a new connection object wrapping net.Conn with deadlines.
func New(c net.Conn) *DeadlineConn {
return &DeadlineConn{
Conn: c,
}
}
+117
View File
@@ -0,0 +1,117 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package deadlineconn
import (
"bufio"
"io"
"net"
"sync"
"testing"
"time"
)
// Test deadlineconn handles read timeout properly by reading two messages beyond deadline.
func TestBuffConnReadTimeout(t *testing.T) {
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("unable to create listener. %v", err)
}
defer l.Close()
serverAddr := l.Addr().String()
tcpListener, ok := l.(*net.TCPListener)
if !ok {
t.Fatalf("failed to assert to net.TCPListener")
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
tcpConn, terr := tcpListener.AcceptTCP()
if terr != nil {
t.Errorf("failed to accept new connection. %v", terr)
return
}
deadlineconn := New(tcpConn)
deadlineconn.WithReadDeadline(time.Second)
deadlineconn.WithWriteDeadline(time.Second)
defer deadlineconn.Close()
// Read a line
b := make([]byte, 12)
_, terr = deadlineconn.Read(b)
if terr != nil {
t.Errorf("failed to read from client. %v", terr)
return
}
received := string(b)
if received != "message one\n" {
t.Errorf(`server: expected: "message one\n", got: %v`, received)
return
}
// Wait for more than read timeout to simulate processing.
time.Sleep(3 * time.Second)
_, terr = deadlineconn.Read(b)
if terr != nil {
t.Errorf("failed to read from client. %v", terr)
return
}
received = string(b)
if received != "message two\n" {
t.Errorf(`server: expected: "message two\n", got: %v`, received)
return
}
// Send a response.
_, terr = io.WriteString(deadlineconn, "messages received\n")
if terr != nil {
t.Errorf("failed to write to client. %v", terr)
return
}
}()
c, err := net.Dial("tcp", serverAddr)
if err != nil {
t.Fatalf("unable to connect to server. %v", err)
}
defer c.Close()
_, err = io.WriteString(c, "message one\n")
if err != nil {
t.Fatalf("failed to write to server. %v", err)
}
_, err = io.WriteString(c, "message two\n")
if err != nil {
t.Fatalf("failed to write to server. %v", err)
}
received, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
t.Fatalf("failed to read from server. %v", err)
}
if received != "messages received\n" {
t.Fatalf(`client: expected: "messages received\n", got: %v`, received)
}
wg.Wait()
}