Debian Codegraph @

postgres/gcppostgres/gcppostgres.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 gcppostgres provides connections to managed PostgreSQL Cloud SQL instances.
16 // See https://cloud.google.com/sql/docs/postgres/ for more information.
17 //
18 // # URLs
19 //
20 // For postgres.Open, gcppostgres registers for the scheme "gcppostgres".
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 gcppostgres // import "gocloud.dev/postgres/gcppostgres"
29
30 import (
31 "context"
32 "database/sql"
33 "database/sql/driver"
34 "errors"
35 "fmt"
36 "net"
37 "net/url"
38 "slices"
39 "strings"
40 "sync"
41 "time"
42
43 "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/proxy"
44 "github.com/XSAM/otelsql"
45 "github.com/lib/pq"
46 "gocloud.dev/gcp"
47 "gocloud.dev/gcp/cloudsql"
48 "gocloud.dev/postgres"
49 )
50
51 // Scheme is the URL scheme gcppostgres registers its URLOpener under on
52 // postgres.DefaultMux.
53 const Scheme = "gcppostgres"
54
55 func init() {
56 postgres.DefaultURLMux().RegisterPostgres(Scheme, new(lazyCredsOpener))
57 }
58
59 // lazyCredsOpener obtains Application Default Credentials on the first call
60 // to OpenPostgresURL.
61 type lazyCredsOpener struct {
62 init sync.Once
63 opener *URLOpener
64 err error
65 }
66
67 func (o *lazyCredsOpener) OpenPostgresURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
68 o.init.Do(func() {
69 creds, err := gcp.DefaultCredentials(ctx)
70 if err != nil {
71 o.err = err
72 return
73 }
74 client, err := gcp.NewHTTPClient(gcp.DefaultTransport(), creds.TokenSource)
75 if err != nil {
76 o.err = err
77 return
78 }
79 certSource := cloudsql.NewCertSourceWithIAM(client, creds.TokenSource)
80 o.opener = &URLOpener{CertSource: certSource}
81 })
82 if o.err != nil {
83 return nil, fmt.Errorf("gcppostgres open %v: %v", u, o.err)
84 }
85 return o.opener.OpenPostgresURL(ctx, u)
86 }
87
88 // URLOpener opens GCP PostgreSQL URLs
89 // like "gcppostgres://user:password@myproject/us-central1/instanceId/mydb".
90 type URLOpener struct {
91 // CertSource specifies how the opener will obtain authentication information.
92 // CertSource must not be nil.
93 CertSource proxy.CertSource
94
95 // TraceOpts contains options for OpenTelemetry.
96 TraceOpts []otelsql.Option
97 }
98
99 // OpenPostgresURL opens a new GCP database connection wrapped with OpenTelemetry instrumentation.
100 func (uo *URLOpener) OpenPostgresURL(ctx context.Context, u *url.URL) (*sql.DB, error) {
101 if uo.CertSource == nil {
102 return nil, fmt.Errorf("gcppostgres: URLOpener CertSource is nil")
103 }
104 instance, dbName, err := instanceFromURL(u)
105 if err != nil {
106 return nil, fmt.Errorf("gcppostgres: open %v: %v", u, err)
107 }
108
109 query := u.Query()
110 for k := range query {
111 // Only permit parameters that do not conflict with other behavior.
112 if k == "sslmode" || k == "sslcert" || k == "sslkey" || k == "sslrootcert" {
113 return nil, fmt.Errorf("gcppostgres: open: extra parameter %s not allowed", k)
114 }
115 }
116 query.Set("sslmode", "disable")
117
118 u2 := new(url.URL)
119 *u2 = *u
120 u2.Scheme = "postgres"
121 u2.Host = "cloudsql"
122 u2.Path = "/" + dbName
123 u2.RawQuery = query.Encode()
124 db := sql.OpenDB(connector{
125 client: &proxy.Client{
126 Port: 3307,
127 Certs: uo.CertSource,
128 },
129 instance: instance,
130 pqConn: u2.String(),
131 traceOpts: append([]otelsql.Option(nil), uo.TraceOpts...),
132 })
133 return db, nil
134 }
135
136 func instanceFromURL(u *url.URL) (instance, db string, _ error) {
137 path := u.Host + u.Path // everything after scheme but before query or fragment
138 parts := strings.SplitN(path, "/", 4)
139 if len(parts) < 4 {
140 return "", "", fmt.Errorf("%s is not in the form project/region/instance/dbname", path)
141 }
142 if slices.Contains(parts, "") {
143 return "", "", fmt.Errorf("%s is not in the form project/region/instance/dbname", path)
144 }
145 return parts[0] + ":" + parts[1] + ":" + parts[2], parts[3], nil
146 }
147
148 type pqDriver struct {
149 client *proxy.Client
150 instance string
151 traceOpts []otelsql.Option
152 }
153
154 func (d pqDriver) Open(name string) (driver.Conn, error) {
155 c, _ := d.OpenConnector(name)
156 return c.Connect(context.Background())
157 }
158
159 func (d pqDriver) OpenConnector(name string) (driver.Connector, error) {
160 return connector{d.client, d.instance, name, d.traceOpts}, nil
161 }
162
163 type connector struct {
164 client *proxy.Client
165 instance string
166 pqConn string
167 traceOpts []otelsql.Option
168 }
169
170 func (c connector) Connect(context.Context) (driver.Conn, error) {
171 conn, err := pq.DialOpen(dialer{c.client, c.instance}, c.pqConn)
172 if err != nil {
173 return nil, err
174 }
175 return conn, nil
176 }
177
178 func (c connector) Driver() driver.Driver {
179 return otelsql.WrapDriver(pqDriver{c.client, c.instance, c.traceOpts}, c.traceOpts...)
180 }
181
182 type dialer struct {
183 client *proxy.Client
184 instance string
185 }
186
187 func (d dialer) Dial(network, address string) (net.Conn, error) {
188 return d.client.Dial(d.instance)
189 }
190
191 func (d dialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) {
192 return nil, errors.New("gcppostgres: DialTimeout not supported")
193 }