Skip to content

Commit

Permalink
tcp: ignore ENOPROTOOPT returned by SetKeepAlive on some platforms
Browse files Browse the repository at this point in the history
Signed-off-by: Achille Roussel <[email protected]>
  • Loading branch information
achille-roussel committed Jun 12, 2023
1 parent 65ed3c5 commit 4eb009c
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ package mysql
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"syscall"
)

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

// Enable TCP Keepalives on TCP connections
if tc, ok := mc.netConn.(*net.TCPConn); ok {
if err := tc.SetKeepAlive(true); err != nil {
// Don't send COM_QUIT before handshake.
mc.netConn.Close()
mc.netConn = nil
return nil, err
}
if err := enableKeepAlive(mc.netConn); err != nil {
// Don't send COM_QUIT before handshake.
mc.netConn.Close()
mc.netConn = nil
return nil, err
}

// Call startWatcher for context support (From Go 1.8)
Expand Down Expand Up @@ -188,3 +188,18 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
func (c *connector) Driver() driver.Driver {
return &MySQLDriver{}
}

func enableKeepAlive(nc net.Conn) error {
if tc, ok := nc.(*net.TCPConn); ok {
if err := tc.SetKeepAlive(true); err != nil {
// The underlying setsockopt syscall may return ENOPROTOOPT if the
// system does not support TCP keep-alive. We can still successfully
// use the driver without keep-alive support, which is why we choose
// to silence it here.
if !errors.Is(err, syscall.ENOPROTOOPT) {
return err
}
}
}
return nil
}

0 comments on commit 4eb009c

Please sign in to comment.