Repository navigation
Expand file tree
/
Copy pathgcpmysql.go
More file actions
209 lines (188 loc) · 6.46 KB
/
Copy pathgcpmysql.go
File metadata and controls
209 lines (188 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright 2018 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package gcpmysql provides connections to managed MySQL Cloud SQL instances.
// See https://cloud.google.com/sql/docs/mysql/ for more information.
//
// # URLs
//
// For mysql.Open, gcpmysql registers for the scheme "gcpmysql".
// The default URL opener will create a connection using the default
// credentials from the environment, as described in
// https://cloud.google.com/docs/authentication/production.
// To customize the URL opener, or for more details on the URL format,
// see URLOpener.
//
// # IP Type
//
// By default, connections use auto-IP selection (public IP if available,
// otherwise private IP), matching the behavior of the legacy cloudsql-proxy.
// To use a specific IP type, set URLOpener.IPType or pass the "ip_type" query
// parameter in the URL (requires URLOpener.Dialer to be set):
//
// gcpmysql://user:pass@project/region/instance/dbname?ip_type=psc
//
// Valid values for ip_type: auto, public, private, psc.
//
// See https://gocloud.dev/concepts/urls/ for background information.
package gcpmysql // import "gocloud.dev/mysql/gcpmysql"
import (
"context"
"database/sql"
"fmt"
"net"
"net/url"
"slices"
"strings"
"sync"
"cloud.google.com/go/cloudsqlconn"
"github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
"github.com/XSAM/otelsql"
"github.com/go-sql-driver/mysql"
"gocloud.dev/gcp"
"gocloud.dev/gcp/cloudsql"
cdkmysql "gocloud.dev/mysql"
)
// Scheme is the URL scheme gcpmysql registers its URLOpener under on
// mysql.DefaultMux.
const Scheme = "gcpmysql"
func init() {
cdkmysql.DefaultURLMux().RegisterMySQL(Scheme, new(lazyCredsOpener))
}
// lazyCredsOpener obtains Application Default Credentials on the first call
// to OpenMySQLURL.
type lazyCredsOpener struct {
init sync.Once
opener *URLOpener
err error
}
func (o *lazyCredsOpener) OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
o.init.Do(func() {
creds, err := gcp.DefaultCredentials(ctx)
if err != nil {
o.err = err
return
}
// Ignore cleanup: the dialer lives for the process lifetime in this global opener.
d, _, err := cloudsql.NewDialer(ctx, creds.TokenSource)
if err != nil {
o.err = err
return
}
o.opener = &URLOpener{Dialer: d}
})
if o.err != nil {
return nil, fmt.Errorf("gcpmysql open %v: %w", u.Redacted(), o.err)
}
return o.opener.OpenMySQLURL(ctx, u)
}
// URLOpener opens Cloud MySQL URLs like
// "gcpmysql://user:password@project/region/instance/dbname".
type URLOpener struct {
// Dialer creates Cloud SQL connections using the Cloud SQL Go Connector.
// Supports PSC and explicit IP type selection via the "ip_type" URL query
// parameter. If both Dialer and CertSource are set, Dialer takes precedence.
Dialer *cloudsqlconn.Dialer
// CertSource specifies how the opener will obtain authentication information.
//
// Deprecated: Use Dialer instead. CertSource does not support PSC or
// explicit IP type selection. Ignored if Dialer is also set.
CertSource proxy.CertSource
// TraceOpts contains options for OpenTelemetry.
TraceOpts []otelsql.Option
}
// OpenMySQLURL opens a new GCP database connection wrapped with OpenTelemetry instrumentation.
func (uo *URLOpener) OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
if uo.Dialer == nil && uo.CertSource == nil {
return nil, fmt.Errorf("gcpmysql: URLOpener Dialer and CertSource are both nil")
}
cfg, err := configFromURL(u)
if err != nil {
return nil, fmt.Errorf("gcpmysql: open %v: %w", u.Redacted(), err)
}
if uo.Dialer != nil {
// Cloud SQL Go Connector with IP type and PSC support.
ipType := cloudsql.IPTypeAuto
if s := u.Query().Get("ip_type"); s != "" {
parsed, err := cloudsql.ParseIPType(s)
if err != nil {
return nil, fmt.Errorf("gcpmysql: open %v: %w", u.Redacted(), err)
}
ipType = parsed
}
dialOpts := ipType.DialOptions()
d := uo.Dialer
cfg.DialFunc = func(ctx context.Context, _, addr string) (net.Conn, error) {
// MySQL driver's addr is in the form "[host]:3306" after normalized.
// https://github.com/go-sql-driver/mysql/blob/76c00e35a8d48f8f70f0e7dffe584692bd3fa612/dsn.go#L193-L195
instance, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
return d.Dial(ctx, instance, dialOpts...)
}
} else {
// Legacy path: cloudsql-proxy v1 (no PSC or IP type selection).
client := &proxy.Client{Certs: uo.CertSource, Port: 3307}
cfg.DialFunc = func(ctx context.Context, _, addr string) (net.Conn, error) {
instance, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
return client.DialContext(ctx, instance)
}
}
c, err := mysql.NewConnector(cfg)
if err != nil {
return nil, fmt.Errorf("gcpmysql: open connector for %v: %w", u.Redacted(), err)
}
return otelsql.OpenDB(c, uo.TraceOpts...), nil
}
func configFromURL(u *url.URL) (*mysql.Config, error) {
instance, dbName, err := instanceFromURL(u)
if err != nil {
return nil, err
}
// Strip ip_type from query before passing to MySQL DSN parser.
query := u.Query()
query.Del("ip_type")
var cfg *mysql.Config
switch {
case len(query) > 0:
optDsn := fmt.Sprintf("/%s?%s", dbName, query.Encode())
if cfg, err = mysql.ParseDSN(optDsn); err != nil {
return nil, err
}
default:
cfg = mysql.NewConfig()
}
password, _ := u.User.Password()
cfg.AllowNativePasswords = true
cfg.Net = "tcp"
cfg.Addr = instance
cfg.User = u.User.Username()
cfg.Passwd = password
cfg.DBName = dbName
return cfg, nil
}
func instanceFromURL(u *url.URL) (instance, db string, _ error) {
path := u.Host + u.Path // everything after scheme but before query or fragment
parts := strings.SplitN(path, "/", 4)
if len(parts) < 4 {
return "", "", fmt.Errorf("%s is not in the form project/region/instance/dbname", path)
}
if slices.Contains(parts, "") {
return "", "", fmt.Errorf("%s is not in the form project/region/instance/dbname", path)
}
return parts[0] + ":" + parts[1] + ":" + parts[2], parts[3], nil
}