-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancer.go
894 lines (790 loc) · 24.9 KB
/
balancer.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
// Package balancer provides load balancing of network connections per
// different strategies.
package balancer
import (
"context"
"fmt"
"io"
"math/rand"
"net"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/getlantern/errors"
"github.com/getlantern/flashlight/v7/ops"
"github.com/getlantern/golog"
)
const (
// NetworkConnect is a pseudo network name to instruct the dialer to establish
// a CONNECT tunnel to the proxy.
NetworkConnect = "connect"
// NetworkPersistent is a pseudo network name to instruct the dialer to
// signal the proxy to establish a persistent HTTP connection over which
// one or more HTTP requests can be sent directly.
NetworkPersistent = "persistent"
connectivityRechecks = 3
printStatsInterval = 10 * time.Second
)
var (
log = golog.LoggerFor("balancer")
recheckInterval = 2 * time.Second
evalInterval = time.Minute
)
// Dialer provides the ability to dial a proxy and obtain information needed to
// effectively load balance between dialers.
type Dialer interface {
// SupportsAddr indicates whether this Dialer supports the given addr. If it does not, the
// balancer will not attempt to dial that addr with this Dialer.
SupportsAddr(network, addr string) bool
// DialContext dials out to the given origin. failedUpstream indicates whether
// this was an upstream error (as opposed to errors connecting to the proxy).
DialContext(ctx context.Context, network, addr string) (conn net.Conn, failedUpstream bool, err error)
// Name returns the name for this Dialer
Name() string
// Label returns a label for this Dialer (includes Name plus more).
Label() string
// JustifiedLabel is like Label() but with elements justified for line-by
// -line display.
JustifiedLabel() string
// Location returns the country code, country name and city name of the
// dialer, in this order.
Location() (string, string, string)
// Protocol returns a string representation of the protocol used by this
// Dialer.
Protocol() string
// Addr returns the address for this Dialer
Addr() string
// Trusted indicates whether or not this dialer is trusted
Trusted() bool
// NumPreconnecting returns the number of pending preconnect requests.
NumPreconnecting() int
// NumPreconnected returns the number of preconnected connections.
NumPreconnected() int
// MarkFailure marks a dial failure on this dialer.
MarkFailure()
// EstRTT provides a round trip delay time estimate, similar to how RTT is
// estimated in TCP (https://tools.ietf.org/html/rfc6298)
EstRTT() time.Duration
// EstBandwidth provides the estimated bandwidth in Mbps
EstBandwidth() float64
// EstSuccessRate returns the estimated success rate dialing this dialer.
EstSuccessRate() float64
// Attempts returns the total number of dial attempts
Attempts() int64
// Successes returns the total number of dial successes
Successes() int64
// ConsecSuccesses returns the number of consecutive dial successes
ConsecSuccesses() int64
// Failures returns the total number of dial failures
Failures() int64
// ConsecFailures returns the number of consecutive dial failures
ConsecFailures() int64
// Succeeding indicates whether or not this dialer is currently good to use
Succeeding() bool
// Probe performs active probing of the proxy to better understand
// connectivity and performance. If forPerformance is true, the dialer will
// probe more and with bigger data in order for bandwidth estimation to
// collect enough data to make a decent estimate. Probe returns true if it was
// successfully able to communicate with the Proxy.
Probe(forPerformance bool) bool
// ProbeStats returns probe related stats for the dialer which can be used
// to estimate the overhead of active probling.
ProbeStats() (successes uint64, successKBs uint64, failures uint64, failedKBs uint64)
// DataSent returns total bytes of application data sent to connections
// created via this dialer.
DataSent() uint64
// DataRecv returns total bytes of application data received from
// connections created via this dialer.
DataRecv() uint64
// Stop stops background processing for this Dialer.
Stop()
WriteStats(w io.Writer)
}
type dialStats struct {
success int64
failure int64
}
// Balancer balances connections among multiple Dialers.
type Balancer struct {
mu sync.RWMutex
overallDialTimeout time.Duration
dialers sortedDialers
trusted sortedDialers
sessionStats map[string]*dialStats
lastReset time.Time
chEvalDialers chan struct{}
closeOnce sync.Once
closeCh chan struct{}
onActiveDialer chan Dialer
priorTopDialer Dialer
hasSucceedingDialer chan bool
HasSucceedingDialer <-chan bool
configured chan struct{}
closeConfiguredOnce sync.Once
allowBackgroundChecking func() bool
}
// New creates a new Balancer using the supplied Dialers.
func New(allowBackgroundChecking func() bool, overallDialTimeout time.Duration, dialers ...Dialer) *Balancer {
log.Debugf("Constructing new balancer with %d dialers", len(dialers))
// a small alpha to gradually adjust timeout based on performance of all
// dialers
hasSucceedingDialer := make(chan bool, 1000)
b := &Balancer{
overallDialTimeout: overallDialTimeout,
closeCh: make(chan struct{}),
chEvalDialers: make(chan struct{}, 1),
onActiveDialer: make(chan Dialer, 1),
hasSucceedingDialer: hasSucceedingDialer,
HasSucceedingDialer: hasSucceedingDialer,
configured: make(chan struct{}),
allowBackgroundChecking: allowBackgroundChecking,
}
b.initOpsContext()
// TODO: remove or optimize the periodical probing
ops.Go(b.periodicallyProbeDialers)
ops.Go(b.periodicallyPrintStats)
ops.Go(b.evalDialersLoop)
ops.Go(b.KeepLookingForSucceedingDialer)
if len(dialers) > 0 {
b.Reset(dialers)
}
return b
}
// Reset closes existing dialers and replaces them with new ones.
func (b *Balancer) Reset(dialers []Dialer) {
if len(dialers) > 0 {
defer b.closeConfiguredOnce.Do(func() { close(b.configured) })
}
log.Debugf("Resetting with %d dialers", len(dialers))
dls := make(sortedDialers, len(dialers))
copy(dls, dialers)
sessionStats := make(map[string]*dialStats, len(dls))
for _, d := range dls {
sessionStats[d.Label()] = &dialStats{}
}
lastReset := time.Now()
b.mu.Lock()
oldDialers := b.dialers
b.dialers = dls
b.sessionStats = sessionStats
b.lastReset = lastReset
b.mu.Unlock()
recordTopDialer(b.sortDialers())
for _, dl := range oldDialers {
dl.Stop()
}
b.printStats()
b.requestEvalDialers("Resetting balancer")
}
// ResetFromExisting Resets using the existing dialers (useful when you want to
// force redialing).
func (b *Balancer) ResetFromExisting() {
log.Debugf("Resetting from existing dialers")
b.mu.Lock()
dialers := b.dialers
b.mu.Unlock()
b.Reset(dialers)
}
// Dial dials (network, addr) using one of the currently active configured
// Dialers. The dialer is chosen based on the following ordering:
//
// - succeeding dialers are preferred to failing
// - dialers whose bandwidth is unknown are preferred to those whose bandwidth
// is known (in order to collect data)
// - faster dialers (based on bandwidth / RTT) are preferred to slower ones
//
// Only Trusted Dialers are used to dial HTTP hosts.
//
// Dial looks through the proxy connections based on the above ordering and
// dial with the first available. If none are available, it keeps cycling
// through the list in priority order until it finds one. It will keep trying
// for up to 30 seconds, at which point it gives up.
//
// Blocks until dialers are available on the balancer (configured via the New
// constructor or b.Reset).
func (b *Balancer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
op := ops.Begin("balancer_dial")
defer op.End()
op = ops.Begin("balancer_dial_details")
defer op.End()
select {
case <-b.configured:
// The dialers are configured, so we can proceed.
case <-time.After(b.overallDialTimeout):
return nil, errors.New("timed out waiting for dialers to be configured")
case <-ctx.Done():
return nil, errors.New("no configured dialers: %v", ctx.Err())
}
start := time.Now()
bd, err := b.newBalancedDial(network, addr)
if err != nil {
return nil, op.FailIf(log.Error(err))
}
conn, err := bd.dial(ctx, start)
if err != nil {
return nil, op.FailIf(log.Error(err))
}
op.BalancerDialTime(time.Since(start), nil)
return conn, nil
}
// balancedDial encapsulates a single dial using the available Dialers
type balancedDial struct {
*Balancer
network string
addr string
sessionStats map[string]*dialStats
dialers []Dialer
failedUpstream map[int]Dialer
idx int
}
func (b *Balancer) newBalancedDial(network, addr string) (*balancedDial, error) {
dialers, sessionStats, pickErr := b.pickDialers(network, addr)
if pickErr != nil {
return nil, pickErr
}
return &balancedDial{
Balancer: b,
network: network,
addr: addr,
sessionStats: sessionStats,
dialers: dialers,
failedUpstream: make(map[int]Dialer, len(dialers)),
}, nil
}
func (bd *balancedDial) dial(parentCtx context.Context, start time.Time) (net.Conn, error) {
childCtx, cancel := context.WithTimeout(parentCtx, bd.Balancer.overallDialTimeout)
defer cancel()
attempts := 0
for {
conn, err := bd.dialWithDialer(childCtx, bd.dialers[bd.idx], start, attempts)
if err != nil {
// Log the dial error here as a trace since it's not fatal. If we
// have another dialer, we'll try it.
log.Tracef(
"Dialing %s://%s with %s failed: %v. You can ignore this since we'll try with other dialers.",
bd.network, bd.addr, bd.dialers[bd.idx].Label(), err)
} else {
return conn, nil
}
// Check context: if it dies, we can't continue.
select {
case <-childCtx.Done():
err = fmt.Errorf(
"Dialing %s://%s with %s on attempt %d context died (1st codepath): dial duration (%s): Context duration (%s). Context error: %w",
bd.network, bd.addr,
bd.dialers[bd.idx].Label(),
attempts, time.Since(start),
bd.Balancer.overallDialTimeout,
childCtx.Err())
return nil, err
default:
}
attempts++
if !bd.advanceToNextDialer(childCtx, attempts) {
// If we reached here, we have no more dialers and the context
// might've died. Determine the error and die
if childCtx.Err() != nil {
err = fmt.Errorf(
"Dialing %s://%s with %s on attempt %d context died (2nd codepath): Context duration (%s). Context error: %w",
bd.network, bd.addr,
bd.dialers[bd.idx].Label(),
attempts,
bd.Balancer.overallDialTimeout,
childCtx.Err())
} else {
err = fmt.Errorf("No more dialers for %s://%s with %s on attempt %d",
bd.network, bd.addr,
bd.dialers[bd.idx].Label(),
attempts)
}
return nil, err
}
// If we reach here, we failed with this dialer, but there are still
// other dialers in the pipeline. Advance to the next one.
}
// UNREACHABLE CODE
}
// advanceToNextDialer advances this balancedDial to the next dialer, cycling
// back to the beginning if necessary. If all dialers have failed upstream, this
// method returns false.
func (bd *balancedDial) advanceToNextDialer(
ctx context.Context,
attempts int) bool {
if len(bd.failedUpstream) == len(bd.dialers) {
// all dialers failed upstream, give up
return false
}
for {
select {
case <-ctx.Done():
return false
default:
}
bd.idx++
if bd.idx >= len(bd.dialers) {
bd.idx = 0
// back off
time.Sleep(time.Duration(attempts) * 250 * time.Millisecond)
}
if bd.failedUpstream[bd.idx] != nil {
// this dialer failed upstream, don't bother trying again
continue
}
return true
}
}
func (bd *balancedDial) dialWithDialer(ctx context.Context, dialer Dialer, start time.Time, attempts int) (net.Conn, error) {
deadline, _ := ctx.Deadline()
log.Tracef("Dialing %s://%s with %s on pass %v with timeout %v", bd.network, bd.addr, dialer.Label(), attempts, deadline.Sub(time.Now()))
oldRTT, oldBW := dialer.EstRTT(), dialer.EstBandwidth()
conn, failedUpstream, err := dialer.DialContext(ctx, bd.network, bd.addr)
if err != nil {
bd.onFailure(dialer, failedUpstream, err, attempts)
return nil, err
}
// Multiplexed dialers don't wait for anything from the proxy when dialing
// "persistent" connections, so we can't blindly trust such connections as
// signals of success dialers.
if bd.network == NetworkPersistent {
return conn, nil
}
// Please leave this at Debug level, as it helps us understand
// performance issues caused by a poor proxy being selected.
log.Debugf("Successfully dialed via %v to %v://%v on pass %v (%v)", dialer.Label(), bd.network, bd.addr, attempts, time.Since(start))
bd.onSuccess(dialer)
// Reevaluate all dialers if the top dialer performance dramatically changed
if attempts == 0 {
switch {
case dialer.EstRTT() > oldRTT*5:
reason := fmt.Sprintf("Dialer %s RTT increased from %v to %v",
dialer.Label(), oldRTT, dialer.EstRTT())
bd.requestEvalDialers(reason)
case dialer.EstBandwidth()*5 < oldBW:
reason := fmt.Sprintf("Dialer %s bandwidth decreased from %v to %v",
dialer.Label(), oldBW, dialer.EstBandwidth())
bd.requestEvalDialers(reason)
default:
}
}
return conn, nil
}
func (bd *balancedDial) onSuccess(dialer Dialer) {
atomic.AddInt64(&bd.sessionStats[dialer.Label()].success, 1)
select {
case bd.onActiveDialer <- dialer:
default:
}
// Mark dialers with upstream errors with failure, since we found a
// dialer that doesn't suffer from an upstream error. An example of
// when this might happen is if some dialers have upstream network
// connectivity issues that prevent them from resolving or connecting
// to the origin, but other dialers don't suffer from the same issues.
for _, d := range bd.failedUpstream {
atomic.AddInt64(&bd.sessionStats[d.Label()].failure, 1)
d.MarkFailure()
}
}
func (bd *balancedDial) onFailure(dialer Dialer, failedUpstream bool, err error, attempts int) {
continueString := "...continuing"
if failedUpstream {
continueString = "...aborting"
}
msg := "%v dialing via %v to %s://%s: %v on pass %v%v"
if failedUpstream {
log.Debugf(msg,
"Upstream error", dialer.Label(), bd.network, bd.addr, err, attempts, continueString)
} else {
log.Errorf(msg,
"Unexpected error", dialer.Label(), bd.network, bd.addr, err, attempts, continueString)
}
if failedUpstream {
bd.failedUpstream[bd.idx] = dialer
} else {
atomic.AddInt64(&bd.sessionStats[dialer.Label()].failure, 1)
if attempts == 0 {
// Whenever top dialer fails, re-evaluate dialers immediately
// without checking connectivity for faster convergence. A full
// check and re-evaluating should follow up if the dialer changes,
// to avoid permanently switching to a slow dialer due to outdated
// measurements.
if bd.evalDialers() {
bd.requestEvalDialers("Top dialer changed because of failing")
}
}
}
}
// OnActiveDialer returns the channel of the last dialer the balancer was using.
// Can be called only once.
func (b *Balancer) OnActiveDialer() <-chan Dialer {
return b.onActiveDialer
}
// evalDialersLoop keeps running until the balancer is closed. It checks a
// channel every second to see if there are requests to evalulate all dialers,
// runs it, then wait for one minute (randomized) to recheck the channel.
func (b *Balancer) evalDialersLoop() {
nextEvalTimer := time.NewTimer(0)
defer nextEvalTimer.Stop()
chDone := make(chan struct{})
for {
select {
case <-nextEvalTimer.C:
select {
case <-b.chEvalDialers:
ops.Go(func() {
b.checkConnectivityForAll()
_ = b.evalDialers()
chDone <- struct{}{}
})
default:
nextEvalTimer.Reset(evalInterval / 60)
}
case <-chDone:
nextEvalTimer.Reset(randomize(evalInterval))
case <-b.closeCh:
return
}
}
}
// evalDialers re-orders dailers and reports/logs the result. It returns true
// if the top dialer changed.
func (b *Balancer) evalDialers() (changed bool) {
dialers := b.sortDialers()
if len(dialers) < 2 {
// nothing to do
return
}
newTopDialer := dialers[0]
op := ops.Begin("proxy_selection_stability")
defer op.End()
b.mu.RLock()
priorTopDialer := b.priorTopDialer
b.mu.RUnlock()
if priorTopDialer == nil {
op.SetMetricSum("top_dialer_initialized", 1)
log.Debugf("Top dialer initialized to %v", newTopDialer.Label())
} else if newTopDialer.Name() == priorTopDialer.Name() {
op.SetMetricSum("top_dialer_unchanged", 1)
log.Debug("Top dialer unchanged")
return
} else {
changed = true
op.SetMetricSum("top_dialer_changed", 1)
reason := "performance"
if !priorTopDialer.Succeeding() {
reason = "failing"
}
op.Set("reason", reason)
log.Debugf("Top dialer changed from %v to %v", priorTopDialer.Label(), newTopDialer.Label())
recordTopDialer(dialers)
}
b.mu.Lock()
b.priorTopDialer = newTopDialer
b.mu.Unlock()
// Print stats immediately after dialer initialized / changed so we have an
// idea what caused it.
b.printStats()
return
}
func (b *Balancer) checkConnectivityForAll() {
dialers := b.copyOfDialers()
if len(dialers) < 2 {
// nothing to do
return
}
log.Debugf("Rechecking connectivity for %d dialers", len(dialers))
var wg sync.WaitGroup
wg.Add(len(dialers))
for _, _d := range dialers {
d := _d
ops.Go(func() {
for i := 0; i < connectivityRechecks; i++ {
d.Probe(false)
time.Sleep(randomize(recheckInterval))
}
wg.Done()
})
}
wg.Wait()
}
func (b *Balancer) requestEvalDialers(reason string) {
if !b.allowBackgroundChecking() {
log.Debug("skip re-evaluating dialers because background checking is not allowed")
return
}
select {
case b.chEvalDialers <- struct{}{}:
log.Debug(reason + ", re-evaluating all dialers")
default:
}
}
// Close closes this Balancer, stopping all background processing. You must call
// Close to avoid leaking goroutines.
func (b *Balancer) Close() {
b.closeOnce.Do(func() {
b.Reset([]Dialer{})
close(b.closeCh)
})
}
func (b *Balancer) periodicallyProbeDialers() {
t := time.NewTimer(0)
defer t.Stop()
for {
t.Reset(randomize(10 * time.Minute))
select {
case <-t.C:
if b.allowBackgroundChecking() {
log.Debugf("Start periodical probing")
b.checkConnectivityForAll()
log.Debugf("End periodical probing")
}
case <-b.closeCh:
return
}
}
}
func (b *Balancer) periodicallyPrintStats() {
ticker := time.NewTicker(printStatsInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
b.printStats()
case <-b.closeCh:
return
}
}
}
func (b *Balancer) printStats() {
b.mu.Lock()
dialers := b.dialers
lastReset := b.lastReset
b.mu.Unlock()
log.Debugf("----------- Dialer Stats (%v) -----------", time.Since(lastReset))
rank := float64(1)
var buf strings.Builder
for _, d := range dialers {
estRTT := d.EstRTT().Seconds()
estBandwidth := d.EstBandwidth()
d.WriteStats(&buf)
log.Debug(buf.String())
buf.Reset()
host, _, _ := net.SplitHostPort(d.Addr())
// Report stats to borda
op := ops.Begin("proxy_rank").
ProxyName(d.Name()).
Set("proxy_host", host).
SetMetricAvg("rank", rank).
SetMetricAvg("est_rtt_ms", estRTT*1000)
if estBandwidth > 0 {
op.SetMetricAvg("est_mbps", estBandwidth)
}
op.End()
rank++
}
log.Debug("----------- End Dialer Stats -----------")
}
func (b *Balancer) pickDialers(network, addr string) ([]Dialer, map[string]*dialStats, error) {
trustedOnly := false
_, port, _ := net.SplitHostPort(addr)
// We try to identify HTTP traffic (as opposed to HTTPS) by port and only
// send HTTP traffic to dialers marked as trusted.
if port == "" || port == "80" || port == "8080" {
trustedOnly = true
}
b.mu.RLock()
_dialers := b.dialers
if trustedOnly {
_dialers = b.trusted
}
sessionStats := b.sessionStats
b.mu.RUnlock()
// Pick only dialers that support the requested network and address.
dialers := make(sortedDialers, 0, len(_dialers))
for _, d := range _dialers {
if d.SupportsAddr(network, addr) {
dialers = append(dialers, d)
}
}
if dialers.Len() == 0 {
if trustedOnly {
return nil, nil, fmt.Errorf("No trusted dialers")
}
return nil, nil, fmt.Errorf("No dialers")
}
return dialers, sessionStats, nil
}
func (b *Balancer) copyOfDialers() sortedDialers {
b.mu.RLock()
_dialers := b.dialers
b.mu.RUnlock()
dialers := make(sortedDialers, len(_dialers))
copy(dialers, _dialers)
return dialers
}
func (b *Balancer) sortDialers() []Dialer {
dialers := SortDialers(b.copyOfDialers())
trusted := make(sortedDialers, 0, len(dialers))
for _, d := range dialers {
if d.Trusted() {
trusted = append(trusted, d)
}
}
b.mu.Lock()
b.dialers = dialers
b.trusted = trusted
b.mu.Unlock()
return dialers
}
func (b *Balancer) KeepLookingForSucceedingDialer() {
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
defer close(b.hasSucceedingDialer)
for {
select {
case <-ticker.C:
b.mu.RLock()
dialers := b.dialers
b.mu.RUnlock()
hasSucceedingDialer := false
triedAllDialers := true
for _, dialer := range dialers {
if dialer.Succeeding() {
hasSucceedingDialer = true
}
if dialer.Attempts() == 0 {
triedAllDialers = false
}
}
if hasSucceedingDialer || triedAllDialers {
// only report if we've got a succeeding dialer, or if we've actually tried all dialers
select {
case b.hasSucceedingDialer <- hasSucceedingDialer:
// okay
default:
// channel full
}
}
case <-b.closeCh:
return
}
}
}
func recordTopDialer(sortedDialers []Dialer) {
ops.SetGlobal("num_proxies", len(sortedDialers))
if len(sortedDialers) == 0 {
ops.SetGlobal("top_proxy_name", nil)
ops.SetGlobal("top_dc", nil)
ops.SetGlobal("top_proxy_protocol", nil)
return
}
dialer := sortedDialers[0]
name, dc := ops.ProxyNameAndDC(dialer.Name())
if name != "" {
ops.SetGlobal("top_proxy_name", name)
}
if dc != "" {
ops.SetGlobal("top_dc", dc)
}
ops.SetGlobal("top_proxy_protocol", dialer.Protocol())
}
func SortDialers(dialers []Dialer) []Dialer {
sorted := sortedDialers(dialers)
sort.Sort(sorted)
return sorted
}
type sortedDialers []Dialer
func (d sortedDialers) Len() int { return len(d) }
func (d sortedDialers) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
// This is how the dialers are re-ordered. It's based on the assumption that
// the succeeding status and RTT are up-to-date when sorting (but sensitive to
// packet loss on the wire), while the less-updated estimated bandwidth can be
// a hint when RTT is somewhat comparable.
func (d sortedDialers) Less(i, j int) bool {
a, b := d[i], d[j]
// Prefer the proxy with higher success rate
rateA, rateB := a.EstSuccessRate(), b.EstSuccessRate()
if rateA-rateB > 0.1 {
return true
} else if rateB-rateA > 0.1 {
return false
}
if rateA < 0.1 && rateB < 0.1 {
// If both have very low success rate, sort randomly so that we have the best chance of
// finding a dialer that works.
return rand.Float64() < 0.5
}
eba, ebb := a.EstBandwidth(), b.EstBandwidth()
// should avoid sending traffic to proxy if bandwidth is unknown. The
// dialer will take care of probing for bandwidth when starts up.
ebaKnown, ebbKnown := eba != 0, ebb != 0
if ebaKnown && !ebbKnown {
return true
}
if !ebaKnown && ebbKnown {
return false
}
ela, elb := a.EstRTT().Seconds(), b.EstRTT().Seconds()
// when RTT differs significantly, choose the one with smaller RTT.
if ela*3 < elb {
return true
}
if elb*3 < ela {
return false
}
// bandwidth is known for neither proxy and RTT is comparable, sort by
// label to keep sending traffic to same proxy until we know bandwidth.
if !ebaKnown && !ebbKnown {
return strings.Compare(a.Label(), b.Label()) < 0
}
// divide bandwidth by rtt to determine how to sort
return float64(eba)/ela > float64(ebb)/elb
}
func randomize(d time.Duration) time.Duration {
return d/2 + time.Duration(rand.Int63n(int64(d)))
}
func (b *Balancer) initOpsContext() {
ops.SetGlobalDynamic("balancer_metrics", func() interface{} {
metrics := make(map[string]interface{}, 9)
setProxy := func(prefix string, dialer Dialer) {
name, dc := ops.ProxyNameAndDC(dialer.Name())
metrics[prefix+"_proxy"] = name
metrics[prefix+"_dc"] = dc
metrics[prefix+"_protocol"] = dialer.Protocol()
}
b.mu.RLock()
dialers := b.dialers
sessionStats := b.sessionStats
b.mu.RUnlock()
if len(dialers) == 0 {
// no dialers yet, ignore
return metrics
}
var topSession Dialer
topSessionAttempts := int64(-1)
var topAllTime Dialer
topAllTimeAttempts := int64(-1)
for _, dialer := range dialers {
ds := sessionStats[dialer.Label()]
sessionSuccesses := atomic.LoadInt64(&ds.success)
sessionFailures := atomic.LoadInt64(&ds.failure)
sessionAttempts := sessionSuccesses + sessionFailures
if sessionAttempts > topSessionAttempts {
topSession = dialer
topSessionAttempts = sessionAttempts
}
allTimeAttempts := dialer.Attempts()
if allTimeAttempts > topAllTimeAttempts {
topAllTime = dialer
topAllTimeAttempts = allTimeAttempts
}
}
setProxy("top_current", dialers[0])
setProxy("top_session", topSession)
setProxy("top_all_time", topAllTime)
return metrics
})
}