Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tcp: handle errors returned by SetKeepAlive #1448

Merged
merged 2 commits into from
Jun 13, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
achille-roussel marked this conversation as resolved.
Show resolved Hide resolved
}

// 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
}