forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgcoord.go
1716 lines (1576 loc) · 49.6 KB
/
pgcoord.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tailnet
import (
"context"
"database/sql"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"golang.org/x/xerrors"
gProto "google.golang.org/protobuf/proto"
"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/pubsub"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
agpl "github.com/coder/coder/v2/tailnet"
"github.com/coder/coder/v2/tailnet/proto"
"github.com/coder/quartz"
)
const (
EventHeartbeats = "tailnet_coordinator_heartbeat"
eventPeerUpdate = "tailnet_peer_update"
eventTunnelUpdate = "tailnet_tunnel_update"
eventReadyForHandshake = "tailnet_ready_for_handshake"
HeartbeatPeriod = time.Second * 2
MissedHeartbeats = 3
numQuerierWorkers = 10
numBinderWorkers = 10
numTunnelerWorkers = 10
numHandshakerWorkers = 5
dbMaxBackoff = 10 * time.Second
cleanupPeriod = time.Hour
)
// pgCoord is a postgres-backed coordinator
//
// ┌────────────┐
// ┌────────────► handshaker ├────────┐
// │ └────────────┘ │
// │ ┌──────────┐ │
// ├────────────► tunneler ├──────────┤
// │ └──────────┘ │
// │ │
// ┌────────┐ ┌────────┐ ┌───▼───┐
// │ connIO ├───────► binder ├────────► store │
// └───▲────┘ │ │ │ │
// │ └────────┘ ┌──────┤ │
// │ │ └───────┘
// │ │
// │ ┌──────────▼┐ ┌────────┐
// │ │ │ │ │
// └────────────┤ querier ◄─────┤ pubsub │
// │ │ │ │
// └───────────┘ └────────┘
//
// each incoming connection (websocket) from a peer is wrapped in a connIO which handles reading & writing
// from it. Node updates from a connIO are sent to the binder, which writes them to the database.Store. Tunnel
// updates from a connIO are sent to the tunneler, which writes them to the database.Store. The querier is responsible
// for querying the store for the nodes the connection needs. The querier receives pubsub notifications about changes,
// which trigger queries for the latest state.
//
// The querier also sends the coordinator's heartbeat, and monitors the heartbeats of other coordinators. When
// heartbeats cease for a coordinator, it stops using any nodes discovered from that coordinator and pushes an update
// to affected connIOs.
//
// This package uses the term "binding" to mean the act of registering an association between some connection
// and a *proto.Node. It uses the term "mapping" to mean the act of determining the nodes that the connection
// needs to receive (i.e. the nodes of all peers it shares a tunnel with).
type pgCoord struct {
ctx context.Context
logger slog.Logger
pubsub pubsub.Pubsub
store database.Store
bindings chan binding
newConnections chan *connIO
closeConnections chan *connIO
tunnelerCh chan tunnel
handshakerCh chan readyForHandshake
id uuid.UUID
cancel context.CancelFunc
closeOnce sync.Once
closed chan struct{}
binder *binder
tunneler *tunneler
handshaker *handshaker
querier *querier
}
var pgCoordSubject = rbac.Subject{
ID: uuid.Nil.String(),
Roles: rbac.Roles([]rbac.Role{
{
Identifier: rbac.RoleIdentifier{Name: "tailnetcoordinator"},
DisplayName: "Tailnet Coordinator",
Site: rbac.Permissions(map[string][]policy.Action{
rbac.ResourceTailnetCoordinator.Type: {policy.WildcardSymbol},
}),
Org: map[string][]rbac.Permission{},
User: []rbac.Permission{},
},
}),
Scope: rbac.ScopeAll,
}.WithCachedASTValue()
// NewPGCoord creates a high-availability coordinator that stores state in the PostgreSQL database and
// receives notifications of updates via the pubsub.
func NewPGCoord(ctx context.Context, logger slog.Logger, ps pubsub.Pubsub, store database.Store) (agpl.Coordinator, error) {
return newPGCoordInternal(ctx, logger, ps, store, quartz.NewReal())
}
// NewTestPGCoord is only used in testing to pass a clock.Clock in.
func NewTestPGCoord(ctx context.Context, logger slog.Logger, ps pubsub.Pubsub, store database.Store, clk quartz.Clock) (agpl.Coordinator, error) {
return newPGCoordInternal(ctx, logger, ps, store, clk)
}
func newPGCoordInternal(
ctx context.Context, logger slog.Logger, ps pubsub.Pubsub, store database.Store, clk quartz.Clock,
) (
*pgCoord, error,
) {
ctx, cancel := context.WithCancel(dbauthz.As(ctx, pgCoordSubject))
id := uuid.New()
logger = logger.Named("pgcoord").With(slog.F("coordinator_id", id))
bCh := make(chan binding)
// used for opening connections
cCh := make(chan *connIO)
// used for closing connections
ccCh := make(chan *connIO)
// for communicating subscriptions with the tunneler
sCh := make(chan tunnel)
// for communicating ready for handshakes with the handshaker
rfhCh := make(chan readyForHandshake)
// signals when first heartbeat has been sent, so it's safe to start binding.
fHB := make(chan struct{})
c := &pgCoord{
ctx: ctx,
cancel: cancel,
logger: logger,
pubsub: ps,
store: store,
binder: newBinder(ctx, logger, id, store, bCh, fHB),
bindings: bCh,
newConnections: cCh,
closeConnections: ccCh,
tunneler: newTunneler(ctx, logger, id, store, sCh, fHB),
tunnelerCh: sCh,
handshaker: newHandshaker(ctx, logger, id, ps, rfhCh, fHB),
handshakerCh: rfhCh,
id: id,
querier: newQuerier(ctx, logger, id, ps, store, id, cCh, ccCh, numQuerierWorkers, fHB, clk),
closed: make(chan struct{}),
}
logger.Info(ctx, "starting coordinator")
return c, nil
}
func (c *pgCoord) ServeMultiAgent(id uuid.UUID) agpl.MultiAgentConn {
return agpl.ServeMultiAgent(c, c.logger, id)
}
func (c *pgCoord) Node(id uuid.UUID) *agpl.Node {
// We're going to directly query the database, since we would only have the mapping stored locally if we had
// a tunnel peer connected, which is not always the case.
peers, err := c.store.GetTailnetPeers(c.ctx, id)
if err != nil {
c.logger.Error(c.ctx, "failed to query peers", slog.Error(err))
return nil
}
mappings := make([]mapping, 0, len(peers))
for _, peer := range peers {
pNode := new(proto.Node)
err := gProto.Unmarshal(peer.Node, pNode)
if err != nil {
c.logger.Critical(c.ctx, "failed to unmarshal node", slog.F("bytes", peer.Node), slog.Error(err))
return nil
}
mappings = append(mappings, mapping{
peer: peer.ID,
coordinator: peer.CoordinatorID,
updatedAt: peer.UpdatedAt,
node: pNode,
})
}
mappings = c.querier.heartbeats.filter(mappings)
var bestT time.Time
var bestN *proto.Node
for _, m := range mappings {
if m.updatedAt.After(bestT) {
bestN = m.node
bestT = m.updatedAt
}
}
if bestN == nil {
return nil
}
node, err := agpl.ProtoToNode(bestN)
if err != nil {
c.logger.Critical(c.ctx, "failed to convert node", slog.F("node", bestN), slog.Error(err))
return nil
}
return node
}
func (c *pgCoord) Close() error {
c.logger.Info(c.ctx, "closing coordinator")
c.cancel()
c.closeOnce.Do(func() { close(c.closed) })
c.querier.wait()
c.binder.wait()
c.tunneler.workerWG.Wait()
c.handshaker.workerWG.Wait()
return nil
}
func (c *pgCoord) Coordinate(
ctx context.Context, id uuid.UUID, name string, a agpl.CoordinateeAuth,
) (
chan<- *proto.CoordinateRequest, <-chan *proto.CoordinateResponse,
) {
logger := c.logger.With(slog.F("peer_id", id))
reqs := make(chan *proto.CoordinateRequest, agpl.RequestBufferSize)
resps := make(chan *proto.CoordinateResponse, agpl.ResponseBufferSize)
if !c.querier.isHealthy() {
// If the coordinator is unhealthy, we don't want to hook this Coordinate call up to the
// binder, as that can cause an unnecessary call to DeleteTailnetPeer when the connIO is
// closed. Instead, we just close the response channel and bail out.
// c.f. https://github.com/coder/coder/issues/12923
c.logger.Info(ctx, "closed incoming coordinate call while unhealthy",
slog.F("peer_id", id),
)
close(resps)
return reqs, resps
}
cIO := newConnIO(c.ctx, ctx, logger, c.bindings, c.tunnelerCh, c.handshakerCh, reqs, resps, id, name, a)
err := agpl.SendCtx(c.ctx, c.newConnections, cIO)
if err != nil {
// this can only happen if the context is canceled, no need to log
return reqs, resps
}
go func() {
<-cIO.Done()
_ = agpl.SendCtx(c.ctx, c.closeConnections, cIO)
}()
return reqs, resps
}
type tKey struct {
src uuid.UUID
dst uuid.UUID
}
type tunnel struct {
tKey
// whether the subscription should be active. if true, the subscription is
// added. if false, the subscription is removed.
active bool
}
type tunneler struct {
ctx context.Context
logger slog.Logger
coordinatorID uuid.UUID
store database.Store
updates <-chan tunnel
mu sync.Mutex
latest map[uuid.UUID]map[uuid.UUID]tunnel
workQ *workQ[tKey]
workerWG sync.WaitGroup
}
func newTunneler(ctx context.Context,
logger slog.Logger,
id uuid.UUID,
store database.Store,
updates <-chan tunnel,
startWorkers <-chan struct{},
) *tunneler {
s := &tunneler{
ctx: ctx,
logger: logger,
coordinatorID: id,
store: store,
updates: updates,
latest: make(map[uuid.UUID]map[uuid.UUID]tunnel),
workQ: newWorkQ[tKey](ctx),
}
go s.handle()
// add to the waitgroup immediately to avoid any races waiting for it before
// the workers start.
s.workerWG.Add(numTunnelerWorkers)
go func() {
<-startWorkers
for i := 0; i < numTunnelerWorkers; i++ {
go s.worker()
}
}()
return s
}
func (t *tunneler) handle() {
for {
select {
case <-t.ctx.Done():
t.logger.Debug(t.ctx, "tunneler exiting", slog.Error(t.ctx.Err()))
return
case tun := <-t.updates:
t.cache(tun)
t.workQ.enqueue(tun.tKey)
}
}
}
func (t *tunneler) worker() {
defer t.workerWG.Done()
eb := backoff.NewExponentialBackOff()
eb.MaxElapsedTime = 0 // retry indefinitely
eb.MaxInterval = dbMaxBackoff
bkoff := backoff.WithContext(eb, t.ctx)
for {
tk, err := t.workQ.acquire()
if err != nil {
// context expired
return
}
err = backoff.Retry(func() error {
tun := t.retrieve(tk)
return t.writeOne(tun)
}, bkoff)
if err != nil {
bkoff.Reset()
}
t.workQ.done(tk)
}
}
func (t *tunneler) cache(update tunnel) {
t.mu.Lock()
defer t.mu.Unlock()
if update.active {
if _, ok := t.latest[update.src]; !ok {
t.latest[update.src] = map[uuid.UUID]tunnel{}
}
t.latest[update.src][update.dst] = update
} else {
// If inactive and dst is nil, it means clean up all tunnels.
if update.dst == uuid.Nil {
delete(t.latest, update.src)
} else {
delete(t.latest[update.src], update.dst)
// clean up the tunnel map if all the tunnels are gone.
if len(t.latest[update.src]) == 0 {
delete(t.latest, update.src)
}
}
}
}
// retrieveBinding gets the latest tunnel for a key.
func (t *tunneler) retrieve(k tKey) tunnel {
t.mu.Lock()
defer t.mu.Unlock()
dstMap, ok := t.latest[k.src]
if !ok {
return tunnel{
tKey: k,
active: false,
}
}
tun, ok := dstMap[k.dst]
if !ok {
return tunnel{
tKey: k,
active: false,
}
}
return tun
}
func (t *tunneler) writeOne(tun tunnel) error {
var err error
switch {
case tun.dst == uuid.Nil:
err = t.store.DeleteAllTailnetTunnels(t.ctx, database.DeleteAllTailnetTunnelsParams{
SrcID: tun.src,
CoordinatorID: t.coordinatorID,
})
t.logger.Debug(t.ctx, "deleted all tunnels",
slog.F("src_id", tun.src),
slog.Error(err),
)
case tun.active:
_, err = t.store.UpsertTailnetTunnel(t.ctx, database.UpsertTailnetTunnelParams{
CoordinatorID: t.coordinatorID,
SrcID: tun.src,
DstID: tun.dst,
})
t.logger.Debug(t.ctx, "upserted tunnel",
slog.F("src_id", tun.src),
slog.F("dst_id", tun.dst),
slog.Error(err),
)
case !tun.active:
_, err = t.store.DeleteTailnetTunnel(t.ctx, database.DeleteTailnetTunnelParams{
CoordinatorID: t.coordinatorID,
SrcID: tun.src,
DstID: tun.dst,
})
t.logger.Debug(t.ctx, "deleted tunnel",
slog.F("src_id", tun.src),
slog.F("dst_id", tun.dst),
slog.Error(err),
)
// writeOne should be idempotent
if xerrors.Is(err, sql.ErrNoRows) {
err = nil
}
default:
panic("unreachable")
}
if err != nil && !database.IsQueryCanceledError(err) {
t.logger.Error(t.ctx, "write tunnel to database",
slog.F("src_id", tun.src),
slog.F("dst_id", tun.dst),
slog.F("active", tun.active),
slog.Error(err))
}
return err
}
// bKey, or "binding key" identifies a peer in a binding
type bKey uuid.UUID
// binding represents an association between a peer and a Node.
type binding struct {
bKey
node *proto.Node
kind proto.CoordinateResponse_PeerUpdate_Kind
}
// binder reads node bindings from the channel and writes them to the database. It handles retries with a backoff.
type binder struct {
ctx context.Context
logger slog.Logger
coordinatorID uuid.UUID
store database.Store
bindings <-chan binding
mu sync.Mutex
latest map[bKey]binding
workQ *workQ[bKey]
workerWG sync.WaitGroup
close chan struct{}
}
func newBinder(ctx context.Context,
logger slog.Logger,
id uuid.UUID,
store database.Store,
bindings <-chan binding,
startWorkers <-chan struct{},
) *binder {
b := &binder{
ctx: ctx,
logger: logger,
coordinatorID: id,
store: store,
bindings: bindings,
latest: make(map[bKey]binding),
workQ: newWorkQ[bKey](ctx),
close: make(chan struct{}),
}
go b.handleBindings()
// add to the waitgroup immediately to avoid any races waiting for it before
// the workers start.
b.workerWG.Add(numBinderWorkers)
go func() {
<-startWorkers
for i := 0; i < numBinderWorkers; i++ {
go b.worker()
}
}()
go func() {
defer close(b.close)
<-b.ctx.Done()
b.logger.Debug(b.ctx, "binder exiting, waiting for workers")
b.workerWG.Wait()
b.logger.Debug(b.ctx, "updating peers to lost")
//nolint:gocritic // provisioner is system
ctx, cancel := context.WithTimeout(dbauthz.AsSystemRestricted(context.Background()), time.Second*15)
defer cancel()
err := b.store.UpdateTailnetPeerStatusByCoordinator(ctx, database.UpdateTailnetPeerStatusByCoordinatorParams{
CoordinatorID: b.coordinatorID,
Status: database.TailnetStatusLost,
})
if err != nil {
b.logger.Error(b.ctx, "update peer status to lost", slog.Error(err))
}
}()
return b
}
func (b *binder) handleBindings() {
for {
select {
case <-b.ctx.Done():
b.logger.Debug(b.ctx, "binder exiting")
return
case bnd := <-b.bindings:
b.storeBinding(bnd)
b.workQ.enqueue(bnd.bKey)
}
}
}
func (b *binder) worker() {
defer b.workerWG.Done()
eb := backoff.NewExponentialBackOff()
eb.MaxElapsedTime = 0 // retry indefinitely
eb.MaxInterval = dbMaxBackoff
bkoff := backoff.WithContext(eb, b.ctx)
for {
bk, err := b.workQ.acquire()
if err != nil {
// context expired
return
}
err = backoff.Retry(func() error {
bnd := b.retrieveBinding(bk)
return b.writeOne(bnd)
}, bkoff)
if err != nil {
bkoff.Reset()
}
b.workQ.done(bk)
}
}
func (b *binder) writeOne(bnd binding) error {
var err error
if bnd.kind == proto.CoordinateResponse_PeerUpdate_DISCONNECTED {
_, err = b.store.DeleteTailnetPeer(b.ctx, database.DeleteTailnetPeerParams{
ID: uuid.UUID(bnd.bKey),
CoordinatorID: b.coordinatorID,
})
// writeOne is idempotent
if xerrors.Is(err, sql.ErrNoRows) {
err = nil
}
} else {
var nodeRaw []byte
nodeRaw, err = gProto.Marshal(bnd.node)
if err != nil {
// this is very bad news, but it should never happen because the node was Unmarshalled or converted by this
// process earlier.
b.logger.Critical(b.ctx, "failed to marshal node", slog.Error(err))
return err
}
status := database.TailnetStatusOk
if bnd.kind == proto.CoordinateResponse_PeerUpdate_LOST {
status = database.TailnetStatusLost
}
_, err = b.store.UpsertTailnetPeer(b.ctx, database.UpsertTailnetPeerParams{
ID: uuid.UUID(bnd.bKey),
CoordinatorID: b.coordinatorID,
Node: nodeRaw,
Status: status,
})
}
if err != nil && !database.IsQueryCanceledError(err) {
b.logger.Error(b.ctx, "failed to write binding to database",
slog.F("binding_id", bnd.bKey),
slog.F("node", bnd.node),
slog.Error(err))
}
return err
}
// storeBinding stores the latest binding, where we interpret kind == DISCONNECTED as removing the binding. This keeps the map
// from growing without bound.
func (b *binder) storeBinding(bnd binding) {
b.mu.Lock()
defer b.mu.Unlock()
switch bnd.kind {
case proto.CoordinateResponse_PeerUpdate_NODE:
b.latest[bnd.bKey] = bnd
case proto.CoordinateResponse_PeerUpdate_DISCONNECTED:
delete(b.latest, bnd.bKey)
case proto.CoordinateResponse_PeerUpdate_LOST:
// we need to coalesce with the previously stored node, since it must
// be non-nil in the database
old, ok := b.latest[bnd.bKey]
if !ok {
// lost before we ever got a node update. No action
return
}
bnd.node = old.node
b.latest[bnd.bKey] = bnd
}
}
// retrieveBinding gets the latest binding for a key.
func (b *binder) retrieveBinding(bk bKey) binding {
b.mu.Lock()
defer b.mu.Unlock()
bnd, ok := b.latest[bk]
if !ok {
bnd = binding{
bKey: bk,
node: nil,
kind: proto.CoordinateResponse_PeerUpdate_DISCONNECTED,
}
}
return bnd
}
func (b *binder) wait() {
<-b.close
}
// mapper tracks data sent to a peer, and sends updates based on changes read from the database.
type mapper struct {
ctx context.Context
logger slog.Logger
// reads from this channel trigger recomputing the set of mappings to send, and sending any updates. It is used when
// coordinators are added or removed
update chan struct{}
mappings chan []mapping
c *connIO
// sent is the state of mappings we have actually enqueued; used to compute diffs for updates.
sent map[uuid.UUID]mapping
// called to filter mappings to healthy coordinators
heartbeats *heartbeats
}
func newMapper(c *connIO, logger slog.Logger, h *heartbeats) *mapper {
logger = logger.With(
slog.F("peer_id", c.UniqueID()),
)
m := &mapper{
ctx: c.peerCtx, // mapper has same lifetime as the underlying connection it serves
logger: logger,
c: c,
update: make(chan struct{}),
mappings: make(chan []mapping),
heartbeats: h,
sent: make(map[uuid.UUID]mapping),
}
go m.run()
return m
}
func (m *mapper) run() {
for {
var best map[uuid.UUID]mapping
select {
case <-m.ctx.Done():
return
case mappings := <-m.mappings:
m.logger.Debug(m.ctx, "got new mappings")
m.c.setLatestMapping(mappings)
best = m.bestMappings(mappings)
case <-m.update:
m.logger.Debug(m.ctx, "triggered update")
best = m.bestMappings(m.c.getLatestMapping())
}
update := m.bestToUpdate(best)
if update == nil {
m.logger.Debug(m.ctx, "skipping nil node update")
continue
}
if err := m.c.Enqueue(update); err != nil && !xerrors.Is(err, context.Canceled) {
m.logger.Error(m.ctx, "failed to enqueue node update", slog.Error(err))
}
}
}
// bestMappings takes a set of mappings and resolves the best set of nodes. We may get several mappings for a
// particular connection, from different coordinators in the distributed system. Furthermore, some coordinators
// might be considered invalid on account of missing heartbeats. We take the most recent mapping from a valid
// coordinator as the "best" mapping.
func (m *mapper) bestMappings(mappings []mapping) map[uuid.UUID]mapping {
mappings = m.heartbeats.filter(mappings)
best := make(map[uuid.UUID]mapping, len(mappings))
for _, mpng := range mappings {
bestM, ok := best[mpng.peer]
switch {
case !ok:
// no current best
best[mpng.peer] = mpng
// NODE always beats LOST mapping, since the LOST could be from a coordinator that's
// slow updating the DB, and the peer has reconnected to a different coordinator and
// given a NODE mapping.
case bestM.kind == proto.CoordinateResponse_PeerUpdate_LOST && mpng.kind == proto.CoordinateResponse_PeerUpdate_NODE:
best[mpng.peer] = mpng
case mpng.updatedAt.After(bestM.updatedAt) && mpng.kind == proto.CoordinateResponse_PeerUpdate_NODE:
// newer, and it's a NODE update.
best[mpng.peer] = mpng
}
}
return best
}
func (m *mapper) bestToUpdate(best map[uuid.UUID]mapping) *proto.CoordinateResponse {
resp := new(proto.CoordinateResponse)
for k, mpng := range best {
var reason string
sm, ok := m.sent[k]
switch {
case !ok && mpng.kind == proto.CoordinateResponse_PeerUpdate_LOST:
// we don't need to send a "lost" update if we've never sent an update about this peer
continue
case !ok && mpng.kind == proto.CoordinateResponse_PeerUpdate_NODE:
reason = "new"
case ok && sm.kind == proto.CoordinateResponse_PeerUpdate_LOST && mpng.kind == proto.CoordinateResponse_PeerUpdate_LOST:
// was lost and remains lost, no update needed
continue
case ok && sm.kind == proto.CoordinateResponse_PeerUpdate_LOST && mpng.kind == proto.CoordinateResponse_PeerUpdate_NODE:
reason = "found"
case ok && sm.kind == proto.CoordinateResponse_PeerUpdate_NODE && mpng.kind == proto.CoordinateResponse_PeerUpdate_LOST:
reason = "lost"
case ok && sm.kind == proto.CoordinateResponse_PeerUpdate_NODE && mpng.kind == proto.CoordinateResponse_PeerUpdate_NODE:
eq, err := sm.node.Equal(mpng.node)
if err != nil {
m.logger.Critical(m.ctx, "failed to compare nodes", slog.F("old", sm.node), slog.F("new", mpng.node))
continue
}
if eq {
continue
}
reason = "update"
}
resp.PeerUpdates = append(resp.PeerUpdates, &proto.CoordinateResponse_PeerUpdate{
Id: agpl.UUIDToByteSlice(k),
Node: mpng.node,
Kind: mpng.kind,
Reason: reason,
})
m.sent[k] = mpng
}
for k := range m.sent {
if _, ok := best[k]; !ok {
resp.PeerUpdates = append(resp.PeerUpdates, &proto.CoordinateResponse_PeerUpdate{
Id: agpl.UUIDToByteSlice(k),
Kind: proto.CoordinateResponse_PeerUpdate_DISCONNECTED,
Reason: "disconnected",
})
delete(m.sent, k)
}
}
if len(resp.PeerUpdates) == 0 {
return nil
}
return resp
}
// querier is responsible for monitoring pubsub notifications and querying the database for the
// mappings that all connected peers need. It also checks heartbeats and withdraws mappings from
// coordinators that have failed heartbeats.
//
// There are two kinds of pubsub notifications it listens for and responds to.
//
// 1. Tunnel updates --- a tunnel was added or removed. In this case we need
// to recompute the mappings for peers on both sides of the tunnel.
// 2. Peer updates --- a peer got a new binding. When a peer gets a new
// binding, we need to update all the _other_ peers it shares a tunnel with.
// However, we don't keep tunnels in memory (to avoid the
// complexity of synchronizing with the database), so we first have to query
// the database to learn the tunnel peers, then schedule an update on each
// one.
type querier struct {
ctx context.Context
logger slog.Logger
coordinatorID uuid.UUID
pubsub pubsub.Pubsub
store database.Store
newConnections chan *connIO
closeConnections chan *connIO
workQ *workQ[querierWorkKey]
wg sync.WaitGroup
heartbeats *heartbeats
updates <-chan hbUpdate
mu sync.Mutex
mappers map[mKey]*mapper
healthy bool
}
func newQuerier(ctx context.Context,
logger slog.Logger,
coordinatorID uuid.UUID,
ps pubsub.Pubsub,
store database.Store,
self uuid.UUID,
newConnections chan *connIO,
closeConnections chan *connIO,
numWorkers int,
firstHeartbeat chan struct{},
clk quartz.Clock,
) *querier {
updates := make(chan hbUpdate)
q := &querier{
ctx: ctx,
logger: logger.Named("querier"),
coordinatorID: coordinatorID,
pubsub: ps,
store: store,
newConnections: newConnections,
closeConnections: closeConnections,
workQ: newWorkQ[querierWorkKey](ctx),
heartbeats: newHeartbeats(ctx, logger, ps, store, self, updates, firstHeartbeat, clk),
mappers: make(map[mKey]*mapper),
updates: updates,
healthy: true, // assume we start healthy
}
q.subscribe()
q.wg.Add(2 + numWorkers)
go func() {
<-firstHeartbeat
go q.handleIncoming()
for i := 0; i < numWorkers; i++ {
go q.worker()
}
go q.handleUpdates()
}()
return q
}
func (q *querier) wait() {
q.wg.Wait()
q.heartbeats.wg.Wait()
}
func (q *querier) handleIncoming() {
defer q.wg.Done()
for {
select {
case <-q.ctx.Done():
return
case c := <-q.newConnections:
q.newConn(c)
case c := <-q.closeConnections:
q.cleanupConn(c)
}
}
}
func (q *querier) newConn(c *connIO) {
q.mu.Lock()
defer q.mu.Unlock()
if !q.healthy {
err := c.Close()
// This can only happen during a narrow window where we were healthy
// when pgCoord checked before accepting the connection, but now are
// unhealthy now that we get around to processing it. Seeing a small
// number of these logs is not worrying, but a large number probably
// indicates something is amiss.
q.logger.Warn(q.ctx, "closed incoming connection while unhealthy",
slog.Error(err),
slog.F("peer_id", c.UniqueID()),
)
return
}
mpr := newMapper(c, q.logger, q.heartbeats)
mk := mKey(c.UniqueID())
dup, ok := q.mappers[mk]
if ok {
// duplicate, overwrite and close the old one
atomic.StoreInt64(&c.overwrites, dup.c.Overwrites()+1)
err := dup.c.CoordinatorClose()
if err != nil {
q.logger.Error(q.ctx, "failed to close duplicate mapper", slog.F("peer_id", dup.c.UniqueID()), slog.Error(err))
}
}
q.mappers[mk] = mpr
q.workQ.enqueue(querierWorkKey{
mappingQuery: mk,
})
}
func (q *querier) isHealthy() bool {
q.mu.Lock()
defer q.mu.Unlock()
return q.healthy
}
func (q *querier) cleanupConn(c *connIO) {
logger := q.logger.With(slog.F("peer_id", c.UniqueID()))
q.mu.Lock()
defer q.mu.Unlock()
mk := mKey(c.UniqueID())
mpr, ok := q.mappers[mk]
if !ok {
return
}
if mpr.c != c {
logger.Debug(q.ctx, "attempt to cleanup for duplicate connection, ignoring")
return
}
err := c.CoordinatorClose()
if err != nil {
logger.Error(q.ctx, "failed to close connIO", slog.Error(err))
}
delete(q.mappers, mk)
q.logger.Debug(q.ctx, "removed mapper")
}
func (q *querier) worker() {
defer q.wg.Done()
eb := backoff.NewExponentialBackOff()
eb.MaxElapsedTime = 0 // retry indefinitely
eb.MaxInterval = dbMaxBackoff
bkoff := backoff.WithContext(eb, q.ctx)
for {
qk, err := q.workQ.acquire()
if err != nil {
// context expired
return
}
err = backoff.Retry(func() error {
return q.query(qk)
}, bkoff)
if err != nil {
bkoff.Reset()
}
q.workQ.done(qk)
}
}
func (q *querier) query(qk querierWorkKey) error {
if uuid.UUID(qk.mappingQuery) != uuid.Nil {
return q.mappingQuery(qk.mappingQuery)
}
if qk.peerUpdate != uuid.Nil {
return q.peerUpdate(qk.peerUpdate)
}
q.logger.Critical(q.ctx, "bad querierWorkKey", slog.F("work_key", qk))
return backoff.Permanent(xerrors.Errorf("bad querierWorkKey %v", qk))
}
// peerUpdate is work scheduled in response to a new peer->binding. We need to find out all the
// other peers that share a tunnel with the indicated peer, and then schedule a mapping update on
// each, so that they can find out about the new binding.
func (q *querier) peerUpdate(peer uuid.UUID) error {
logger := q.logger.With(slog.F("peer_id", peer))
logger.Debug(q.ctx, "querying peers that share a tunnel")
others, err := q.store.GetTailnetTunnelPeerIDs(q.ctx, peer)
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
return err
}
logger.Debug(q.ctx, "queried peers that share a tunnel", slog.F("num_peers", len(others)))
for _, other := range others {
logger.Debug(q.ctx, "got tunnel peer", slog.F("other_id", other.PeerID))
q.workQ.enqueue(querierWorkKey{mappingQuery: mKey(other.PeerID)})
}
return nil
}
// mappingQuery queries the database for all the mappings that the given peer should know about,
// that is, all the peers that it shares a tunnel with and their current node mappings (if they
// exist). It then sends the mapping snapshot to the corresponding mapper, where it will get