-
Notifications
You must be signed in to change notification settings - Fork 230
/
proxy.go
444 lines (404 loc) · 11.6 KB
/
proxy.go
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package sqldb
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"strings"
"time"
"github.com/jackc/pgproto3/v2"
"github.com/rs/zerolog/log"
"encr.dev/cli/daemon/namespace"
"encr.dev/pkg/fns"
"encr.dev/pkg/pgproxy"
)
// ServeProxy serves the database proxy using the given listener.
func (cm *ClusterManager) ServeProxy(ln net.Listener) error {
var tempDelay time.Duration // how long to sleep on accept failure
for {
conn, e := ln.Accept()
if e != nil {
if ne, ok := e.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
log.Error().Err(e).Msgf("dbproxy: accept error, retrying in %v", tempDelay)
time.Sleep(tempDelay)
continue
}
return fmt.Errorf("dbproxy: could not accept: %v", e)
}
tempDelay = 0
go func() {
if err := cm.ProxyConn(conn, true); err != nil && err != context.Canceled {
log.Error().Err(err).Msg("dbproxy: proxy error")
}
}()
}
}
// ProxyConn authenticates and proxies a conn to the appropriate
// database cluster and database.
// If waitForSetup is true, it will wait for initial setup to complete
// before proxying the connection.
func (cm *ClusterManager) ProxyConn(client net.Conn, waitForSetup bool) error {
defer fns.CloseIgnore(client)
cl, err := pgproxy.SetupClient(client, &pgproxy.ClientConfig{
TLS: nil,
WantPassword: true,
})
if err != nil {
return err
}
if cancel, ok := cl.Hello.(*pgproxy.CancelData); ok {
cm.cancelRequest(client, cancel)
return nil
}
startup := cl.Hello.(*pgproxy.StartupData)
// If the username is "encore" we're connecting to a database cluster
// which may not be local
var cluster *Cluster
if startup.Username == "encore" {
password := startup.Password
found, ok := cm.LookupPassword(password)
if !ok {
cm.log.Error().Msg("dbproxy: could not find cluster")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database cluster not found or invalid connection string",
})
return nil
}
cluster = found
} else {
// The username is the app slug we want to connect to
app, err := cm.apps.FindLatestByPlatformOrLocalID(startup.Username)
if err != nil {
cm.log.Error().Err(err).Msg("dbproxy: could not find app")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "unknown app ID",
})
return nil
}
ctx := context.Background()
clusterType, nsID, ok := strings.Cut(startup.Password, "-")
// Look up the namespace to use.
var ns *namespace.Namespace
if !ok {
ns, err = cm.ns.GetActive(ctx, app)
} else {
ns, err = cm.ns.GetByID(ctx, app, namespace.ID(nsID))
}
if err != nil {
cm.log.Error().Err(err).Msg("dbproxy: could not find infra namespace")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "unknown active infra namespace",
})
return nil
}
// Resolve the cluster type.
var ct ClusterType
switch clusterType {
case "local":
ct = Run
case "test":
ct = Test
case "shadow":
ct = Shadow
default:
cm.log.Error().Str("password", startup.Password).Msg("dbproxy: invalid password for connection URI")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "28P01", // 28P01 = invalid password
Message: "if connecting with an app slug as the username, the only accepted passwords are 'local' or 'test' to route to those instances on your local system",
})
return nil
}
// Create the cluster if it doesn't exist in memory yet
// This might be because the daemon is running, but the hasn't done anything
// with the app in question yet on this run
cluster = cm.Create(context.Background(), &CreateParams{
ClusterID: GetClusterID(app, ct, ns),
Memfs: ct.Memfs(),
})
// Ensure the cluster is started
_, err = cluster.Start(context.Background(), nil)
if err != nil {
cm.log.Error().Err(err).Msg("dbproxy: could not start cluster")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "could not start database cluster",
})
return nil
}
}
// If Encore knows about the database, check if it's ready
// however if the cluster doesn't know about the database, skip this part.
//
// This is because either:
// 1. The database exists and is connected to
// 2. The database does not exist, and the remote server will return a "database doesn't exist" error.
dbname := startup.Database
db, ok := cluster.GetDB(dbname)
if ok {
var ready <-chan struct{}
if waitForSetup {
ready = db.Ready()
} else {
s := make(chan struct{})
close(s)
ready = s
}
// Wait for up to 60s for the cluster and database to come online.
select {
case <-db.Ctx.Done():
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "db is shutting down",
})
return nil
case <-time.After(60 * time.Second):
cm.log.Error().Str("db", db.ApplicationCloudName()).Msg("dbproxy: timed out waiting for database to come online")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "timed out waiting for db to complete setup",
})
return nil
case <-ready:
// Continue connecting to backend, below
}
}
info, err := cluster.Info(context.Background())
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "cluster not running: " + err.Error(),
})
return nil
}
server, err := net.Dial("tcp", info.Config.Host)
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database not running: " + err.Error(),
})
return nil
}
defer fns.CloseIgnore(server)
// Send a modified startup message to the backend
admin, _ := info.Encore.First(RoleAdmin, RoleSuperuser)
startup.Username = admin.Username
startup.Password = admin.Password
if db == nil {
// We don't know about this database, we'll use the requested name
// in case it does actually exist within the cluster.
//
// If it doesn't the cluster will return an SQL error to the client.
startup.Database = dbname
} else {
startup.Database = db.ApplicationCloudName()
}
fe, err := pgproxy.SetupServer(server, &pgproxy.ServerConfig{
TLS: nil,
Startup: startup,
})
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "could not connect: " + err.Error(),
})
return nil
}
log.Trace().Msg("backend connection established, notifying client")
if err := pgproxy.AuthenticateClient(cl.Backend); err != nil {
return err
}
keyData, err := pgproxy.FinalizeInitialHandshake(cl.Backend, fe)
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "could not establish connection: " + err.Error(),
})
return nil
}
log.Trace().Msg("connection handshake completed, proxying steady-state data")
// Store the key data so we know where to route cancellation requests.
if keyData != nil {
cm.mu.Lock()
cm.backendKeyData[keyData.SecretKey] = cluster
cm.mu.Unlock()
defer func() {
cm.mu.Lock()
delete(cm.backendKeyData, keyData.SecretKey)
cm.mu.Unlock()
}()
}
return pgproxy.CopySteadyState(cl.Backend, fe)
}
// PreauthProxyConn is a pre-authenticated proxy conn directly specifically to the given cluster.
func (cm *ClusterManager) PreauthProxyConn(client net.Conn, id ClusterID) error {
defer fns.CloseIgnore(client)
cl, err := pgproxy.SetupClient(client, &pgproxy.ClientConfig{
TLS: &tls.Config{MinVersion: tls.VersionTLS12},
})
if err != nil {
log.Error().Err(err).Msg("failed to setup client")
return err
}
if cancel, ok := cl.Hello.(*pgproxy.CancelData); ok {
cm.cancelRequest(client, cancel)
return nil
}
startup := cl.Hello.(*pgproxy.StartupData)
cluster, ok := cm.Get(id)
if !ok {
cm.log.Error().Interface("cluster", id).Msg("dbproxy: could not find cluster")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database cluster not running",
})
return nil
}
db, ok := cluster.GetDB(startup.Database)
if !ok {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database not found",
})
return nil
}
// Wait for up to 60s for the cluster to come online.
select {
case <-db.Ctx.Done():
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "db is shutting down",
})
return nil
case <-time.After(60 * time.Second):
cm.log.Error().Str("db", startup.Database).Msg("dbproxy: timed out waiting for database to come online")
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "timed out waiting for db to complete setup",
})
return nil
case <-cluster.Ready():
// Continue connecting to backend, below
}
info, err := cluster.Info(context.Background())
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "cluster not running: " + err.Error(),
})
return nil
}
server, err := net.Dial("tcp", info.Config.Host)
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database not running: " + err.Error(),
})
return nil
}
defer fns.CloseIgnore(server)
admin, _ := info.Encore.First(RoleAdmin, RoleSuperuser)
startup.Username = admin.Username
startup.Password = admin.Password
startup.Database = db.ApplicationCloudName()
fe, err := pgproxy.SetupServer(server, &pgproxy.ServerConfig{
TLS: nil,
Startup: startup,
})
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "could not connect: " + err.Error(),
})
return nil
}
if err := pgproxy.AuthenticateClient(cl.Backend); err != nil {
return err
}
keyData, err := pgproxy.FinalizeInitialHandshake(cl.Backend, fe)
if err != nil {
_ = cl.Backend.Send(&pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "could not establish connection: " + err.Error(),
})
return nil
}
// Store the key data so we know where to route cancellation requests.
if keyData != nil {
cm.mu.Lock()
cm.backendKeyData[keyData.SecretKey] = cluster
cm.mu.Unlock()
defer func() {
cm.mu.Lock()
delete(cm.backendKeyData, keyData.SecretKey)
cm.mu.Unlock()
}()
}
log.Trace().Msg("successfully completed handshake, copying data back and forth")
return pgproxy.CopySteadyState(cl.Backend, fe)
}
// cancelRequest handles a cancel request.
func (cm *ClusterManager) cancelRequest(client io.Writer, req *pgproxy.CancelData) {
cm.mu.Lock()
cluster, ok := cm.backendKeyData[req.Raw.SecretKey]
cm.mu.Unlock()
if !ok {
return
}
info, err := cluster.Info(context.Background())
if err != nil {
msg := &pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database cluster not running",
}
_, _ = client.Write(msg.Encode(nil))
return
}
backend, err := net.Dial("tcp", info.Config.Host)
if err != nil {
msg := &pgproto3.ErrorResponse{
Severity: "FATAL",
Code: "08006",
Message: "database cluster not running",
}
_, _ = client.Write(msg.Encode(nil))
return
}
defer fns.CloseIgnore(backend)
_ = pgproxy.SendCancelRequest(backend, req.Raw)
}
func writeMsg(w io.Writer, msg pgproto3.Message) error {
_, err := w.Write(msg.Encode(nil))
return err
}