forked from weaveworks/scope
/
consul_pipe_router.go
445 lines (393 loc) · 11 KB
/
consul_pipe_router.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
445
package multitenant
import (
"fmt"
"io"
"net/http"
"net/url"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"golang.org/x/net/context"
"github.com/weaveworks/common/mtime"
"github.com/weaveworks/scope/app"
"github.com/weaveworks/scope/common/xfer"
)
const (
gcInterval = 30 * time.Second // we check all the pipes every 30s
pipeTimeout = 1 * time.Minute // pipes are closed when a client hasn't been connected for 1 minute
gcTimeout = 10 * time.Minute // after another 10 minutes, tombstoned pipes are forgotten
)
var (
wsDialer = &websocket.Dialer{}
)
// TODO deal with garbage collection
type consulPipe struct {
CreatedAt, DeletedAt time.Time
UIAddr, ProbeAddr string // Addrs where each end is connected
UIRef, ProbeRef int // Ref counts
}
func (c *consulPipe) setAddrFor(e app.End, addr string) {
if e == app.UIEnd {
c.UIAddr = addr
} else {
c.ProbeAddr = addr
}
}
func (c *consulPipe) addrFor(e app.End) string {
if e == app.UIEnd {
return c.UIAddr
}
return c.ProbeAddr
}
func (c *consulPipe) eitherEndFor(addr string) bool {
return c.addrFor(app.UIEnd) == addr || c.addrFor(app.ProbeEnd) == addr
}
func (c *consulPipe) acquire(e app.End) int {
if e == app.UIEnd {
c.UIRef++
return c.UIRef
}
c.ProbeRef++
return c.ProbeRef
}
func (c *consulPipe) release(e app.End) int {
if e == app.UIEnd {
c.UIRef--
return c.UIRef
}
c.ProbeRef--
return c.ProbeRef
}
type consulPipeRouter struct {
prefix string
advertise string // Address of this pipe router to advertise in consul
client ConsulClient
userIDer UserIDer
activePipes map[string]xfer.Pipe
bridges map[string]*bridgeConnection
actorChan chan func()
pipeWaiters map[string][]chan xfer.Pipe
// Used by Stop()
quit chan struct{}
wait sync.WaitGroup
}
// NewConsulPipeRouter returns a new consul based router
func NewConsulPipeRouter(client ConsulClient, prefix, advertise string, userIDer UserIDer) app.PipeRouter {
pipeRouter := &consulPipeRouter{
prefix: prefix,
advertise: advertise,
client: client,
userIDer: userIDer,
activePipes: map[string]xfer.Pipe{},
bridges: map[string]*bridgeConnection{},
actorChan: make(chan func()),
pipeWaiters: map[string][]chan xfer.Pipe{},
quit: make(chan struct{}),
}
pipeRouter.wait.Add(2)
go pipeRouter.watchAll()
go pipeRouter.actor()
go pipeRouter.privateAPI()
return pipeRouter
}
func (pr *consulPipeRouter) Stop() {
close(pr.quit)
pr.wait.Wait()
}
func (pr *consulPipeRouter) actor() {
defer pr.wait.Done()
for {
select {
case f := <-pr.actorChan:
f()
case <-pr.quit:
return
}
}
}
// watchAll listens to all pipe updates from consul.
// This is effectively a distributed, consistent actor routine.
// All state changes for this pipe router happen in this loop,
// and all the methods are implemented as CAS's on consul, to
// trigger an event in this loop.
func (pr *consulPipeRouter) watchAll() {
defer pr.wait.Done()
pr.client.WatchPrefix(pr.prefix, &consulPipe{}, pr.quit, func(key string, value interface{}) bool {
cp := *value.(*consulPipe)
select {
case pr.actorChan <- func() { pr.handlePipeUpdate(key, cp) }:
return true
case <-pr.quit:
return false
}
})
}
func (pr *consulPipeRouter) handlePipeUpdate(key string, cp consulPipe) {
// 1. If this pipe is closed, or we're not one of the ends, we
// should ensure our local pipe (and bridge) is closed.
if !cp.DeletedAt.IsZero() || !cp.eitherEndFor(pr.advertise) {
pipe, ok := pr.activePipes[key]
delete(pr.activePipes, key)
if ok {
log.Infof("Deleting pipe %s", key)
pipe.Close()
}
bridge, ok := pr.bridges[key]
delete(pr.bridges, key)
if ok {
bridge.stop()
}
return
}
if !cp.eitherEndFor(pr.advertise) {
return
}
// 2. If this pipe if for us, we should have a pipe for it.
pipe, ok := pr.activePipes[key]
if !ok {
log.Infof("Creating pipe %s", key)
pipe = xfer.NewPipe()
pr.activePipes[key] = pipe
for _, pw := range pr.pipeWaiters[key] {
pw <- pipe
}
delete(pr.pipeWaiters, key)
}
// 3. Ensure there is a bridging connection for this pipe.
// Semantics are the owner of the UIEnd connects to the owner of the ProbeEnd
shouldBridge := cp.DeletedAt.IsZero() &&
cp.addrFor(app.UIEnd) != cp.addrFor(app.ProbeEnd) &&
cp.addrFor(app.UIEnd) == pr.advertise &&
cp.addrFor(app.ProbeEnd) != ""
bridge, ok := pr.bridges[key]
// If we shouldn't be bridging but are, or we should be bridging but are pointing
// at the wrong place, stop the current bridge.
if (!shouldBridge && ok) || (shouldBridge && ok && bridge.addr != cp.addrFor(app.ProbeEnd)) {
delete(pr.bridges, key)
bridge.stop()
ok = false
}
// If we should be bridging and are not, start a new bridge
if shouldBridge && !ok {
bridge = newBridgeConnection(key, cp.addrFor(app.ProbeEnd), pipe)
pr.bridges[key] = bridge
}
}
func (pr *consulPipeRouter) getPipe(key string) xfer.Pipe {
pc := make(chan xfer.Pipe)
select {
case pr.actorChan <- func() { pc <- pr.activePipes[key] }:
return <-pc
case <-pr.quit:
return nil
}
}
func (pr *consulPipeRouter) waitForPipe(key string) xfer.Pipe {
pc := make(chan xfer.Pipe)
select {
case pr.actorChan <- func() {
pipe, ok := pr.activePipes[key]
if ok {
pc <- pipe
} else {
pr.pipeWaiters[key] = append(pr.pipeWaiters[key], pc)
}
}:
return <-pc
case <-pr.quit:
return nil
}
}
func (pr *consulPipeRouter) privateAPI() {
router := mux.NewRouter()
router.Methods("GET").
MatcherFunc(app.URLMatcher("/private/api/pipe/{key}")).
HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := mux.Vars(r)["key"]
log.Infof("%s: Server bridge connection started", key)
defer log.Infof("%s: Server bridge connection stopped", key)
pipe := pr.getPipe(key)
if pipe == nil {
log.Errorf("%s: Server bridge connection; Unknown pipe!", key)
w.WriteHeader(http.StatusNotFound)
return
}
conn, err := xfer.Upgrade(w, r, nil)
if err != nil {
log.Errorf("%s: Server bridge connection; Error upgrading to websocket: %v", key, err)
return
}
defer conn.Close()
end, _ := pipe.Ends()
if err := pipe.CopyToWebsocket(end, conn); err != nil && !xfer.IsExpectedWSCloseError(err) {
log.Errorf("%s: Server bridge connection; Error copying pipe to websocket: %v", key, err)
}
})
log.Infof("Serving private API on endpoint %s.", pr.advertise)
log.Infof("Private API terminated: %v", http.ListenAndServe(pr.advertise, router))
}
func (pr *consulPipeRouter) Exists(ctx context.Context, id string) (bool, error) {
userID, err := pr.userIDer(ctx)
if err != nil {
return false, err
}
key := fmt.Sprintf("%s%s-%s", pr.prefix, userID, id)
consulPipe := consulPipe{}
err = pr.client.Get(key, &consulPipe)
if err == ErrNotFound {
return false, nil
} else if err != nil {
return false, err
}
return consulPipe.DeletedAt.IsZero(), nil
}
func (pr *consulPipeRouter) Get(ctx context.Context, id string, e app.End) (xfer.Pipe, io.ReadWriter, error) {
userID, err := pr.userIDer(ctx)
if err != nil {
return nil, nil, err
}
key := fmt.Sprintf("%s%s-%s", pr.prefix, userID, id)
log.Infof("Get %s:%s", key, e)
// Try to ensure the given end of the given pipe
// is 'owned' by this pipe service replica in consul.
err = pr.client.CAS(key, &consulPipe{}, func(in interface{}) (interface{}, bool, error) {
var pipe *consulPipe
if in == nil {
pipe = &consulPipe{
CreatedAt: mtime.Now(),
}
} else {
pipe = in.(*consulPipe)
}
if !pipe.DeletedAt.IsZero() {
return nil, false, fmt.Errorf("Pipe %s has been deleted", key)
}
end := pipe.addrFor(e)
if end != "" && end != pr.advertise {
return nil, true, fmt.Errorf("Error: Pipe %s has existing connection to %s", key, end)
}
pipe.setAddrFor(e, pr.advertise)
pipe.acquire(e)
return pipe, false, nil
})
if err != nil {
return nil, nil, err
}
pipe := pr.waitForPipe(key)
myEnd, _ := pipe.Ends()
if e == app.ProbeEnd {
_, myEnd = pipe.Ends()
}
return pipe, myEnd, nil
}
func (pr *consulPipeRouter) Release(ctx context.Context, id string, e app.End) error {
userID, err := pr.userIDer(ctx)
if err != nil {
return err
}
key := fmt.Sprintf("%s%s-%s", pr.prefix, userID, id)
log.Infof("Release %s:%s", key, e)
// atomically clear my end of the pipe in consul
return pr.client.CAS(key, &consulPipe{}, func(in interface{}) (interface{}, bool, error) {
if in == nil {
return nil, false, fmt.Errorf("pipe %s not found", id)
}
p := in.(*consulPipe)
if p.addrFor(e) != pr.advertise {
return nil, false, fmt.Errorf("pipe %s not owned by us", id)
}
refs := p.release(e)
if refs == 0 {
p.setAddrFor(e, "")
}
return p, true, nil
})
}
func (pr *consulPipeRouter) Delete(ctx context.Context, id string) error {
userID, err := pr.userIDer(ctx)
if err != nil {
return err
}
key := fmt.Sprintf("%s%s-%s", pr.prefix, userID, id)
log.Infof("Delete %s", key)
return pr.client.CAS(key, &consulPipe{}, func(in interface{}) (interface{}, bool, error) {
if in == nil {
return nil, false, fmt.Errorf("Pipe %s not found", id)
}
p := in.(*consulPipe)
p.DeletedAt = mtime.Now()
return p, false, nil
})
}
// A bridgeConnection represents a connection between two pipe router replicas.
// They are created & destroyed in response to events from consul, which in turn
// are triggered when UIs or Probes connect to various pipe routers.
type bridgeConnection struct {
key string
addr string // address to connect to
pipe xfer.Pipe
mtx sync.Mutex
conn xfer.Websocket
stopped bool
wait sync.WaitGroup
}
func newBridgeConnection(key, addr string, pipe xfer.Pipe) *bridgeConnection {
log.Infof("%s: Starting client bridge connection", key)
result := &bridgeConnection{
key: key,
addr: addr,
pipe: pipe,
}
result.wait.Add(1)
go result.loop()
return result
}
func (bc *bridgeConnection) stop() {
log.Infof("%s: Stopping client bridge connection", bc.key)
bc.mtx.Lock()
bc.stopped = true
if bc.conn != nil {
bc.conn.Close()
end, _ := bc.pipe.Ends()
end.Write(nil) // this will cause the other end of wake up and exit
}
bc.mtx.Unlock()
bc.wait.Wait()
}
func (bc *bridgeConnection) loop() {
log.Infof("%s: Client bridge connection started", bc.key)
defer bc.wait.Done()
defer log.Infof("%s: Client bridge connection stopped", bc.key)
_, end := bc.pipe.Ends()
url := fmt.Sprintf("ws://%s/private/api/pipe/%s", bc.addr, url.QueryEscape(bc.key))
for {
bc.mtx.Lock()
bc.conn = nil
if bc.stopped {
bc.mtx.Unlock()
return
}
bc.mtx.Unlock()
// connect to other pipes instance
conn, _, err := xfer.DialWS(wsDialer, url, http.Header{})
if err != nil {
log.Errorf("%s: Client bridge connection; Error connecting to %s: %v", bc.key, url, err)
time.Sleep(time.Second) // TODO backoff
continue
}
bc.mtx.Lock()
if bc.stopped {
bc.mtx.Unlock()
conn.Close()
return
}
bc.conn = conn
bc.mtx.Unlock()
if err := bc.pipe.CopyToWebsocket(end, conn); err != nil && !xfer.IsExpectedWSCloseError(err) {
log.Errorf("%s: Client bridge connection; Error copying pipe to websocket: %v", bc.key, err)
}
conn.Close()
}
}