Debian Codegraph @

mysql/gcpmysql/gcpmysql.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package gcpmysql provides connections to managed MySQL Cloud SQL instances.
16 // See https://cloud.google.com/sql/docs/mysql/ for more information.
17 //
18 // # URLs
19 //
20 // For mysql.Open, gcpmysql registers for the scheme "gcpmysql".
21 // The default URL opener will create a connection using the default
22 // credentials from the environment, as described in
23 // https://cloud.google.com/docs/authentication/production.
24 // To customize the URL opener, or for more details on the URL format,
25 // see URLOpener.
26 //
27 // See https://gocloud.dev/concepts/urls/ for background information.
28 package gcpmysql // import "gocloud.dev/mysql/gcpmysql"
29
30 import (
31 "context"
32 "database/sql"
33 "fmt"
34 "net"
35 "net/url"
36 "slices"
37 "strings"
38 "sync"
39
40 "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
41 "github.com/XSAM/otelsql"
42 "github.com/go-sql-driver/mysql"
43 "gocloud.dev/gcp"
44 "gocloud.dev/gcp/cloudsql"
45 cdkmysql "gocloud.dev/mysql"
46 )
47
48 // Scheme is the URL scheme gcpmysql registers its URLOpener under on
49 // mysql.DefaultMux.
50 const Scheme = "gcpmysql"
51
52 func init() {
53 cdkmysql.DefaultURLMux().RegisterMySQL(Scheme, new(lazyCredsOpener))
54 }
55
56 // lazyCredsOpener obtains Application Default Credentials on the first call
57 // to OpenMySQLURL.
58 type lazyCredsOpener struct {
59 init sync.Once
60 opener *URLOpener
61 err error
62 }
63
64 func (o *lazyCredsOpener) OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
65 o.init.Do(func() {
66 creds, err := gcp.DefaultCredentials(ctx)
67 if err != nil {
68 o.err = err
69 return
70 }
71 client, err := gcp.NewHTTPClient(gcp.DefaultTransport(), creds.TokenSource)
72 if err != nil {
73 o.err = err
74 return
75 }
76 certSource := cloudsql.NewCertSource(client)
77 o.opener = &URLOpener{CertSource: certSource}
78 })
79 if o.err != nil {
80 return nil, fmt.Errorf("gcpmysql open %v: %v", u, o.err)
81 }
82 return o.opener.OpenMySQLURL(ctx, u)
83 }
84
85 // URLOpener opens Cloud MySQL URLs like
86 // "gcpmysql://user:password@project/region/instance/dbname".
87 type URLOpener struct {
88 // CertSource specifies how the opener will obtain authentication information.
89 // CertSource must not be nil.
90 CertSource proxy.CertSource
91
92 // TraceOpts contains options for OpenTelemetry.
93 TraceOpts []otelsql.Option
94 }
95
96 // OpenMySQLURL opens a new GCP database connection wrapped with OpenTelemetry instrumentation.
97 func (uo *URLOpener) OpenMySQLURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
98 if uo.CertSource == nil {
99 return nil, fmt.Errorf("gcpmysql: URLOpener CertSource is nil")
100 }
101 var (
102 client = &proxy.Client{Certs: uo.CertSource, Port: 3307}
103 cfg, err = configFromURL(u)
104 )
105 if err != nil {
106 return nil, fmt.Errorf("gcpmysql: open config %v", err)
107 }
108 cfg.DialFunc = func(ctx context.Context, _, addr string) (net.Conn, error) {
109 // MySQL driver's addr is in the form "[host]:3306" after normalized.
110 // https://github.com/go-sql-driver/mysql/blob/76c00e35a8d48f8f70f0e7dffe584692bd3fa612/dsn.go#L193-L195
111 instance, _, err := net.SplitHostPort(addr)
112 if err != nil {
113 return nil, err
114 }
115 return client.DialContext(ctx, instance)
116 }
117 c, err := mysql.NewConnector(cfg)
118 if err != nil {
119 return nil, fmt.Errorf("gcpmysql: open connector %v", err)
120 }
121 return otelsql.OpenDB(c, uo.TraceOpts...), nil
122 }
123
124 func configFromURL(u *url.URL) (*mysql.Config, error) {
125 instance, dbName, err := instanceFromURL(u)
126 if err != nil {
127 return nil, err
128 }
129
130 var cfg *mysql.Config
131 switch {
132 case len(u.RawQuery) > 0:
133 optDsn := fmt.Sprintf("/%s?%s", dbName, u.RawQuery)
134 if cfg, err = mysql.ParseDSN(optDsn); err != nil {
135 return nil, err
136 }
137 default:
138 cfg = mysql.NewConfig()
139 }
140
141 password, _ := u.User.Password()
142
143 cfg.AllowNativePasswords = true
144 cfg.Net = "tcp"
145 cfg.Addr = instance
146 cfg.User = u.User.Username()
147 cfg.Passwd = password
148 cfg.DBName = dbName
149
150 return cfg, nil
151 }
152
153 func instanceFromURL(u *url.URL) (instance, db string, _ error) {
154 path := u.Host + u.Path // everything after scheme but before query or fragment
155 parts := strings.SplitN(path, "/", 4)
156 if len(parts) < 4 {
157 return "", "", fmt.Errorf("%s is not in the form project/region/instance/dbname", path)
158 }
159 if slices.Contains(parts, "") {
160 return "", "", fmt.Errorf("%s is not in the form project/region/instance/dbname", path)
161 }
162 return parts[0] + ":" + parts[1] + ":" + parts[2], parts[3], nil
163 }