Skip to content

Commit 4eb009c

Browse files
tcp: ignore ENOPROTOOPT returned by SetKeepAlive on some platforms
Signed-off-by: Achille Roussel <[email protected]>
1 parent 65ed3c5 commit 4eb009c

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

connector.go

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@ package mysql
1111
import (
1212
"context"
1313
"database/sql/driver"
14+
"errors"
1415
"fmt"
1516
"net"
1617
"os"
1718
"strconv"
1819
"strings"
20+
"syscall"
1921
)
2022

2123
type connector struct {
@@ -98,13 +100,11 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
98100
}
99101

100102
// Enable TCP Keepalives on TCP connections
101-
if tc, ok := mc.netConn.(*net.TCPConn); ok {
102-
if err := tc.SetKeepAlive(true); err != nil {
103-
// Don't send COM_QUIT before handshake.
104-
mc.netConn.Close()
105-
mc.netConn = nil
106-
return nil, err
107-
}
103+
if err := enableKeepAlive(mc.netConn); err != nil {
104+
// Don't send COM_QUIT before handshake.
105+
mc.netConn.Close()
106+
mc.netConn = nil
107+
return nil, err
108108
}
109109

110110
// Call startWatcher for context support (From Go 1.8)
@@ -188,3 +188,18 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
188188
func (c *connector) Driver() driver.Driver {
189189
return &MySQLDriver{}
190190
}
191+
192+
func enableKeepAlive(nc net.Conn) error {
193+
if tc, ok := nc.(*net.TCPConn); ok {
194+
if err := tc.SetKeepAlive(true); err != nil {
195+
// The underlying setsockopt syscall may return ENOPROTOOPT if the
196+
// system does not support TCP keep-alive. We can still successfully
197+
// use the driver without keep-alive support, which is why we choose
198+
// to silence it here.
199+
if !errors.Is(err, syscall.ENOPROTOOPT) {
200+
return err
201+
}
202+
}
203+
}
204+
return nil
205+
}

0 commit comments

Comments
 (0)