Skip to content

Fix connection leak caused by rapid context cancellation #1024

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

Merged
merged 3 commits into from
Nov 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
// Call startWatcher for context support (From Go 1.8)
mc.startWatcher()
if err := mc.watchCancel(ctx); err != nil {
mc.cleanup()
return nil, err
}
defer mc.finish()
Expand Down
53 changes: 53 additions & 0 deletions driver_go110_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,56 @@ func TestConnectorTimeoutsDuringOpen(t *testing.T) {
t.Fatalf("(*Connector).Connect should have timed out")
}
}

// A connection which can only be closed.
type dummyConnection struct {
net.Conn
closed bool
}

func (d *dummyConnection) Close() error {
d.closed = true
return nil
}

func TestConnectorTimeoutsWatchCancel(t *testing.T) {
var (
cancel func() // Used to cancel the context just after connecting.
created *dummyConnection // The created connection.
)

RegisterDialContext("TestConnectorTimeoutsWatchCancel", func(ctx context.Context, addr string) (net.Conn, error) {
// Canceling at this time triggers the watchCancel error branch in Connect().
cancel()
created = &dummyConnection{}
return created, nil
})

mycnf := NewConfig()
mycnf.User = "root"
mycnf.Addr = "foo"
mycnf.Net = "TestConnectorTimeoutsWatchCancel"

conn, err := NewConnector(mycnf)
if err != nil {
t.Fatal(err)
}

db := sql.OpenDB(conn)
defer db.Close()

var ctx context.Context
ctx, cancel = context.WithCancel(context.Background())
defer cancel()

if _, err := db.Conn(ctx); err != context.Canceled {
t.Errorf("got %v, want context.Canceled", err)
}

if created == nil {
t.Fatal("no connection created")
}
if !created.closed {
t.Errorf("connection not closed")
}
}