-
Notifications
You must be signed in to change notification settings - Fork 19
/
proxy.go
359 lines (292 loc) · 7.65 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
package mongonet
import "crypto/tls"
import "fmt"
import "io"
import "net"
import "gopkg.in/mgo.v2/bson"
import "github.com/mongodb/slogger/v2/slogger"
type Proxy struct {
config ProxyConfig
connPool *ConnectionPool
logger *slogger.Logger
}
type ProxySession struct {
proxy *Proxy
conn net.Conn
interceptor ProxyInterceptor
logger *slogger.Logger
SSLServerName string
}
type ResponseInterceptor interface {
InterceptMongoToClient(m Message) (Message, error)
}
type ProxyInterceptor interface {
InterceptClientToMongo(m Message) (Message, ResponseInterceptor, error)
Close()
TrackInBytes(int)
TrackOutBytes(int)
}
type ProxyInterceptorFactory interface {
// This has to be thread safe, will be called from many clients
NewInterceptor(ps *ProxySession) (ProxyInterceptor, error)
}
// -----
func (ps *ProxySession) RemoteAddr() net.Addr {
return ps.conn.RemoteAddr()
}
func (ps *ProxySession) GetLogger() *slogger.Logger {
return ps.logger
}
func (ps *ProxySession) ServerPort() int {
return ps.proxy.config.BindPort
}
func (ps *ProxySession) Stats() bson.D {
return bson.D{
{"connectionPool", bson.D{
{"totalCreated", ps.proxy.connPool.totalCreated},
},
},
}
}
func (ps *ProxySession) RespondToCommand(clientMessage Message, doc SimpleBSON) error {
if clientMessage.Header().OpCode == OP_QUERY {
rm := &ReplyMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_REPLY},
0, // flags - error bit
0, // cursor id
0, // StartingFrom
1, // NumberReturned
[]SimpleBSON{doc},
}
return SendMessage(rm, ps.conn)
} else if clientMessage.Header().OpCode == OP_COMMAND {
rm := &CommandReplyMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_COMMAND_REPLY},
doc,
SimpleBSONEmpty(),
[]SimpleBSON{},
}
return SendMessage(rm, ps.conn)
} else {
panic("impossible")
}
}
func (ps *ProxySession) respondWithError(clientMessage Message, err error) error {
ps.logger.Logf(slogger.INFO, "respondWithError %s", err)
if clientMessage.Header().OpCode == OP_QUERY {
errDoc := bson.D{{"$err", err.Error()}, {"ok", 0}}
doc, myErr := SimpleBSONConvert(errDoc)
if myErr != nil {
return myErr
}
rm := &ReplyMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_REPLY},
2, // flags - error bit
0, // cursor id
0, // StartingFrom
1, // NumberReturned
[]SimpleBSON{doc},
}
return SendMessage(rm, ps.conn)
} else if clientMessage.Header().OpCode == OP_COMMAND {
errDoc := bson.D{{"errmsg", err.Error()}, {"ok", 0}}
doc, myErr := SimpleBSONConvert(errDoc)
if myErr != nil {
return myErr
}
rm := &CommandReplyMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_COMMAND_REPLY},
doc,
SimpleBSONEmpty(),
[]SimpleBSON{},
}
return SendMessage(rm, ps.conn)
} else {
panic("impossible")
}
}
func (ps *ProxySession) doLoop(pooledConn *PooledConnection) (*PooledConnection, error) {
m, err := ReadMessage(ps.conn)
if err != nil {
if err == io.EOF {
return pooledConn, err
}
return pooledConn, NewStackErrorf("got error reading from client: %s", err)
}
var respInter ResponseInterceptor
if ps.interceptor != nil {
ps.interceptor.TrackInBytes(int(m.Header().Size))
m, respInter, err = ps.interceptor.InterceptClientToMongo(m)
if err != nil {
if !m.HasResponse() {
// we can't respond, so we just fail
return pooledConn, err
}
err = ps.respondWithError(m, err)
if err != nil {
return pooledConn, NewStackErrorf("couldn't send error response to client %s", err)
}
return pooledConn, nil
}
if m == nil {
// already responded
return pooledConn, nil
}
}
if pooledConn == nil {
pooledConn, err = ps.proxy.connPool.Get()
if err != nil {
return nil, NewStackErrorf("cannot get connection to mongo %s", err)
}
}
if pooledConn.closed {
panic("oh no!")
}
mongoConn := pooledConn.conn
err = SendMessage(m, mongoConn)
if err != nil {
return nil, NewStackErrorf("error writing to mongo: %s", err)
}
if !m.HasResponse() {
return pooledConn, nil
}
defer pooledConn.Close()
inExhaustMode :=
m.Header().OpCode == OP_QUERY &&
m.(*QueryMessage).Flags&(1<<6) != 0
for {
resp, err := ReadMessage(mongoConn)
if err != nil {
pooledConn.bad = true
return nil, NewStackErrorf("got error reading response from mongo %s", err)
}
if respInter != nil {
resp, err = respInter.InterceptMongoToClient(resp)
if err != nil {
return nil, NewStackErrorf("error intercepting message %s", err)
}
}
err = SendMessage(resp, ps.conn)
if err != nil {
return nil, NewStackErrorf("got error sending response to client %s", err)
}
if ps.interceptor != nil {
ps.interceptor.TrackOutBytes(int(m.Header().Size))
}
if !inExhaustMode {
return nil, nil
}
if resp.(*ReplyMessage).CursorId == 0 {
return nil, nil
}
}
}
func (ps *ProxySession) Run() {
var err error
defer ps.conn.Close()
switch c := ps.conn.(type) {
case *tls.Conn:
// we do this here so that we can get the SNI server name
err = c.Handshake()
if err != nil {
ps.logger.Logf(slogger.ERROR, "error doing tls handshake %s", err)
return
}
ps.SSLServerName = c.ConnectionState().ServerName
}
ps.logger.Logf(slogger.INFO, "new connection SSLServerName [%s]", ps.SSLServerName)
if ps.proxy.config.InterceptorFactory != nil {
ps.interceptor, err = ps.proxy.config.InterceptorFactory.NewInterceptor(ps)
if err != nil {
ps.logger.Logf(slogger.INFO, "error creating new interceptor because: %s", err)
return
}
defer ps.interceptor.Close()
}
defer ps.logger.Logf(slogger.INFO, "socket closed")
var pooledConn *PooledConnection = nil
for {
pooledConn, err = ps.doLoop(pooledConn)
if err != nil {
if pooledConn != nil {
pooledConn.Close()
}
if err != io.EOF {
ps.logger.Logf(slogger.WARN, "error doing loop: %s", err)
}
return
}
}
if pooledConn != nil {
pooledConn.Close()
}
}
// -------
func NewProxy(pc ProxyConfig) Proxy {
p := Proxy{pc, NewConnectionPool(pc.MongoAddress(), pc.MongoSSL, pc.ConnectionPoolHook), nil}
p.logger = p.NewLogger("proxy")
return p
}
func (p *Proxy) NewLogger(prefix string) *slogger.Logger {
filters := []slogger.TurboFilter{slogger.TurboLevelFilter(p.config.LogLevel)}
appenders := p.config.Appenders
if appenders == nil {
appenders = []slogger.Appender{slogger.StdOutAppender()}
}
return &slogger.Logger{prefix, appenders, 0, filters}
}
func (p *Proxy) Run() error {
bindTo := fmt.Sprintf("%s:%d", p.config.BindHost, p.config.BindPort)
p.logger.Logf(slogger.WARN, "listening on %s", bindTo)
var err error
var ln net.Listener
if p.config.UseSSL {
if len(p.config.SSLKeys) == 0 {
return fmt.Errorf("no ssl keys configured")
}
certs := []tls.Certificate{}
for _, pair := range p.config.SSLKeys {
cer, err := tls.LoadX509KeyPair(pair.CertFile, pair.KeyFile)
if err != nil {
return fmt.Errorf("cannot LoadX509KeyPair from %s %s %s", pair.CertFile, pair.KeyFile, err)
}
certs = append(certs, cer)
}
config := &tls.Config{Certificates: certs}
config.BuildNameToCertificate()
ln, err = tls.Listen("tcp", bindTo, config)
if err != nil {
return fmt.Errorf("cannot start listen tls in proxy: %s", err)
}
} else {
ln, err = net.Listen("tcp", bindTo)
if err != nil {
return NewStackErrorf("cannot start listening in proxy: %s", err)
}
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
return NewStackErrorf("could not accept in proxy: %s", err)
}
c := &ProxySession{p, conn, nil, p.NewLogger(fmt.Sprintf("ProxySession %s", conn.RemoteAddr())), ""}
go c.Run()
}
}