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

fix: race condition when opening multiple connections in parallel as first action #59

Merged
merged 4 commits into from
Nov 2, 2021
Merged
Show file tree
Hide file tree
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
79 changes: 65 additions & 14 deletions driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"

"cloud.google.com/go/civil"
Expand Down Expand Up @@ -55,11 +57,13 @@ var dsnRegExp = regexp.MustCompile("((?P<HOSTGROUP>[\\w.-]+(?:\\.[\\w\\.-]+)*[\\
var _ driver.DriverContext = &Driver{}

func init() {
sql.Register("spanner", &Driver{})
sql.Register("spanner", &Driver{connectors: make(map[string]*connector)})
}

// Driver represents a Google Cloud Spanner database/sql driver.
type Driver struct {
mu sync.Mutex
connectors map[string]*connector
}

// Open opens a connection to a Google Cloud Spanner database.
Expand Down Expand Up @@ -132,6 +136,7 @@ func extractConnectorParams(paramsString string) (map[string]string, error) {

type connector struct {
driver *Driver
dsn string
connectorConfig connectorConfig

// spannerClientConfig represents the optional advanced configuration to be used
Expand All @@ -146,9 +151,22 @@ type connector struct {
// retried internally (when possible), or whether all aborted errors will be
// propagated to the caller. This option is enabled by default.
retryAbortsInternally bool

initClient sync.Once
client *spanner.Client
clientErr error
adminClient *adminapi.DatabaseAdminClient
adminClientErr error
connCount int32
}

func newConnector(d *Driver, dsn string) (*connector, error) {
d.mu.Lock()
defer d.mu.Unlock()
if c, ok := d.connectors[dsn]; ok {
return c, nil
}

connectorConfig, err := extractConnectorConfig(dsn)
if err != nil {
return nil, err
Expand All @@ -174,13 +192,31 @@ func newConnector(d *Driver, dsn string) (*connector, error) {
config := spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
}
return &connector{
if strval, ok := connectorConfig.params["minsessions"]; ok {
if val, err := strconv.ParseUint(strval, 10, 64); err == nil {
config.MinOpened = val
}
}
if strval, ok := connectorConfig.params["maxsessions"]; ok {
if val, err := strconv.ParseUint(strval, 10, 64); err == nil {
config.MaxOpened = val
}
}
if strval, ok := connectorConfig.params["writesessions"]; ok {
if val, err := strconv.ParseFloat(strval, 64); err == nil {
config.WriteSessions = val
}
}
c := &connector{
driver: d,
dsn: dsn,
connectorConfig: connectorConfig,
spannerClientConfig: config,
options: opts,
retryAbortsInternally: retryAbortsInternally,
}, nil
}
d.connectors[dsn] = c
return c, nil
}

func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
Expand All @@ -194,18 +230,22 @@ func openDriverConn(ctx context.Context, c *connector) (driver.Conn, error) {
c.connectorConfig.project,
c.connectorConfig.instance,
c.connectorConfig.database)
client, err := spanner.NewClientWithConfig(ctx, databaseName, c.spannerClientConfig, opts...)
if err != nil {
return nil, err
}

adminClient, err := adminapi.NewDatabaseAdminClient(ctx, opts...)
if err != nil {
return nil, err
c.initClient.Do(func() {
c.client, c.clientErr = spanner.NewClientWithConfig(ctx, databaseName, c.spannerClientConfig, opts...)
c.adminClient, c.adminClientErr = adminapi.NewDatabaseAdminClient(ctx, opts...)
})
if c.clientErr != nil {
return nil, c.clientErr
}
if c.adminClientErr != nil {
return nil, c.adminClientErr
}
atomic.AddInt32(&c.connCount, 1)
return &conn{
client: client,
adminClient: adminClient,
connector: c,
client: c.client,
adminClient: c.adminClient,
database: databaseName,
retryAborts: c.retryAbortsInternally,
execSingleQuery: queryInSingleUse,
Expand All @@ -215,7 +255,7 @@ func openDriverConn(ctx context.Context, c *connector) (driver.Conn, error) {
}

func (c *connector) Driver() driver.Driver {
return &Driver{}
return c.driver
}

// SpannerConn is the public interface for the raw Spanner connection for the
Expand Down Expand Up @@ -295,6 +335,7 @@ type SpannerConn interface {
}

type conn struct {
connector *connector
closed bool
client *spanner.Client
adminClient *adminapi.DatabaseAdminClient
Expand Down Expand Up @@ -787,8 +828,18 @@ func (c *conn) ExecContext(ctx context.Context, query string, args []driver.Name
}

func (c *conn) Close() error {
// Check if this is the last open connection of the connector.
if count := atomic.AddInt32(&c.connector.connCount, -1); count > 0 {
return nil
}

// This was the last connection. Remove the connector and close the Spanner clients.
c.connector.driver.mu.Lock()
delete(c.connector.driver.connectors, c.connector.dsn)
c.connector.driver.mu.Unlock()

c.client.Close()
return nil
return c.adminClient.Close()
}

func (c *conn) Begin() (driver.Tx, error) {
Expand Down
85 changes: 72 additions & 13 deletions driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,56 +22,70 @@ import (

"cloud.google.com/go/spanner"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"google.golang.org/grpc/codes"
)

func TestExtractDnsParts(t *testing.T) {
tests := []struct {
input string
want connectorConfig
wantErr error
input string
wantConnectorConfig connectorConfig
wantSpannerConfig spanner.ClientConfig
wantErr error
}{
{
input: "projects/p/instances/i/databases/d",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
project: "p",
instance: "i",
database: "d",
params: map[string]string{},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "projects/DEFAULT_PROJECT_ID/instances/test-instance/databases/test-database",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
project: "DEFAULT_PROJECT_ID",
instance: "test-instance",
database: "test-database",
params: map[string]string{},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "localhost:9010/projects/p/instances/i/databases/d",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
host: "localhost:9010",
project: "p",
instance: "i",
database: "d",
params: map[string]string{},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "spanner.googleapis.com/projects/p/instances/i/databases/d",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
host: "spanner.googleapis.com",
project: "p",
instance: "i",
database: "d",
params: map[string]string{},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "spanner.googleapis.com/projects/p/instances/i/databases/d?usePlainText=true",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
host: "spanner.googleapis.com",
project: "p",
instance: "i",
Expand All @@ -80,10 +94,13 @@ func TestExtractDnsParts(t *testing.T) {
"useplaintext": "true",
},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "spanner.googleapis.com/projects/p/instances/i/databases/d;credentials=/path/to/credentials.json",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
host: "spanner.googleapis.com",
project: "p",
instance: "i",
Expand All @@ -92,10 +109,13 @@ func TestExtractDnsParts(t *testing.T) {
"credentials": "/path/to/credentials.json",
},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "spanner.googleapis.com/projects/p/instances/i/databases/d?credentials=/path/to/credentials.json;readonly=true",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
host: "spanner.googleapis.com",
project: "p",
instance: "i",
Expand All @@ -105,10 +125,13 @@ func TestExtractDnsParts(t *testing.T) {
"readonly": "true",
},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "spanner.googleapis.com/projects/p/instances/i/databases/d?usePlainText=true;",
want: connectorConfig{
wantConnectorConfig: connectorConfig{
host: "spanner.googleapis.com",
project: "p",
instance: "i",
Expand All @@ -117,15 +140,51 @@ func TestExtractDnsParts(t *testing.T) {
"useplaintext": "true",
},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
},
},
{
input: "spanner.googleapis.com/projects/p/instances/i/databases/d?minSessions=200;maxSessions=1000;writeSessions=0.5",
wantConnectorConfig: connectorConfig{
host: "spanner.googleapis.com",
project: "p",
instance: "i",
database: "d",
params: map[string]string{
"minsessions": "200",
"maxsessions": "1000",
"writesessions": "0.5",
},
},
wantSpannerConfig: spanner.ClientConfig{
SessionPoolConfig: spanner.SessionPoolConfig{
MinOpened: 200,
MaxOpened: 1000,
WriteSessions: 0.5,
HealthCheckInterval: spanner.DefaultSessionPoolConfig.HealthCheckInterval,
HealthCheckWorkers: spanner.DefaultSessionPoolConfig.HealthCheckWorkers,
MaxBurst: spanner.DefaultSessionPoolConfig.MaxBurst,
MaxIdle: spanner.DefaultSessionPoolConfig.MaxIdle,
TrackSessionHandles: spanner.DefaultSessionPoolConfig.TrackSessionHandles,
},
},
},
}
for _, tc := range tests {
config, err := extractConnectorConfig(tc.input)
if err != nil {
t.Errorf("extract failed for %q: %v", tc.input, err)
} else {
if !cmp.Equal(config, tc.want, cmp.AllowUnexported(connectorConfig{})) {
t.Errorf("connector config mismatch for %q\ngot: %v\nwant %v", tc.input, config, tc.want)
if !cmp.Equal(config, tc.wantConnectorConfig, cmp.AllowUnexported(connectorConfig{})) {
t.Errorf("connector config mismatch for %q\ngot: %v\nwant %v", tc.input, config, tc.wantConnectorConfig)
}
conn, err := newConnector(&Driver{connectors: make(map[string]*connector)}, tc.input)
if err != nil {
t.Errorf("failed to get connector for %q: %v", tc.input, err)
}
if !cmp.Equal(conn.spannerClientConfig, tc.wantSpannerConfig, cmpopts.IgnoreUnexported(spanner.ClientConfig{}, spanner.SessionPoolConfig{})) {
t.Errorf("connector Spanner client config mismatch for %q\n Got: %v\nWant: %v", tc.input, conn.spannerClientConfig, tc.wantSpannerConfig)
}
}
}
Expand Down
Loading