/
TunnelPool.java
1346 lines (1244 loc) · 53.5 KB
/
TunnelPool.java
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 net.i2p.router.tunnel.pool;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.Lease;
import net.i2p.data.LeaseSet;
import net.i2p.data.TunnelId;
import net.i2p.router.RouterContext;
import net.i2p.router.TunnelInfo;
import net.i2p.router.TunnelPoolSettings;
import net.i2p.router.tunnel.HopConfig;
import net.i2p.router.tunnel.TunnelCreatorConfig;
import net.i2p.stat.Rate;
import net.i2p.stat.RateAverages;
import net.i2p.stat.RateStat;
import net.i2p.util.Log;
/**
* A group of tunnels for the router or a particular client, in a single direction.
* Public only for TunnelRenderer in router console.
*/
public class TunnelPool {
private final List<PooledTunnelCreatorConfig> _inProgress = new ArrayList<PooledTunnelCreatorConfig>();
protected final RouterContext _context;
protected final Log _log;
private TunnelPoolSettings _settings;
private final List<TunnelInfo> _tunnels;
private final TunnelPeerSelector _peerSelector;
private final TunnelPoolManager _manager;
protected volatile boolean _alive;
private long _lifetimeProcessed;
private int _lastSelectedIdx;
private final int _expireSkew;
private long _started;
private long _lastRateUpdate;
private long _lastLifetimeProcessed;
private final String _rateName;
private final long _firstInstalled;
private final AtomicInteger _consecutiveBuildTimeouts = new AtomicInteger();
private static final int TUNNEL_LIFETIME = 10*60*1000;
/** if less than one success in this many, reduce quantity (exploratory only) */
private static final int BUILD_TRIES_QUANTITY_OVERRIDE = 12;
/** if less than one success in this many, reduce length (exploratory only) */
private static final int BUILD_TRIES_LENGTH_OVERRIDE_1 = 8;
private static final int BUILD_TRIES_LENGTH_OVERRIDE_2 = 12;
private static final long STARTUP_TIME = 30*60*1000;
TunnelPool(RouterContext ctx, TunnelPoolManager mgr, TunnelPoolSettings settings, TunnelPeerSelector sel) {
_context = ctx;
_log = ctx.logManager().getLog(TunnelPool.class);
_manager = mgr;
_settings = settings;
_tunnels = new ArrayList<TunnelInfo>(settings.getTotalQuantity());
_peerSelector = sel;
_expireSkew = _context.random().nextInt(90*1000);
_started = System.currentTimeMillis();
_lastRateUpdate = _started;
_firstInstalled = ctx.getProperty("router.firstInstalled", 0L) + 60*60*1000;
String name;
if (_settings.isExploratory()) {
name = "exploratory";
} else {
name = _settings.getDestinationNickname();
// just strip HTML here rather than escape it everywhere in the console
if (name != null)
name = DataHelper.stripHTML(name);
else
name = _settings.getDestination().toBase32();
}
_rateName = "tunnel.Bps." + name +
(_settings.isInbound() ? ".in" : ".out");
refreshSettings();
ctx.statManager().createRateStat("tunnel.matchLease", "How often does our OBEP match their IBGW?", "Tunnels",
new long[] {60*60*1000});
}
/**
* Warning, this may be called more than once
* (without an intervening shutdown()) if the
* tunnel is stopped and then restarted by the client manager with the same
* Destination (i.e. for servers or clients w/ persistent key,
* or restarting close-on-idle clients)
*/
synchronized void startup() {
synchronized (_inProgress) {
_inProgress.clear();
}
if (_log.shouldLog(Log.INFO))
_log.info(toString() + ": Startup() called, was already alive? " + _alive, new Exception());
_alive = true;
_started = System.currentTimeMillis();
_lastRateUpdate = _started;
_lastLifetimeProcessed = 0;
_manager.getExecutor().repoll();
if (_settings.isInbound() && !_settings.isExploratory()) {
// we just reconnected and didn't require any new tunnel builders.
// however, we /do/ want a leaseSet, so build one
LeaseSet ls = null;
synchronized (_tunnels) {
ls = locked_buildNewLeaseSet();
}
if (ls != null)
requestLeaseSet(ls);
}
_context.statManager().createRequiredRateStat(_rateName,
"Tunnel Bandwidth (Bytes/sec)", "Tunnels",
new long[] { 5*60*1000l });
}
synchronized void shutdown() {
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": Shutdown called");
_alive = false;
_context.statManager().removeRateStat(_rateName);
synchronized (_inProgress) {
_inProgress.clear();
}
_consecutiveBuildTimeouts.set(0);
}
/**
* RateStat name for the bandwidth graph
* @return non-null
* @since 0.9.35
*/
public String getRateName() {
return _rateName;
}
private void refreshSettings() {
if (!_settings.isExploratory())
return; // don't override client specified settings
Properties props = new Properties();
props.putAll(_context.router().getConfigMap());
if (_settings.isInbound())
_settings.readFromProperties(TunnelPoolSettings.PREFIX_INBOUND_EXPLORATORY, props);
else
_settings.readFromProperties(TunnelPoolSettings.PREFIX_OUTBOUND_EXPLORATORY, props);
}
private long getLifetime() { return System.currentTimeMillis() - _started; }
/**
* Pull a random tunnel out of the pool. If there are none available but
* the pool is configured to allow 0hop tunnels, this builds a fake one
* and returns it.
*
* @return null on failure, but it should always build and return a fallback
*/
TunnelInfo selectTunnel() { return selectTunnel(true); }
private TunnelInfo selectTunnel(boolean allowRecurseOnFail) {
boolean avoidZeroHop = !_settings.getAllowZeroHop();
long now = _context.clock().now();
synchronized (_tunnels) {
if (_tunnels.isEmpty()) {
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": No tunnels to select from");
} else {
// if there are nonzero hop tunnels and the zero hop tunnels are fallbacks,
// avoid the zero hop tunnels
TunnelInfo backloggedTunnel = null;
if (avoidZeroHop) {
for (int i = 0; i < _tunnels.size(); i++) {
_lastSelectedIdx++;
if (_lastSelectedIdx >= _tunnels.size())
_lastSelectedIdx = 0;
TunnelInfo info = _tunnels.get(_lastSelectedIdx);
if (info.getLength() > 1 && info.getExpiration() > now) {
// avoid outbound tunnels where the 1st hop is backlogged
if (_settings.isInbound() || !_context.commSystem().isBacklogged(info.getPeer(1))) {
return info;
} else {
backloggedTunnel = info;
}
}
}
// return a random backlogged tunnel
if (backloggedTunnel != null) {
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": All tunnels are backlogged");
return backloggedTunnel;
}
}
// ok, either we are ok using zero hop tunnels, or only fallback tunnels remain. pick 'em
// randomly
for (int i = 0; i < _tunnels.size(); i++) {
TunnelInfo info = _tunnels.get(i);
if (info.getExpiration() > now) {
// avoid outbound tunnels where the 1st hop is backlogged
if (_settings.isInbound() || info.getLength() <= 1 ||
!_context.commSystem().isBacklogged(info.getPeer(1))) {
//_log.debug("Selecting tunnel: " + info + " - " + _tunnels);
return info;
} else {
backloggedTunnel = info;
}
}
}
// return a random backlogged tunnel
if (backloggedTunnel != null)
return backloggedTunnel;
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": after " + _tunnels.size() + " tries, no unexpired ones were found: " + _tunnels);
}
}
if (_alive && !avoidZeroHop)
buildFallback();
if (allowRecurseOnFail)
return selectTunnel(false);
else
return null;
}
/**
* Return the tunnel from the pool that is XOR-closet to the target.
* By using this instead of the random selectTunnel(),
* we force some locality in OBEP-IBGW connections to minimize
* those connections network-wide.
*
* Does not check for backlogged next peer.
* Does not return an expired tunnel.
*
* @return null on failure
* @since 0.8.10
*/
TunnelInfo selectTunnel(Hash closestTo) {
boolean avoidZeroHop = !_settings.getAllowZeroHop();
TunnelInfo rv = null;
long now = _context.clock().now();
synchronized (_tunnels) {
if (!_tunnels.isEmpty()) {
if (_tunnels.size() > 1)
Collections.sort(_tunnels, new TunnelInfoComparator(closestTo, avoidZeroHop));
for (TunnelInfo info : _tunnels) {
if (info.getExpiration() > now) {
rv = info;
break;
}
}
}
}
if (rv != null) {
_context.statManager().addRateData("tunnel.matchLease", closestTo.equals(rv.getFarEnd()) ? 1 : 0);
} else {
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": No tunnels to select from");
}
return rv;
}
/**
* @param gatewayId for inbound, the GW rcv tunnel ID; for outbound, the GW send tunnel ID.
*/
public TunnelInfo getTunnel(TunnelId gatewayId) {
synchronized (_tunnels) {
for (int i = 0; i < _tunnels.size(); i++) {
TunnelInfo info = _tunnels.get(i);
if (_settings.isInbound()) {
if (info.getReceiveTunnelId(0).equals(gatewayId))
return info;
} else {
if (info.getSendTunnelId(0).equals(gatewayId))
return info;
}
}
}
return null;
}
/**
* Return a list of tunnels in the pool
*
* @return A copy of the list of TunnelInfo objects
*/
public List<TunnelInfo> listTunnels() {
synchronized (_tunnels) {
return new ArrayList<TunnelInfo>(_tunnels);
}
}
/**
* Do we really need more fallbacks?
* Used to prevent a zillion of them.
* Does not check config, only call if config allows zero hop.
*/
boolean needFallback() {
long exp = _context.clock().now() + 120*1000;
synchronized (_tunnels) {
for (int i = 0; i < _tunnels.size(); i++) {
TunnelInfo info = _tunnels.get(i);
if (info.getLength() <= 1 && info.getExpiration() > exp)
return false;
}
}
return true;
}
/**
* Return settings.getTotalQuantity, unless this is an exploratory tunnel
* AND exploratory build success rate is less than 1/10, AND total settings
* is greater than 1. Otherwise subtract 1 to help prevent congestion collapse,
* and prevent really unintegrated routers from working too hard.
* We only do this for exploratory as different clients could have different
* length settings. Although I guess inbound and outbound exploratory
* could be different too, and inbound is harder...
*
* As of 0.9.19, add more if exploratory and floodfill, as floodfills
* generate a lot of exploratory traffic.
* TODO high-bandwidth non-floodfills do also...
*
* Also returns 1 if set for zero hop, client or exploratory.
*
* @since 0.8.11
*/
private int getAdjustedTotalQuantity() {
if (_settings.getLength() == 0 && _settings.getLengthVariance() == 0)
return 1;
int rv = _settings.getTotalQuantity();
if (!_settings.isExploratory()) {
if (rv <= 1)
return rv;
// throttle client tunnel builds in times of congestion
int fails = _consecutiveBuildTimeouts.get();
if (fails > 4) {
if (fails > 12) {
rv = 1;
if (_log.shouldWarn())
_log.warn("Limit to 1 tunnel after " + fails + " consec. build timeouts on " + this);
} else if (fails > 8) {
rv = Math.max(1, rv / 3);
if (_log.shouldWarn())
_log.warn("Limit to " + rv + " tunnels after " + fails + " consec. build timeouts on " + this);
} else if (rv > 2) {
rv--;
if (_log.shouldWarn())
_log.warn("Limit to " + rv + " tunnels after " + fails + " consec. build timeouts on " + this);
}
}
return rv;
}
// TODO high-bw non-ff also
if (_context.netDb().floodfillEnabled() &&
_context.router().getUptime() > 5*60*1000) {
rv += 2;
}
if (rv > 1) {
RateStat e = _context.statManager().getRate("tunnel.buildExploratoryExpire");
RateStat r = _context.statManager().getRate("tunnel.buildExploratoryReject");
RateStat s = _context.statManager().getRate("tunnel.buildExploratorySuccess");
if (e != null && r != null && s != null) {
Rate er = e.getRate(10*60*1000);
Rate rr = r.getRate(10*60*1000);
Rate sr = s.getRate(10*60*1000);
if (er != null && rr != null && sr != null) {
RateAverages ra = RateAverages.getTemp();
long ec = er.computeAverages(ra, false).getTotalEventCount();
long rc = rr.computeAverages(ra, false).getTotalEventCount();
long sc = sr.computeAverages(ra, false).getTotalEventCount();
long tot = ec + rc + sc;
if (tot >= BUILD_TRIES_QUANTITY_OVERRIDE) {
if (1000 * sc / tot <= 1000 / BUILD_TRIES_QUANTITY_OVERRIDE)
rv--;
}
}
}
}
if (_context.router().getUptime() < STARTUP_TIME) {
// more exploratory during startup, when we are refreshing the netdb RIs
rv++;
}
return rv;
}
/**
* Shorten the length when under extreme stress, else clear the override.
* We only do this for exploratory tunnels, since we have to build a fallback
* if we run out. It's much better to have a shorter tunnel than a fallback.
*
* @since 0.8.11
*/
private void setLengthOverride() {
if (!_settings.isExploratory())
return;
int len = _settings.getLength();
if (len > 1) {
RateStat e = _context.statManager().getRate("tunnel.buildExploratoryExpire");
RateStat r = _context.statManager().getRate("tunnel.buildExploratoryReject");
RateStat s = _context.statManager().getRate("tunnel.buildExploratorySuccess");
if (e != null && r != null && s != null) {
Rate er = e.getRate(10*60*1000);
Rate rr = r.getRate(10*60*1000);
Rate sr = s.getRate(10*60*1000);
if (er != null && rr != null && sr != null) {
RateAverages ra = RateAverages.getTemp();
long ec = er.computeAverages(ra, false).getTotalEventCount();
long rc = rr.computeAverages(ra, false).getTotalEventCount();
long sc = sr.computeAverages(ra, false).getTotalEventCount();
long tot = ec + rc + sc;
if (tot >= BUILD_TRIES_LENGTH_OVERRIDE_1 ||
_firstInstalled > _context.clock().now()) {
long succ = tot > 0 ? 1000 * sc / tot : 0;
if (succ <= 1000 / BUILD_TRIES_LENGTH_OVERRIDE_1) {
if (len > 2 && succ <= 1000 / BUILD_TRIES_LENGTH_OVERRIDE_2)
_settings.setLengthOverride(len - 2);
else
_settings.setLengthOverride(len - 1);
return;
}
}
}
}
}
// disable
_settings.setLengthOverride(-1);
}
/** list of tunnelInfo instances of tunnels currently being built */
public List<PooledTunnelCreatorConfig> listPending() { synchronized (_inProgress) { return new ArrayList<PooledTunnelCreatorConfig>(_inProgress); } }
/** duplicate of size(), let's pick one */
int getTunnelCount() { return size(); }
public TunnelPoolSettings getSettings() { return _settings; }
void setSettings(TunnelPoolSettings settings) {
if (settings != null && _settings != null) {
if (!(settings.isExploratory() || _settings.isExploratory())) {
settings.getAliases().addAll(_settings.getAliases());
settings.setAliasOf(_settings.getAliasOf());
}
}
_settings = settings;
if (_settings != null) {
if (_log.shouldLog(Log.INFO))
_log.info(toString() + ": Settings updated on the pool: " + settings);
_manager.getExecutor().repoll(); // in case we need more
}
}
/**
* Is this pool running AND either exploratory, or tracked by the client manager?
* A pool will be alive but not tracked after the client manager removes it
* but before all the tunnels have expired.
*/
public boolean isAlive() {
return _alive &&
(_settings.isExploratory() ||
_context.clientManager().isLocal(_settings.getDestination()));
}
/** duplicate of getTunnelCount(), let's pick one */
public int size() {
synchronized (_tunnels) {
return _tunnels.size();
}
}
/**
* Add to the pool.
*/
protected void addTunnel(TunnelInfo info) {
if (_log.shouldLog(Log.DEBUG))
_log.debug(toString() + ": Adding tunnel " + info /* , new Exception("Creator") */ );
LeaseSet ls = null;
synchronized (_tunnels) {
_tunnels.add(info);
if (_settings.isInbound() && !_settings.isExploratory())
ls = locked_buildNewLeaseSet();
}
if (ls != null)
requestLeaseSet(ls);
}
/**
* Remove from the pool.
*/
void removeTunnel(TunnelInfo info) {
if (_log.shouldLog(Log.DEBUG))
_log.debug(toString() + ": Removing tunnel " + info);
int remaining = 0;
LeaseSet ls = null;
synchronized (_tunnels) {
boolean removed = _tunnels.remove(info);
if (!removed)
return;
if (_settings.isInbound() && !_settings.isExploratory())
ls = locked_buildNewLeaseSet();
remaining = _tunnels.size();
}
_manager.getExecutor().repoll();
_lifetimeProcessed += info.getProcessedMessagesCount();
updateRate();
long lifetimeConfirmed = info.getVerifiedBytesTransferred();
long lifetime = 10*60*1000;
for (int i = 0; i < info.getLength(); i++)
_context.profileManager().tunnelLifetimePushed(info.getPeer(i), lifetime, lifetimeConfirmed);
if (_alive && _settings.isInbound() && !_settings.isExploratory()) {
if (ls != null) {
requestLeaseSet(ls);
} else {
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": unable to build a new leaseSet on removal (" + remaining
+ " remaining), request a new tunnel");
if (_settings.getAllowZeroHop())
buildFallback();
}
}
if (getTunnelCount() <= 0 && !isAlive()) {
// this calls both our shutdown() and the other one (inbound/outbound)
// This is racy - see TunnelPoolManager
_manager.removeTunnels(_settings.getDestination());
}
}
/**
* Remove the tunnel and blame all the peers (not necessarily equally).
* This may be called multiple times from TestJob.
*/
void tunnelFailed(TunnelInfo cfg) {
fail(cfg);
tellProfileFailed(cfg);
}
/**
* Remove the tunnel and blame only one peer.
* This may be called multiple times.
*
* @since 0.8.13
*/
void tunnelFailed(TunnelInfo cfg, Hash blamePeer) {
fail(cfg);
_context.profileManager().tunnelFailed(blamePeer, 100);
}
/**
* Remove the tunnel.
*/
private void fail(TunnelInfo cfg) {
LeaseSet ls = null;
synchronized (_tunnels) {
boolean removed = _tunnels.remove(cfg);
if (!removed)
return;
if (_settings.isInbound() && !_settings.isExploratory())
ls = locked_buildNewLeaseSet();
}
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": Tunnel failed: " + cfg);
_manager.tunnelFailed();
_lifetimeProcessed += cfg.getProcessedMessagesCount();
updateRate();
if (_settings.isInbound() && !_settings.isExploratory()) {
if (ls != null) {
requestLeaseSet(ls);
}
}
}
/**
* Blame all the other peers in the tunnel, with a probability
* inversely related to the tunnel length
*/
private void tellProfileFailed(TunnelInfo cfg) {
int len = cfg.getLength();
if (len < 2)
return;
int start = 0;
int end = len;
if (cfg.isInbound())
end--;
else
start++;
for (int i = start; i < end; i++) {
int pct = 100/(len-1);
// if inbound, it's probably the gateway's fault
if (cfg.isInbound() && len > 2) {
if (i == start)
pct *= 2;
else
pct /= 2;
}
if (_log.shouldLog(Log.WARN))
_log.warn(toString() + ": Blaming " + cfg.getPeer(i) + ' ' + pct + '%');
_context.profileManager().tunnelFailed(cfg.getPeer(i), pct);
}
}
private void updateRate() {
long now = _context.clock().now();
long et = now - _lastRateUpdate;
if (et > 2*60*1000) {
long bw = 1024 * (_lifetimeProcessed - _lastLifetimeProcessed) * 1000 / et; // Bps
_context.statManager().addRateData(_rateName, bw);
_lastRateUpdate = now;
_lastLifetimeProcessed = _lifetimeProcessed;
}
}
/** noop for outbound and exploratory */
void refreshLeaseSet() {
if (_settings.isInbound() && !_settings.isExploratory()) {
if (_log.shouldLog(Log.DEBUG))
_log.debug(toString() + ": refreshing leaseSet on tunnel expiration (but prior to grace timeout)");
LeaseSet ls;
synchronized (_tunnels) {
ls = locked_buildNewLeaseSet();
}
if (ls != null) {
requestLeaseSet(ls);
}
}
}
/**
* Request lease set from client for the primary and all aliases.
*
* @param ls non-null
* @since 0.9.49
*/
private void requestLeaseSet(LeaseSet ls) {
_context.clientManager().requestLeaseSet(_settings.getDestination(), ls);
Set<Hash> aliases = _settings.getAliases();
if (aliases != null && !aliases.isEmpty()) {
for (Hash h : aliases) {
// don't corrupt other requests
LeaseSet ls2 = new LeaseSet();
for (int i = 0; i < ls.getLeaseCount(); i++) {
ls2.addLease(ls.getLease(i));
}
_context.clientManager().requestLeaseSet(h, ls2);
}
}
}
/**
* This will build a fallback (zero-hop) tunnel ONLY if
* this pool is exploratory, or the settings allow it.
*
* @return true if a fallback tunnel is built
*/
boolean buildFallback() {
int quantity = getAdjustedTotalQuantity();
int usable = 0;
synchronized (_tunnels) {
usable = _tunnels.size();
}
if (usable > 0)
return false;
if (_settings.isExploratory() || _settings.getAllowZeroHop()) {
if (_log.shouldLog(Log.INFO))
_log.info(toString() + ": building a fallback tunnel (usable: " + usable + " needed: " + quantity + ")");
// runs inline, since its 0hop
_manager.getExecutor().buildTunnel(configureNewTunnel(true));
return true;
}
return false;
}
/**
* Always build a LeaseSet with Leases in sorted order,
* so that LeaseSet.equals() and lease-by-lease equals() always work.
* The sort method is arbitrary, as far as the equals() tests are concerned,
* but we use latest expiration first, since we need to sort them by that anyway.
*
*/
private static class LeaseComparator implements Comparator<Lease>, Serializable {
public int compare(Lease l, Lease r) {
long lt = l.getEndTime();
long rt = r.getEndTime();
if (rt > lt)
return 1;
if (rt < lt)
return -1;
return 0;
}
}
/**
* Find the tunnel with the far-end that is XOR-closest to a given hash
*
* @since 0.8.10
*/
private static class TunnelInfoComparator implements Comparator<TunnelInfo>, Serializable {
private final byte[] _base;
private final boolean _avoidZero;
/**
* @param target key to compare distances with
* @param avoidZeroHop if true, zero-hop tunnels will be put last
*/
public TunnelInfoComparator(Hash target, boolean avoidZeroHop) {
_base = target.getData();
_avoidZero = avoidZeroHop;
}
public int compare(TunnelInfo lhs, TunnelInfo rhs) {
if (_avoidZero) {
// put the zero-hops last
int llen = lhs.getLength();
int rlen = rhs.getLength();
if (llen > 1 && rlen <= 1)
return -1;
if (rlen > 1 && llen <= 1)
return 1;
}
// TODO don't prefer exact match for security?
byte lhsb[] = lhs.getFarEnd().getData();
byte rhsb[] = rhs.getFarEnd().getData();
for (int i = 0; i < _base.length; i++) {
int ld = (lhsb[i] ^ _base[i]) & 0xff;
int rd = (rhsb[i] ^ _base[i]) & 0xff;
if (ld < rd)
return -1;
if (ld > rd)
return 1;
}
// latest-expiring first as a tie-breaker
return (int) (rhs.getExpiration() - lhs.getExpiration());
}
}
/**
* Build a leaseSet with the required tunnels that aren't about to expire.
* Caller must synchronize on _tunnels.
* The returned LeaseSet will be incomplete; it will not have the destination
* set and will not be signed. Only the leases will be included.
*
* @return null on failure
*/
protected LeaseSet locked_buildNewLeaseSet() {
if (!_alive)
return null;
int wanted = Math.min(_settings.getQuantity(), LeaseSet.MAX_LEASES);
if (_tunnels.size() < wanted) {
if (_log.shouldInfo())
_log.info(toString() + ": Not enough tunnels (" + _tunnels.size() + ", wanted " + wanted + ")");
// see comment below
if (_tunnels.isEmpty())
return null;
}
long expireAfter = _context.clock().now(); // + _settings.getRebuildPeriod();
TunnelInfo zeroHopTunnel = null;
Lease zeroHopLease = null;
TreeSet<Lease> leases = new TreeSet<Lease>(new LeaseComparator());
for (int i = 0; i < _tunnels.size(); i++) {
TunnelInfo tunnel = _tunnels.get(i);
if (tunnel.getExpiration() <= expireAfter)
continue; // expires too soon, skip it
if (tunnel.getLength() <= 1) {
// More than one zero-hop tunnel in a lease is pointless
// and increases the leaseset size needlessly.
// Keep only the one that expires the latest.
if (zeroHopTunnel != null) {
if (zeroHopTunnel.getExpiration() > tunnel.getExpiration())
continue;
if (zeroHopLease != null)
leases.remove(zeroHopLease);
}
zeroHopTunnel = tunnel;
}
TunnelId inId = tunnel.getReceiveTunnelId(0);
Hash gw = tunnel.getPeer(0);
if ( (inId == null) || (gw == null) ) {
_log.error(toString() + ": broken? tunnel has no inbound gateway/tunnelId? " + tunnel);
continue;
}
Lease lease = new Lease();
// bugfix
// ExpireJob reduces the expiration, which causes a 2nd leaseset with the same lease
// to have an earlier expiration, so it isn't stored.
// Get the "real" expiration from the gateway hop config,
// HopConfig expirations are the same as the "real" expiration and don't change
// see configureNewTunnel()
lease.setEndDate(((TunnelCreatorConfig)tunnel).getConfig(0).getExpiration());
lease.setTunnelId(inId);
lease.setGateway(gw);
leases.add(lease);
// remember in case we want to remove it for a later-expiring zero-hopper
if (tunnel.getLength() <= 1)
zeroHopLease = lease;
}
// Go ahead and use less leases for now, hopefully a new tunnel will be built soon
// and we will get called again to generate a full leaseset.
// For clients with high tunnel count or length,
// this will make startup considerably faster, and reduce loss of leaseset
// when one tunnel is lost, thus making us much more robust.
// This also helps when returning to full lease count after reduce-on-idle
// or close-on-idle.
// So we will generate a succession of leases at startup. That's OK.
// Do we want a config option for this, or are there times when we shouldn't do this?
if (leases.size() < wanted) {
if (_log.shouldInfo())
_log.info(toString() + ": Not enough leases (" + leases.size() + ", wanted " + wanted + ")");
if (leases.isEmpty())
return null;
}
LeaseSet ls = new LeaseSet();
Iterator<Lease> iter = leases.iterator();
int count = Math.min(leases.size(), wanted);
for (int i = 0; i < count; i++)
ls.addLease(iter.next());
if (_log.shouldLog(Log.INFO))
_log.info(toString() + ": built new leaseSet: " + ls);
return ls;
}
public long getLifetimeProcessed() { return _lifetimeProcessed; }
/**
* Keep a separate stat for each type, direction, and length of tunnel.
*/
private final String buildRateName() {
if (_settings.isExploratory())
return "tunnel.buildRatio.exploratory." + (_settings.isInbound() ? "in" : "out");
else
return "tunnel.buildRatio.l" + _settings.getLength() + "v" + _settings.getLengthVariance() +
(_settings.isInbound() ? ".in" : ".out");
}
/**
* Gather the data to see how many tunnels to build, and then actually compute that value (delegated to
* the countHowManyToBuild function below)
*
*/
int countHowManyToBuild() {
if (!isAlive()) {
return 0;
}
int wanted = getAdjustedTotalQuantity();
boolean allowZeroHop = _settings.getAllowZeroHop();
/**
* This algorithm builds based on the previous average length of time it takes
* to build a tunnel. This average is kept in the _buildRateName stat.
* It is a separate stat for each type of pool, since in and out building use different methods,
* as do exploratory and client pools,
* and each pool can have separate length and length variance settings.
* We add one minute to the stat for safety (two for exploratory tunnels).
*
* We linearly increase the number of builds per expiring tunnel from
* 1 to PANIC_FACTOR as the time-to-expire gets shorter.
*
* The stat will be 0 for first 10m of uptime so we will use the older, conservative algorithm
* below instead. This algorithm will take about 30m of uptime to settle down.
* Or, if we are building more than 33% of the time something is seriously wrong,
* we also use the conservative algorithm instead
*
**/
final String rateName = buildRateName();
// Compute the average time it takes us to build a single tunnel of this type.
int avg = 0;
RateStat rs = _context.statManager().getRate(rateName);
if (rs == null) {
// Create the RateStat here rather than at the top because
// the user could change the length settings while running
_context.statManager().createRequiredRateStat(rateName,
"Tunnel Build Frequency", "Tunnels",
new long[] { TUNNEL_LIFETIME });
rs = _context.statManager().getRate(rateName);
}
if (rs != null) {
Rate r = rs.getRate(TUNNEL_LIFETIME);
if (r != null)
avg = (int) ( TUNNEL_LIFETIME * r.getAverageValue() / wanted);
}
if (avg > 0 && avg < TUNNEL_LIFETIME / 3) { // if we're taking less than 200s per tunnel to build
final int PANIC_FACTOR = 4; // how many builds to kick off when time gets short
avg += 60*1000; // one minute safety factor
if (_settings.isExploratory())
avg += 60*1000; // two minute safety factor
long now = _context.clock().now();
int expireSoon = 0;
int expireLater = 0;
int expireTime[];
int fallback = 0;
synchronized (_tunnels) {
expireTime = new int[_tunnels.size()];
for (int i = 0; i < _tunnels.size(); i++) {
TunnelInfo info = _tunnels.get(i);
if (allowZeroHop || (info.getLength() > 1)) {
int timeToExpire = (int) (info.getExpiration() - now);
if (timeToExpire > 0 && timeToExpire < avg) {
expireTime[expireSoon++] = timeToExpire;
} else {
expireLater++;
}
} else if (info.getExpiration() - now > avg) {
fallback++;
}
}
}
int inProgress;
synchronized (_inProgress) {
inProgress = _inProgress.size();
}
int remainingWanted = (wanted - expireLater) - inProgress;
int rv = 0;
int latesttime = 0;
if (remainingWanted > 0) {
if (remainingWanted > expireSoon) {
rv = PANIC_FACTOR * (remainingWanted - expireSoon); // for tunnels completely missing
remainingWanted = expireSoon;
}
// add from 1 to PANIC_FACTOR builds, depending on how late it is
// only use the expire times of the latest-expiring tunnels,
// the other ones are extras
for (int i = 0; i < remainingWanted; i++) {
int latestidx = 0;
// given the small size of the array this is efficient enough
for (int j = 0; j < expireSoon; j++) {
if (expireTime[j] > latesttime) {
latesttime = expireTime[j];
latestidx = j;
}
}
expireTime[latestidx] = 0;
if (latesttime > avg / 2)
rv += 1;
else
rv += 2 + ((PANIC_FACTOR - 2) * (((avg / 2) - latesttime) / (avg / 2)));
}
}
if (rv > 0 && _log.shouldLog(Log.DEBUG))
_log.debug("New Count: rv: " + rv + " allow? " + allowZeroHop
+ " avg " + avg + " latesttime " + latesttime
+ " soon " + expireSoon + " later " + expireLater
+ " std " + wanted + " inProgress " + inProgress + " fallback " + fallback
+ " for " + toString());
_context.statManager().addRateData(rateName, rv + inProgress);
return rv;
}
// fixed, conservative algorithm - starts building 3 1/2 - 6m before expiration
// (210 or 270s) + (0..90s random)
long expireAfter = _context.clock().now() + _expireSkew; // + _settings.getRebuildPeriod() + _expireSkew;
int expire30s = 0;
int expire90s = 0;
int expire150s = 0;
int expire210s = 0;
int expire270s = 0;
int expireLater = 0;
int fallback = 0;
synchronized (_tunnels) {
for (int i = 0; i < _tunnels.size(); i++) {
TunnelInfo info = _tunnels.get(i);
if (allowZeroHop || (info.getLength() > 1)) {
long timeToExpire = info.getExpiration() - expireAfter;
if (timeToExpire <= 0) {
// consider it unusable
} else if (timeToExpire <= 30*1000) {
expire30s++;
} else if (timeToExpire <= 90*1000) {
expire90s++;
} else if (timeToExpire <= 150*1000) {