/
conncache.go
796 lines (717 loc) · 21.6 KB
/
conncache.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
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package manager
import (
"bytes"
"fmt"
"sort"
"time"
"v.io/v23/context"
"v.io/v23/flow"
"v.io/v23/naming"
"v.io/v23/security"
"v.io/v23/verror"
"v.io/x/lib/nsync"
"v.io/x/ref/lib/stats"
"v.io/x/ref/runtime/internal/flow/conn"
)
const maxErrorAge = time.Minute * 5
// ConnCache is a cache from (protocol, address) and (routingID) to a set of Conns.
// Multiple goroutines may invoke methods on the ConnCache simultaneously.
type ConnCache struct {
mu nsync.Mu
cond nsync.CV
conns map[CachedConn]*connEntry
cache map[interface{}][]*connEntry
errors map[interface{}]dialError
reserved map[interface{}]*Reservation
idleExpiry time.Duration
}
type connEntry struct {
conn CachedConn
rid naming.RoutingID
proxy bool
// cancel is a context.CancelFunc that corresponds to the context
// used to dial the connection. Since connections live longer than the
// RPC calls which precipiated their being dialed, we have to use
// context.WithRootCancel to make a context to dial. This means we need
// to cancel that context at some point when the connection is no longer
// needed. In our case that's when we eject the context from the cache.
cancel context.CancelFunc
keys []interface{}
}
type dialError struct {
err error
when time.Time
}
// Reservation represents the right to dial a connection. We only
// hand out one reservation for a given connection at a time.
type Reservation struct {
cache *ConnCache
ctx *context.T
cancel context.CancelFunc
keys []interface{}
remote naming.Endpoint
waitForProxy bool
}
// Context returns the context that should be used to dial the new connection.
func (r *Reservation) Context() *context.T {
return r.ctx
}
// ProxyConn returns a connection to a relevant proxy if it exists. Otherwise
// it returns nil and the reservation holder should dial the proxy if necessary.
func (r *Reservation) ProxyConn() CachedConn {
if !r.waitForProxy {
return nil
}
keys := []interface{}{key(r.remote.Protocol, r.remote.Address)}
// We ignore the error here. The worst thing that can happen is we try
// to dial the proxy again.
conn, _, _, _ := r.cache.internalFind(r.ctx, r.remote, keys, nil, true)
return conn
}
// Unreserve removes this reservation, and broadcasts waiting threads to
// continue with their halted Find call.
func (r *Reservation) Unreserve(conn, proxyConn CachedConn, err error) error {
c := r.cache
defer c.mu.Unlock()
c.mu.Lock()
if c.conns == nil {
r.cancel()
return errCacheClosed.Errorf(r.ctx, "cache is closed")
}
for _, k := range r.keys {
delete(c.reserved, k)
}
if proxyConn != nil {
if c.insertConnLocked(r.remote, proxyConn, true, true, r.cancel) {
r.cancel = nil
}
}
if conn != nil {
c.insertConnLocked(r.remote, conn, proxyConn != nil, proxyConn == nil, r.cancel)
r.cancel = nil
} else if err != nil {
e := dialError{
err: err,
when: time.Now(),
}
c.errors[key(r.remote.Protocol, r.remote.Address)] = e
c.errors[r.remote.RoutingID] = e
}
if r.cancel != nil {
r.cancel()
}
c.cond.Broadcast()
return nil
}
// CachedConn is the interface implemented by *conn.Conn that is used by ConnCache.
// We make the ConnCache API take this interface to make testing easier.
type CachedConn interface {
Status() conn.Status
IsEncapsulated() bool
IsIdle(*context.T, time.Duration) bool
EnterLameDuck(*context.T) chan struct{}
RemoteLameDuck() bool
CloseIfIdle(*context.T, time.Duration) bool
Close(*context.T, error)
RemoteEndpoint() naming.Endpoint
LocalEndpoint() naming.Endpoint
RemoteBlessings() security.Blessings
RemoteDischarges() map[string]security.Discharge
RTT() time.Duration
LastUsed() time.Time
DebugString() string
}
// NewConnCache creates a ConnCache with an idleExpiry for connections.
// If idleExpiry is zero, connections will never expire.
func NewConnCache(idleExpiry time.Duration) *ConnCache {
return &ConnCache{
conns: make(map[CachedConn]*connEntry),
cache: make(map[interface{}][]*connEntry),
errors: make(map[interface{}]dialError),
reserved: make(map[interface{}]*Reservation),
idleExpiry: idleExpiry,
}
}
// Insert adds conn to the cache, keyed by both (protocol, address) and (routingID).
// An error will be returned iff the cache has been closed.
func (c *ConnCache) Insert(conn CachedConn, proxy bool) error {
defer c.mu.Unlock()
c.mu.Lock()
if c.conns == nil {
return errCacheClosed.Errorf(nil, "cache is closed")
}
c.insertConnLocked(conn.RemoteEndpoint(), conn, proxy, true, nil)
return nil
}
// InsertWithRoutingID adds conn to the cache keyed only by conn's RoutingID.
func (c *ConnCache) InsertWithRoutingID(conn CachedConn, proxy bool) error {
defer c.mu.Unlock()
c.mu.Lock()
if c.conns == nil {
return errCacheClosed.Errorf(nil, "cache is closed")
}
c.insertConnLocked(conn.RemoteEndpoint(), conn, proxy, false, nil)
return nil
}
// Find returns a Conn based on the input remoteEndpoint.
// nil is returned if there is no such Conn.
//
// Find calls will block if the desired connections are currently being dialed.
// Find will return immediately if the given context is canceled.
func (c *ConnCache) Find(
ctx *context.T,
remote naming.Endpoint,
auth flow.PeerAuthorizer,
) (conn CachedConn, names []string, rejected []security.RejectedBlessing, err error) {
var keys []interface{}
if keys, conn, names, rejected, _ = c.internalFindCached(ctx, remote, auth); conn != nil {
return conn, names, rejected, nil
}
// Finally try waiting for any outstanding dials to complete.
nc, n, r, err := c.internalFind(ctx, remote, keys, auth, true)
return nc, n, r, err
}
// FindCached returns a Conn only if it's already in the cache.
func (c *ConnCache) FindCached(
ctx *context.T,
remote naming.Endpoint,
auth flow.PeerAuthorizer) (conn CachedConn, names []string, rejected []security.RejectedBlessing, err error) {
_, conn, names, rejected, err = c.internalFindCached(ctx, remote, auth)
return
}
// FindAllCached returns all Conns for the specified endpoint that are
// already in the cache.
func (c *ConnCache) FindAllCached(
ctx *context.T,
remote naming.Endpoint,
auth flow.PeerAuthorizer) ([]CachedConn, error) {
return c.internalFindAllCached(ctx, remote, auth)
}
func (c *ConnCache) internalFind(
ctx *context.T,
remote naming.Endpoint,
keys []interface{},
auth flow.PeerAuthorizer,
wait bool,
) (CachedConn, []string, []security.RejectedBlessing, error) {
c.mu.Lock()
var err error
var entries rttEntries
for {
if c.conns == nil {
c.mu.Unlock()
return nil, nil, nil, errCacheClosed.Errorf(ctx, "cache is closed")
}
entries, err = c.rttEntriesLocked(ctx, keys)
if len(entries) > 0 || !wait || !c.hasReservationsLocked(keys) {
break
}
if c.cond.WaitWithDeadline(&c.mu, nsync.NoDeadline, ctx.Done()) != nsync.OK {
c.mu.Unlock()
switch ctx.Err() {
case context.Canceled:
return nil, nil, nil, verror.ErrCanceled.Errorf(ctx, "canceled")
default:
return nil, nil, nil, verror.ErrTimeout.Errorf(ctx, "timeout")
}
}
}
c.mu.Unlock()
if len(entries) == 0 {
if err == nil {
err = errConnNotInCache.Errorf(ctx, "connection to %s not in cache", remote.String())
}
return nil, nil, nil, err
}
return c.pickFirstAuthorizedConn(ctx, remote, entries, auth)
}
func (c *ConnCache) internalFindCached(
ctx *context.T,
remote naming.Endpoint,
auth flow.PeerAuthorizer) (keys []interface{}, conn CachedConn, names []string, rejected []security.RejectedBlessing, err error) {
// If we have an RID, there's no point in looking under anything else.
if rid := remote.RoutingID; rid != naming.NullRoutingID {
keys = []interface{}{rid, pathkey(remote.Protocol, remote.Address, rid)}
conn, names, rejected, err = c.internalFind(ctx, remote, keys, auth, false)
return keys, conn, names, rejected, err
}
// Try looking under the address if there wasn't a routing ID.
addrKey := key(remote.Protocol, remote.Address)
keys = []interface{}{addrKey}
if conn, names, rejected, err = c.internalFind(ctx, remote, keys, auth, false); conn != nil {
return keys, conn, names, rejected, nil
}
// If that didn't work, try resolving the address and looking again.
p, _ := flow.RegisteredProtocol(remote.Protocol)
network, addresses, rerr := resolve(ctx, p, remote.Protocol, remote.Address)
if rerr != nil {
// TODO(suharshs): Add a unittest for failed resolution.
ctx.Errorf("Failed to resolve (%v, %v): %v", remote.Protocol, remote.Address, rerr)
}
for _, a := range addresses {
if k := key(network, a); k != addrKey {
keys = append(keys, k)
}
}
if len(keys) > 1 {
conn, names, rejected, err = c.internalFind(ctx, remote, keys, auth, false)
}
return keys, conn, names, rejected, err
}
func (c *ConnCache) internalFindAllCached(
ctx *context.T,
remote naming.Endpoint,
auth flow.PeerAuthorizer) ([]CachedConn, error) {
// Collect all of the possible keys that could be used for this endpoint.
keys := make([]interface{}, 0, 4)
if rid := remote.RoutingID; rid != naming.NullRoutingID {
keys = append(keys, []interface{}{rid, pathkey(remote.Protocol, remote.Address, rid)}...)
}
// protocol, address key.
addrKey := key(remote.Protocol, remote.Address)
keys = append(keys, addrKey)
// key for all resolved addresses.
p, _ := flow.RegisteredProtocol(remote.Protocol)
network, addresses, rerr := resolve(ctx, p, remote.Protocol, remote.Address)
if rerr != nil {
// TODO(suharshs): Add a unittest for failed resolution.
ctx.Errorf("Failed to resolve (%v, %v): %v", remote.Protocol, remote.Address, rerr)
}
for _, a := range addresses {
if k := key(network, a); k != addrKey {
keys = append(keys, k)
}
}
c.mu.Lock()
entries, err := c.rttEntriesLocked(ctx, keys)
c.mu.Unlock()
if err != nil {
return nil, err
}
conns := make([]CachedConn, 0, len(entries))
for _, e := range entries {
if e.proxy || auth == nil {
conns = append(conns, e.conn)
}
_, _, rerr := auth.AuthorizePeer(ctx,
e.conn.LocalEndpoint(),
remote,
e.conn.RemoteBlessings(),
e.conn.RemoteDischarges())
if rerr == nil {
conns = append(conns, e.conn)
}
}
return conns, nil
}
// Reserve reserves the right to dial a remote endpoint.
func (c *ConnCache) Reserve(ctx *context.T, remote naming.Endpoint) *Reservation {
if remote.Protocol == "bidi" {
return nil
}
defer c.mu.Unlock()
c.mu.Lock()
if c.conns == nil {
// Cache is closed.
return nil
}
k := key(remote.Protocol, remote.Address)
if remote.RoutingID == naming.NullRoutingID {
if len(c.cache[k]) > 0 || c.reserved[k] != nil {
// There are either connections or a reservation for this
// address, and the routing id is not given, so no reservations
// are needed.
return nil
}
res := &Reservation{
cache: c,
remote: remote,
keys: []interface{}{k},
}
res.ctx, res.cancel = context.WithCancel(ctx)
c.reserved[k] = res
return res
}
// OK, now we're in the more complicated case when there is an address and
// routing ID, so a proxy might be involved.
// TODO(mattr): We should include the routes in the case of multi-proxying.
pk := pathkey(remote.Protocol, remote.Address, remote.RoutingID)
if len(c.cache[k]) == 0 && c.reserved[k] == nil {
// Nobody is dialing the address. We'll reserve both the address and the path.
res := &Reservation{
cache: c,
remote: remote,
keys: []interface{}{k, pk},
}
res.ctx, res.cancel = context.WithCancel(ctx)
c.reserved[k] = res
c.reserved[pk] = res
return res
}
if len(c.cache[pk]) == 0 && c.reserved[pk] == nil {
// The address connection exists (or is being dialed), but the path doesn't.
// We'll only reserve the path.
res := &Reservation{
cache: c,
remote: remote,
keys: []interface{}{pk},
waitForProxy: true,
}
res.ctx, res.cancel = context.WithCancel(ctx)
c.reserved[pk] = res
return res
}
// No need to reserve anything.
return nil
}
// KillConnections will closes at least num Conns in the cache.
// This is useful when the manager is approaching system FD limits.
//
// The policy is as follows:
// (1) Remove undialable (closing/closed) conns from the cache, there is no point
// in closing undialable connections to address a FD limit.
// (2) Close and remove lameducked, expired connections from the cache,
// counting non-proxied connections towards the removed FD count (num).
// (3) LameDuck idle expired connections, killing them if num is still greater
// than 0.
// (4) Finally if 'num' hasn't been reached, remove the LRU remaining conns
// until num is reached.
//
// If num is greater than the number of connections in the cache, all cached
// connections will be closed and removed.
// KillConnections returns an error iff the cache is closed.
func (c *ConnCache) KillConnections(ctx *context.T, num int) error { //nolint:gocyclo
defer c.mu.Unlock()
c.mu.Lock()
if c.conns == nil {
return errCacheClosed.Errorf(ctx, "cache is closed")
}
// kill old error records. We keep them for a while to allow new finds
// to return errors for recent dial attempts, but we need to eliminate
// them eventually.
now := time.Now()
for k, v := range c.errors {
if v.when.Add(maxErrorAge).Before(now) {
delete(c.errors, k)
}
}
entries := make(lruEntries, 0, len(c.conns))
for _, e := range c.conns {
entries = append(entries, e)
}
k := 0
for _, e := range entries {
status := e.conn.Status()
switch {
case status >= conn.Closing:
// Remove undialable conns.
c.removeEntryLocked(e)
case status == conn.LameDuckAcknowledged && e.conn.CloseIfIdle(ctx, c.idleExpiry):
// Close and remove lameducked or idle connections.
c.removeEntryLocked(e)
num--
default:
entries[k] = e
k++
}
}
entries = entries[:k]
// Lameduck or kill idle connections.
// If num > 0, up to num idle connections will be killed instead of lameducked
// to free FD resources.
// Otherwise, the the lameducked connections will be closed when all active
// in subsequent calls of KillConnections, once they become idle.
// TODO(suharshs): This policy is not ideal as we should try to close everything
// we can close without potentially losing RPCs first. The ideal policy would
// close idle client only connections before closing server connections.
k = 0
for _, e := range entries {
// Kill idle connections.
if num > 0 && !e.conn.IsEncapsulated() && e.conn.CloseIfIdle(ctx, c.idleExpiry) {
num--
c.removeEntryLocked(e)
continue
}
// Lameduck idle connections.
if e.conn.IsIdle(ctx, c.idleExpiry) {
e.conn.EnterLameDuck(ctx)
}
// No point in closing encapsulated connections when we reach an FD limit.
if !e.conn.IsEncapsulated() {
entries[k] = e
k++
}
}
entries = entries[:k]
// If we have killed enough idle connections we can exit early.
if num <= 0 {
return nil
}
// Otherwise we need to kill the LRU conns.
sort.Sort(entries)
err := errConnKilledToFreeResources.Errorf(ctx, "connection killed to free resources")
for i := 0; i < num && i < len(entries); i++ {
e := entries[i]
e.conn.Close(ctx, err)
c.removeEntryLocked(e)
}
return nil
}
// EnterLameDuckMode lame ducks all connections and waits for the the remote
// end to acknowledge the lameduck.
func (c *ConnCache) EnterLameDuckMode(ctx *context.T) {
c.mu.Lock()
waitfor := make([]chan struct{}, 0, len(c.conns))
for _, e := range c.conns {
waitfor = append(waitfor, e.conn.EnterLameDuck(ctx))
}
c.mu.Unlock()
for _, w := range waitfor {
<-w
}
}
// Close closes all connections in the cache.
func (c *ConnCache) Close(ctx *context.T) {
defer c.mu.Unlock()
c.mu.Lock()
err := errCacheClosed.Errorf(ctx, "cache is closed")
for _, e := range c.conns {
e.conn.Close(ctx, err)
if e.cancel != nil {
e.cancel()
}
}
for _, r := range c.reserved {
if r.cancel != nil {
r.cancel()
}
}
c.conns = nil
c.cache = nil
c.reserved = nil
c.errors = nil
}
// String returns a user friendly representation of the connections in the cache.
func (c *ConnCache) String() string {
defer c.mu.Unlock()
c.mu.Lock()
buf := &bytes.Buffer{}
if c.conns == nil {
return "conncache closed"
}
fmt.Fprintln(buf, "Cached:")
for _, e := range c.conns {
fmt.Fprintf(buf, "%v: %v\n", e.keys, e.conn)
}
fmt.Fprintln(buf, "Reserved:")
for _, r := range c.reserved {
fmt.Fprintf(buf, "%v: %p\n", r.keys, r)
}
return buf.String()
}
// ExportStats exports cache information to the global stats.
func (c *ConnCache) ExportStats(prefix string) {
stats.NewStringFunc(naming.Join(prefix, "cache"), c.debugStringForCache)
stats.NewStringFunc(naming.Join(prefix, "reserved"), c.debugStringForDialing)
}
func (c *ConnCache) insertConnLocked(remote naming.Endpoint, conn CachedConn, proxy bool, keyByAddr bool, cancel context.CancelFunc) bool {
if _, ok := c.conns[conn]; ok {
// If the conn is already in the cache, don't re-add it.
return false
}
ep := conn.RemoteEndpoint()
entry := &connEntry{
conn: conn,
rid: ep.RoutingID,
proxy: proxy,
cancel: cancel,
keys: make([]interface{}, 0, 3),
}
if entry.rid != naming.NullRoutingID {
entry.keys = append(entry.keys, entry.rid)
}
kdialed := key(remote.Protocol, remote.Address)
if keyByAddr {
entry.keys = append(entry.keys, kdialed)
}
entry.keys = append(entry.keys, pathkey(remote.Protocol, remote.Address, ep.RoutingID))
if kresolved := key(ep.Protocol, ep.Address); kresolved != kdialed {
if keyByAddr {
entry.keys = append(entry.keys, kresolved)
}
entry.keys = append(entry.keys, pathkey(ep.Protocol, ep.Address, ep.RoutingID))
}
for _, k := range entry.keys {
c.cache[k] = append(c.cache[k], entry)
}
c.conns[entry.conn] = entry
return true
}
func (c *ConnCache) rttEntriesLocked(ctx *context.T, keys []interface{}) (rttEntries, error) {
var entries rttEntries
var firstError error
for _, k := range keys {
if found := c.cache[k]; len(found) > 0 {
for _, e := range found {
if status := e.conn.Status(); status >= conn.Closing {
c.removeEntryLocked(e)
} else if !e.conn.RemoteLameDuck() {
entries = append(entries, e)
}
}
} else if err := c.errors[k].err; firstError == nil && err != nil {
firstError = err
}
}
sort.Sort(entries)
return entries, firstError
}
func (c *ConnCache) hasReservationsLocked(keys []interface{}) bool {
for _, k := range keys {
if c.reserved[k] != nil {
return true
}
}
return false
}
func (c *ConnCache) pickFirstAuthorizedConn(
ctx *context.T,
remote naming.Endpoint,
entries rttEntries,
auth flow.PeerAuthorizer) (conn CachedConn, names []string, rejected []security.RejectedBlessing, err error) {
for _, e := range entries {
if e.proxy || auth == nil {
return e.conn, nil, nil, nil
}
names, rejected, err = auth.AuthorizePeer(ctx,
e.conn.LocalEndpoint(),
remote,
e.conn.RemoteBlessings(),
e.conn.RemoteDischarges())
if err == nil {
return e.conn, names, rejected, nil
}
}
return nil, nil, nil, err
}
func (c *ConnCache) removeEntryLocked(entry *connEntry) {
for _, k := range entry.keys {
entries, ok := c.cache[k]
if ok {
entries = removeEntryFromSlice(entries, entry)
if len(entries) == 0 {
delete(c.cache, k)
} else {
c.cache[k] = entries
}
}
}
delete(c.conns, entry.conn)
if entry.cancel != nil {
entry.cancel()
}
}
func removeEntryFromSlice(entries []*connEntry, entry *connEntry) []*connEntry {
for i, e := range entries {
if e == entry {
n := len(entries)
entries[i], entries = entries[n-1], entries[:n-1]
break
}
}
return entries
}
func (c *ConnCache) debugStringForCache() string {
defer c.mu.Unlock()
c.mu.Lock()
if c.cache == nil {
return "<closed>"
}
// map iteration is unstable, so sort the keys first
keys := make(sortedKeys, 0, len(c.cache))
for k := range c.cache {
keys = append(keys, k)
}
sort.Sort(keys)
buf := &bytes.Buffer{}
for _, k := range keys {
fmt.Fprintf(buf, "KEY: %v\n", k)
for _, e := range c.cache[k] {
fmt.Fprintf(buf, "%v\n", e.conn.DebugString())
}
fmt.Fprintf(buf, "\n")
}
return buf.String()
}
func (c *ConnCache) debugStringForDialing() string {
defer c.mu.Unlock()
c.mu.Lock()
if c.reserved == nil {
return "<closed>"
}
keys := make(sortedKeys, 0, len(c.cache))
for k := range c.cache {
keys = append(keys, k)
}
sort.Sort(keys)
buf := &bytes.Buffer{}
for _, k := range keys {
fmt.Fprintf(buf, "KEY: %v\n", k)
fmt.Fprintf(buf, "%#v\n", c.reserved[k])
fmt.Fprintf(buf, "\n")
}
return buf.String()
}
type sortedKeys []interface{}
func (e sortedKeys) Len() int {
return len(e)
}
func (e sortedKeys) Less(i, j int) bool {
return fmt.Sprint(e[i]) < fmt.Sprint(e[j])
}
func (e sortedKeys) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}
func key(protocol, address string) string {
// TODO(mattr): Unalias the default protocol?
return protocol + "," + address
}
func pathkey(protocol, address string, rid naming.RoutingID) string {
// TODO(mattr): Unalias the default protocol?
return protocol + "," + address + "," + rid.String()
}
type rttEntries []*connEntry
func (e rttEntries) Len() int {
return len(e)
}
func (e rttEntries) Less(i, j int) bool {
return e[i].conn.RTT() < e[j].conn.RTT()
}
func (e rttEntries) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}
type lruEntries []*connEntry
func (e lruEntries) Len() int {
return len(e)
}
func (e lruEntries) Less(i, j int) bool {
return e[i].conn.LastUsed().Before(e[j].conn.LastUsed())
}
func (e lruEntries) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}
func resolve(ctx *context.T, p flow.Protocol, protocol, address string) (string, []string, error) {
if p != nil {
net, addrs, err := p.Resolve(ctx, protocol, address)
if err != nil {
return "", nil, err
}
if len(addrs) > 0 {
return net, addrs, nil
}
}
return "", nil, errUnknownProtocol.Errorf(ctx, "unknown protocol: %s", protocol)
}