java.lang.Object
net.i2p.router.tunnel.pool.TunnelPoolManager
All Implemented Interfaces:
Service, TunnelManagerFacade

public class TunnelPoolManagerextends Object implements TunnelManagerFacade
Manage all the exploratory and client tunnel pools. Run the tunnel builder and handler threads.
  • Field Details

    • _context

      private final RouterContext _context
      The router context.
    • _log

      private final Log _log
      Logger for pool management.
    • _clientInboundPools

      private final Map<Hash, TunnelPool> _clientInboundPools
      Hash (destination) to TunnelPool.
    • _clientOutboundPools

      private final Map<Hash, TunnelPool> _clientOutboundPools
      Hash (destination) to TunnelPool.
    • _inboundExploratory

      private final TunnelPool _inboundExploratory
      The router's inbound exploratory pool.
    • _outboundExploratory

      private final TunnelPool _outboundExploratory
      The router's outbound exploratory pool.
    • _executor

      private final BuildExecutor _executor
      Runs the tunnel build requests.
    • _handler

      private final BuildHandler _handler
      Matches build replies to the requests.
    • _clientPeerSelector

      private final TunnelPeerSelector _clientPeerSelector
      Peer selector shared by the client pools.
    • _ghostPeerManager

      private final GhostPeerManager _ghostPeerManager
      Tracks peers that keep failing builds.
    • _isShutdown

      private volatile boolean _isShutdown
      True once the manager has shut down.
    • _numHandlerThreads

      private static volatile int _numHandlerThreads
      Threads running the build handler.
    • _handlerThreadId

      private static final AtomicInteger _handlerThreadId
      Counter naming the handler threads.
    • _handlerThreads

      private final CopyOnWriteArrayList<I2PThread> _handlerThreads
      The running handler threads.
    • _defaultMaxPctTunnels

      private final int _defaultMaxPctTunnels
      Steady-state share of tunnels allowed to clients.
    • _startupMaxPctTunnels

      private final int _startupMaxPctTunnels
      Larger share allowed while the router starts up.
    • _lastIncompleteLeaseSet

      private volatile long _lastIncompleteLeaseSet
      Wall-clock ms at which some pool last published an incomplete LeaseSet, or 0 if never. Used as a decaying signal rather than a live counter so a pool destroyed while incomplete cannot leave the relief stuck on.
    • _lastShareLimitLog

      private volatile long _lastShareLimitLog
      Wall-clock ms of the last participation-share log, for rate limiting.
    • SHARE_RELIEF_TOP

      static final double SHARE_RELIEF_TOP
      Build success at or above which no build-success relief is applied.
      See Also:
    • SHARE_RELIEF_BOTTOM

      static final double SHARE_RELIEF_BOTTOM
      Build success at or below which relief reaches its full factor of 2.
      See Also:
    • INCOMPLETE_LEASESET_RELIEF

      static final double INCOMPLETE_LEASESET_RELIEF
      Relief factor applied while any pool has published an incomplete LeaseSet.
      See Also:
    • INCOMPLETE_LEASESET_WINDOW_MS

      static final long INCOMPLETE_LEASESET_WINDOW_MS
      How long an incomplete-LeaseSet observation keeps relief active, in ms.
      See Also:
    • SHARE_LIMIT_LOG_INTERVAL_MS

      private static final long SHARE_LIMIT_LOG_INTERVAL_MS
      Minimum ms between participation-share limit log lines.
      See Also:
    • PROP_DISABLE_TUNNEL_TESTING

      private static final String PROP_DISABLE_TUNNEL_TESTING
      Config key turning tunnel testing off.
      See Also:
    • PROP_SLOW_TUNNEL_THRESHOLD

      private static final String PROP_SLOW_TUNNEL_THRESHOLD
      Config key for the slow tunnel latency threshold.
      See Also:
    • PROP_SLOW_TUNNEL_MIN

      private static final String PROP_SLOW_TUNNEL_MIN
      Config key for the floor on the slow tunnel threshold.
      See Also:
    • PROP_SLOW_TUNNEL_INTERVAL

      private static final String PROP_SLOW_TUNNEL_INTERVAL
      Config key for how often slow tunnels are checked.
      See Also:
    • DEFAULT_SLOW_THRESHOLD_MS

      private static final int DEFAULT_SLOW_THRESHOLD_MS
      Zero means derive the threshold from average latency.
      See Also:
    • DEFAULT_MIN_SLOW_THRESHOLD

      private static final int DEFAULT_MIN_SLOW_THRESHOLD
      The derived threshold never falls below 10 seconds.
      See Also:
    • DEFAULT_RUN_INTERVAL_MS

      private static final int DEFAULT_RUN_INTERVAL_MS
      Slow tunnels are checked every 60 seconds.
      See Also:
    • REFRESH_DELAY_AFTER_REMOVAL

      private static final long REFRESH_DELAY_AFTER_REMOVAL
      Replacement tunnels get 15 seconds to build before a refresh.
      See Also:
    • MAX_SHARE_RATIO

      private static final double MAX_SHARE_RATIO
      Largest client share ratio accepted.
      See Also:
    • POOL_CLEANUP_DELAY_MS

      private static final long POOL_CLEANUP_DELAY_MS
      Delay before removing pools after client disconnect. Allows tunnels to naturally expire rather than collapsing.
      See Also:
    • _pendingCleanups

      private final Map<Hash, TunnelPoolManager.DelayedPoolCleanup> _pendingCleanups
      Pending delayed cleanups for pool removal. Key: destination hash, Value: cleanup task.
    • _pendingOutboundStartups

      private final Map<Hash, TunnelPoolManager.ConditionalOutboundStartup> _pendingOutboundStartups
      Pending delayed outbound pool startups, keyed by destination hash. Cancelled when the pool is actually removed.
    • PROP_OUTBOUND_STARTUP_RETRIES

      static final String PROP_OUTBOUND_STARTUP_RETRIES
      Property: outbound tunnel startup retries.
      See Also:
    • DEFAULT_OUTBOUND_STARTUP_RETRIES

      private static final int DEFAULT_OUTBOUND_STARTUP_RETRIES
      Tries to bring up the outbound pool at startup.
      See Also:
  • Constructor Details

    • TunnelPoolManager

      public TunnelPoolManager(RouterContext ctx)
      Manage tunnel pools for the given router context.
      Parameters:
      ctx - the router context
  • Method Details

    • selectInboundTunnel

      public TunnelInfo selectInboundTunnel()
      Pick a random inbound exploratory tunnel. Warning - selectInboundExploratoryTunnel(Hash) is preferred.
      Specified by:
      selectInboundTunnel in interface TunnelManagerFacade
      Returns:
      null if none
    • selectInboundTunnel

      public TunnelInfo selectInboundTunnel(Hash destination)
      Pick a random inbound tunnel from the given destination's pool. Warning - selectInboundTunnel(Hash, Hash) is preferred.
      Specified by:
      selectInboundTunnel in interface TunnelManagerFacade
      Parameters:
      destination - if null, returns inbound exploratory tunnel
      Returns:
      null if none
    • selectOutboundTunnel

      public TunnelInfo selectOutboundTunnel()
      Pick a random outbound exploratory tunnel. Warning - selectOutboundExploratoryTunnel(Hash) is preferred.
      Specified by:
      selectOutboundTunnel in interface TunnelManagerFacade
      Returns:
      null if none
    • selectInboundTunnelForTest

      public TunnelInfo selectInboundTunnelForTest(Hash destination)
      Pick a tunnel from a destination's inbound pool to carry a test round's reply, preferring partners that have demonstrated they work. Used only by the test cycle; the live data path keeps using the uniform-random selectInboundTunnel(Hash).
      Parameters:
      destination - if null, an exploratory tunnel is used
      Returns:
      null if none
    • selectOutboundTunnelForTest

      public TunnelInfo selectOutboundTunnelForTest(Hash destination)
      Pick a tunnel from a destination's outbound pool to carry a test round's outbound leg, preferring partners that have demonstrated they work. Test cycle only.
      Parameters:
      destination - if null, an exploratory tunnel is used
      Returns:
      null if none
    • selectOutboundTunnel

      public TunnelInfo selectOutboundTunnel(Hash destination)
      Pick a random outbound tunnel from the given destination's pool. Warning - selectOutboundTunnel(Hash, Hash) is preferred.
      Specified by:
      selectOutboundTunnel in interface TunnelManagerFacade
      Parameters:
      destination - if null, returns outbound exploratory tunnel
      Returns:
      null if none
    • selectAnyOutboundTunnel

      public TunnelInfo selectAnyOutboundTunnel()
      Pick a random outbound tunnel from any pool — client pools first, then exploratory. Used by BuildRequestor for cross-pool build replies when the requesting pool's own tunnels are unavailable. Client tunnels provide a lower-latency reply path than exploratory.
      Specified by:
      selectAnyOutboundTunnel in interface TunnelManagerFacade
      Returns:
      null if none
    • selectAnyInboundTunnel

      public TunnelInfo selectAnyInboundTunnel()
      Pick a random inbound tunnel from any pool — client pools first, then exploratory. Used by BuildRequestor for cross-pool build replies when the requesting pool's own tunnels are unavailable.
      Specified by:
      selectAnyInboundTunnel in interface TunnelManagerFacade
      Returns:
      null if none
    • selectInboundExploratoryTunnel

      public TunnelInfo selectInboundExploratoryTunnel(Hash closestTo)
      Pick the inbound exploratory tunnel with the gateway closest to the given hash. By using this instead of the random selectTunnel(), we force some locality in OBEP-IBGW connections to minimize those connections network-wide.
      Specified by:
      selectInboundExploratoryTunnel in interface TunnelManagerFacade
      Parameters:
      closestTo - the hash whose closest gateway the returned tunnel should reach
      Returns:
      null if none
    • selectInboundTunnel

      public TunnelInfo selectInboundTunnel(Hash destination, Hash closestTo)
      Pick the inbound tunnel with the gateway closest to the given hash from the given destination's pool. By using this instead of the random selectTunnel(), we force some locality in OBEP-IBGW connections to minimize those connections network-wide.
      Specified by:
      selectInboundTunnel in interface TunnelManagerFacade
      Parameters:
      destination - if null, returns inbound exploratory tunnel
      closestTo - the hash whose closest gateway the returned tunnel should reach
      Returns:
      null if none
    • selectOutboundExploratoryTunnel

      public TunnelInfo selectOutboundExploratoryTunnel(Hash closestTo)
      Pick the outbound exploratory tunnel with the endpoint closest to the given hash. By using this instead of the random selectTunnel(), we force some locality in OBEP-IBGW connections to minimize those connections network-wide.
      Specified by:
      selectOutboundExploratoryTunnel in interface TunnelManagerFacade
      Parameters:
      closestTo - the hash whose closest gateway the returned tunnel should reach
      Returns:
      null if none
    • selectOutboundTunnel

      public TunnelInfo selectOutboundTunnel(Hash destination, Hash closestTo)
      Pick the outbound tunnel with the endpoint closest to the given hash from the given destination's pool. By using this instead of the random selectTunnel(), we force some locality in OBEP-IBGW connections to minimize those connections network-wide.
      Specified by:
      selectOutboundTunnel in interface TunnelManagerFacade
      Parameters:
      destination - if null, returns outbound exploratory tunnel
      closestTo - the hash whose closest gateway the returned tunnel should reach
      Returns:
      null if none
    • getFreeTunnelCount

      public int getFreeTunnelCount()
      Number of valid (non-failed, non-expired) inbound exploratory tunnels.
      Specified by:
      getFreeTunnelCount in interface TunnelManagerFacade
      Returns:
      the count of usable inbound exploratory tunnels
    • getOutboundTunnelCount

      public int getOutboundTunnelCount()
      Number of valid (non-failed, non-expired) outbound exploratory tunnels.
      Specified by:
      getOutboundTunnelCount in interface TunnelManagerFacade
      Returns:
      the count of usable outbound exploratory tunnels
    • getInboundClientTunnelCount

      public int getInboundClientTunnelCount()
      Number of GOOD (tested+passed, non-failed, non-expired) inbound client tunnels across all destinations.
      Specified by:
      getInboundClientTunnelCount in interface TunnelManagerFacade
      Returns:
      the count of good inbound client tunnels over all clients
    • getOutboundClientTunnelCount

      public int getOutboundClientTunnelCount()
      Number of GOOD (tested+passed, non-failed, non-expired) outbound client tunnels across all destinations.
      Specified by:
      getOutboundClientTunnelCount in interface TunnelManagerFacade
      Returns:
      the count of good outbound client tunnels over all clients
    • getOutboundClientTunnelCount

      public int getOutboundClientTunnelCount(Hash destination)
      Use to verify a tunnel pool is alive. During bootstrap (no GOOD tunnels yet), counts any valid tunnel (including UNTESTED) so the sidebar shows ok immediately after the first build. Once the pool has established GOOD tunnels, enforces a strict GOOD-only count — UNTESTED tunnels alone don't keep the indicator green.
      Specified by:
      getOutboundClientTunnelCount in interface TunnelManagerFacade
      Parameters:
      destination - hash of the destination owning the outbound pool
      Returns:
      number of outbound client tunnels for the given destination
    • getInboundClientTunnelCount

      public int getInboundClientTunnelCount(Hash destination)
      Use to verify a tunnel pool is alive. During bootstrap (no GOOD tunnels yet), counts any valid tunnel (including UNTESTED) so the sidebar shows ok immediately after the first build. Once the pool has established GOOD tunnels, enforces a strict GOOD-only count.
      Specified by:
      getInboundClientTunnelCount in interface TunnelManagerFacade
      Parameters:
      destination - hash of the destination owning the inbound pool
      Returns:
      number of inbound client tunnels for the given destination
    • getUsableInboundClientTunnelCount

      public int getUsableInboundClientTunnelCount(Hash destination)
      Get USABLE inbound client tunnel count for a specific destination.
      Parameters:
      destination - the client hash
      Returns:
      number of GOOD (tested+passed, non-failed, non-expired) tunnels
    • getUsableOutboundClientTunnelCount

      public int getUsableOutboundClientTunnelCount(Hash destination)
      Get USABLE outbound client tunnel count for a specific destination.
      Parameters:
      destination - the client hash
      Returns:
      number of GOOD (tested+passed, non-failed, non-expired) tunnels
    • getParticipatingCount

      public int getParticipatingCount()
      The number of tunnels we're participating in as a gateway or endpoint.
      Specified by:
      getParticipatingCount in interface TunnelManagerFacade
      Returns:
      number of tunnels where we are a gateway or an endpoint
    • getLastParticipatingExpiration

      public long getLastParticipatingExpiration()
      The expiration time of the last participating tunnel.
      Specified by:
      getLastParticipatingExpiration in interface TunnelManagerFacade
      Returns:
      expiration of the latest-expiring participating tunnel in milliseconds since the epoch, or -1 if we participate in none
    • getShareRatio

      public double getShareRatio()
      Get the share ratio of participating tunnels.
      Specified by:
      getShareRatio in interface TunnelManagerFacade
      Returns:
      (number of part. tunnels) / (estimated total number of hops in our expl.+client tunnels) We just use length setting, not variance, for speed
    • isValidTunnel

      public boolean isValidTunnel(Hash client, TunnelInfo tunnel)
      Check if a tunnel is valid and belongs to the client's pool.
      Specified by:
      isValidTunnel in interface TunnelManagerFacade
      Parameters:
      client - the destination hash identifying the client's pool
      tunnel - tunnel to validate
      Returns:
      true if the tunnel is valid and belongs to the client's pool
    • getInboundSettings

      public TunnelPoolSettings getInboundSettings()
      The inbound exploratory tunnel pool settings.
      Specified by:
      getInboundSettings in interface TunnelManagerFacade
      Returns:
      the inbound settings
    • getOutboundSettings

      public TunnelPoolSettings getOutboundSettings()
      The outbound exploratory tunnel pool settings.
      Specified by:
      getOutboundSettings in interface TunnelManagerFacade
      Returns:
      the outbound settings
    • setInboundSettings

      public void setInboundSettings(TunnelPoolSettings settings)
      The inbound exploratory tunnel pool settings.
      Specified by:
      setInboundSettings in interface TunnelManagerFacade
      Parameters:
      settings - the inbound settings
    • setOutboundSettings

      public void setOutboundSettings(TunnelPoolSettings settings)
      The outbound exploratory tunnel pool settings.
      Specified by:
      setOutboundSettings in interface TunnelManagerFacade
      Parameters:
      settings - the outbound settings
    • getInboundSettings

      public TunnelPoolSettings getInboundSettings(Hash client)
      Get settings for a client's inbound tunnel pool.
      Specified by:
      getInboundSettings in interface TunnelManagerFacade
      Parameters:
      client - the destination hash identifying the client's pool
      Returns:
      settings or null if not found
    • getOutboundSettings

      public TunnelPoolSettings getOutboundSettings(Hash client)
      Get settings for a client's outbound tunnel pool.
      Specified by:
      getOutboundSettings in interface TunnelManagerFacade
      Parameters:
      client - the destination hash identifying the client's pool
      Returns:
      settings or null if not found
    • setInboundSettings

      public void setInboundSettings(Hash client, TunnelPoolSettings settings)
      Set settings for a client's inbound tunnel pool.
      Specified by:
      setInboundSettings in interface TunnelManagerFacade
      Parameters:
      client - the destination hash identifying the client's pool
      settings - the inbound settings
    • setOutboundSettings

      public void setOutboundSettings(Hash client, TunnelPoolSettings settings)
      Set settings for a client's outbound tunnel pool.
      Specified by:
      setOutboundSettings in interface TunnelManagerFacade
      Parameters:
      client - the destination hash identifying the client's pool
      settings - the outbound settings
    • setSettings

      private static void setSettings(Map<Hash, TunnelPool> pools, Hash client, TunnelPoolSettings settings)
      Applies settings to one client's pools.
      Parameters:
      pools - the client pools by destination
      client - the client's destination
      settings - the settings to apply
    • restart

      public void restart()
      Restart all tunnel handlers and rebuild all tunnels.
      Specified by:
      restart in interface Service
    • buildTunnels

      public void buildTunnels(Destination client, ClientTunnelSettings settings)
      Used only at session startup. Do not use to change settings. Do not use for aliased destinations; use addAlias(Destination, ClientTunnelSettings, Destination).
      Specified by:
      buildTunnels in interface TunnelManagerFacade
      Parameters:
      client - connecting destination, whose hash keys the pools created here
      settings - per-destination inbound and outbound pool settings, which replace those of any pools that already exist
    • addAlias

      public boolean addAlias(Destination dest, ClientTunnelSettings settings, Destination existingClient)
      Add another destination to the same tunnels. Must have same encryption key and a different signing key.
      Specified by:
      addAlias in interface TunnelManagerFacade
      Parameters:
      dest - alias destination, which gets its own pools flagged as aliased
      settings - settings for the alias pools, retained under the primary hash
      existingClient - primary destination whose tunnels are being shared
      Returns:
      true if the destination was added, false if it already had a pool
      Throws:
      IllegalArgumentException - if the signing keys match or the encryption keys differ
    • removeAlias

      public void removeAlias(Destination dest)
      Remove a destination for the same tunnels as another.
      Specified by:
      removeAlias in interface TunnelManagerFacade
      Parameters:
      dest - alias destination to drop from the primary's alias set
    • removeTunnels

      public void removeTunnels(Destination dest)
      Must be called AFTER deregistration by the client manager.
      Specified by:
      removeTunnels in interface TunnelManagerFacade
      Parameters:
      dest - destination whose pools are scheduled for removal, deferred so its tunnels keep operating until they expire
    • removeTunnels

      public void removeTunnels(Hash destination)
      This will be called twice, once by the inbound and once by the outbound pool. Synched with buildTunnels(Destination, ClientTunnelSettings) above.

      Must be called AFTER deregistration by the client manager.

      Uses delayed cleanup to allow tunnels to continue operating until they naturally expire. Prevents pool collapse when client disconnects.

      Parameters:
      destination - the hash of the client whose pools are scheduled for removal; a null hash is ignored
    • forceRemoveTunnels

      public void forceRemoveTunnels(Hash destination)
      Force immediate removal of a pool - used for router shutdown.
      Parameters:
      destination - the hash of the client whose pools are dropped immediately; a null hash is ignored
    • doRemoveTunnels

      private void doRemoveTunnels(Hash destination)
      Actually perform pool removal.
      Parameters:
      destination - the hash of the client whose inbound and outbound pools are shut down here
    • buildComplete

      void buildComplete(PooledTunnelCreatorConfig cfg)
      Queue a recurring test job if appropriate.
      Parameters:
      cfg - the configuration of the tunnel that just built, whose pool the test job queues against
    • disableTunnelTesting

      public boolean disableTunnelTesting()
      Report whether periodic tunnel testing is switched off.
      Returns:
      true if tunnel testing is disabled by property, false if it is enabled
    • startup

      public void startup()
      Start the tunnel pool manager and build initial tunnels.
      Specified by:
      startup in interface Service
    • getBuildHandlerThreads

      public static int getBuildHandlerThreads()
      Tuned by Tuner — min 2, max 8.
      Returns:
      number of build handler threads
    • setBuildHandlerThreads

      public static void setBuildHandlerThreads(int val)
      The number of build handler threads.
      Parameters:
      val - thread count (clamped 2-8)
    • getBuildHandlerThreadCount

      public int getBuildHandlerThreadCount()
      Actual number of running BuildHandler threads. May differ from getBuildHandlerThreads() if threads were interrupted or failed to start.
      Returns:
      current build handler thread count
    • adjustBuildHandlerThreads

      public void adjustBuildHandlerThreads(int target)
      Dynamically adjust BuildHandler thread count to match target.
      Parameters:
      target - desired thread count
    • replaceSlowTunnels

      public boolean replaceSlowTunnels()
      Find and remove tunnels exceeding the latency threshold. Does not blame peers for the removal. Removes all such tunnels per pool if pool has more tunnels than configured quantity, but won't go below the configured quantity. Threshold is either the configured property (in ms), or Math.max(int, int)avg latency, DEFAULT_MIN_SLOW_THRESHOLD), whichever is larger.
      Returns:
      true if any tunnels were removed
    • pruneAllPools

      public void pruneAllPools()
      Prune excess tunnels from all pools to stay within budget. Called periodically from RemoveSlowTunnelsJob to ensure we don't exceed the configured tunnel quantity for any pool.
    • shutdown

      public void shutdown()
      Shut the pool manager down. A shutdown manager cannot be restarted.
      Specified by:
      shutdown in interface Service
    • schedulePeerTests

      private void schedulePeerTests(List<Hash> peers)
      Schedule peers for priority testing.
      Parameters:
      peers - list of peer hashes to test urgently
    • cancelPendingOutboundStartup

      private void cancelPendingOutboundStartup(Hash destination)
      Cancel any pending outbound startup event for the destination. Called when the pool is actually removed.
      Parameters:
      destination - the destination hash
    • shutdownExploratory

      private void shutdownExploratory()
      Shuts down the two exploratory pools.
    • listPools

      public void listPools(List<TunnelPool> out)
      List of TunnelPool instances currently in play.
      Specified by:
      listPools in interface TunnelManagerFacade
      Parameters:
      out - list that the client inbound, client outbound and both exploratory pools are appended to
    • tunnelFailed

      void tunnelFailed()
      Poke the build executor to build more tunnels.
    • reportSendFailure

      public void reportSendFailure(TunnelInfo tunnel, int status)
      Report a data-phase send failure for a specific outbound tunnel. Routes to the correct pool (client or exploratory) based on the tunnel's destination, so the pool can increment the failure counter and trigger replacement builds immediately.
      Specified by:
      reportSendFailure in interface TunnelManagerFacade
      Parameters:
      tunnel - the outbound tunnel that carried the failed message
      status - the I2CP MessageStatusMessage failure code
    • forceTunnelFailure

      public void forceTunnelFailure(TunnelInfo tunnel)
      Force a tunnel to fail immediately and trigger a replacement build. Used when rotation is saturated and the pool has no viable alternative tunnels.
      Specified by:
      forceTunnelFailure in interface TunnelManagerFacade
      Parameters:
      tunnel - the outbound tunnel to force-fail
    • getExecutor

      BuildExecutor getExecutor()
      Return the shared thread pool that runs tunnel builds.
      Returns:
      the build executor
    • removeFromExpiration

      void removeFromExpiration(PooledTunnelCreatorConfig cfg)
      Remove a tunnel from the expiration queue to prevent memory leak.
      Parameters:
      cfg - the tunnel configuration to drop from the expiration queue
    • getGhostPeerManager

      public GhostPeerManager getGhostPeerManager()
      The ghost peer manager for tracking unresponsive peers.
      Specified by:
      getGhostPeerManager in interface TunnelManagerFacade
      Returns:
      the manager of peers excluded after build failures
    • isShutdown

      boolean isShutdown()
      Whether the manager has been shut down.
      Returns:
      true if the manager has been shut down
    • getInboundBuildQueueSize

      public int getInboundBuildQueueSize()
      Size of the inbound build queue.
      Specified by:
      getInboundBuildQueueSize in interface TunnelManagerFacade
      Returns:
      current number of queued inbound builds
    • renderStatusHTML

      public void renderStatusHTML(Writer out) throws IOException
      Required by Service; status rendering moved to routerconsole.
      Specified by:
      renderStatusHTML in interface Service
      Parameters:
      out - the writer to write to
      Throws:
      IOException - if an error occurs writing
    • countTunnelsPerPeer

      private int countTunnelsPerPeer(ObjectCounterUnsafe<Hash> lc, boolean exploratory)
      Count tunnels and peers separately for exploratory or client pools.
      Parameters:
      lc - object counter to store peer counts
      exploratory - if true, count exploratory tunnels; if false, count client tunnels
      Returns:
      total number of tunnels counted
    • selectPeersInTooManyTunnels

      public Set<Hash> selectPeersInTooManyTunnels()
      For reliability reasons, don't allow a peer in more than x% of client and exploratory tunnels.

      This also will prevent a single huge-capacity (or malicious) peer from taking all the tunnels in the network (although it would be nice to limit the % of total network tunnels to 10% or so, but that appears to be too low to set as a default here... much lower than 33% will push client tunnels out of the fast tier into high cap or beyond...)

      Possible improvement - restrict based on count per IP, or IP block, to slightly increase costs of collusion.

      Specified by:
      selectPeersInTooManyTunnels in interface TunnelManagerFacade
      Returns:
      Set of peers that should not be allowed in another tunnel
    • participationRelief

      static double participationRelief(boolean firewalled, double buildSuccess, boolean incompleteLeaseSet)
      The relief factor actually applied to the participation share, combining the three inputs. Pure, so the precedence between them is testable without a router.

      Firewalled and incomplete-LeaseSet are both hard signals that the first hop pool is too narrow, and either one takes full relief regardless of what aggregate build success says. Build success is the weakest signal and only applies when neither of the others fires.

      Parameters:
      firewalled - whether the router is firewalled
      buildSuccess - build success ratio, or 1.0 when unknown
      incompleteLeaseSet - whether a pool published an incomplete LeaseSet recently
      Returns:
      the multiplier to apply
    • buildSuccessRelief

      static double buildSuccessRelief(double buildSuccess)
      Graded relief factor for the per-peer participation share, from tunnel build success. Pure: no state, no clock, no logging.

      Returns 1.0 (no relief) at or above SHARE_RELIEF_TOP and 2.0 (the pre-existing full relief) at or below SHARE_RELIEF_BOTTOM, interpolating linearly between. A build success of 1.0 is passed in when no data exists yet, which yields no relief and so leaves the startup thresholds to govern.

      Parameters:
      buildSuccess - build success ratio in [0,1], or 1.0 when unknown
      Returns:
      the multiplier to apply to the participation share percentage
    • participationShareLimit

      static int participationShareLimit(int basePct, double relief)
      Apply a relief factor to a participation share percentage, never returning less than the un-relieved base.
      Parameters:
      basePct - the un-relieved percentage
      relief - the multiplier from buildSuccessRelief(double)
      Returns:
      the percentage to compare peer shares against
    • exceedsShareLimit

      static boolean exceedsShareLimit(int count, int total, int maxPct)
      Whether a peer's share of tunnel participation exceeds the limit. Pure.

      The +1 on both numerator and denominator is the historical form. It equals the unsmoothed integer share exactly whenever the total is at least ten times the count, and inflates it for smaller pools (a peer alone in a pool of two reads 66, not 50). It is reproduced here rather than tidied because changing it would change which peers are excluded. Integer division truncates, so the comparison is against the truncated percentage -- callers relying on an exact boundary must respect that.

      Parameters:
      count - tunnels this peer participates in
      total - tunnels across all peers in this class
      maxPct - the limit returned by participationShareLimit(int, double)
      Returns:
      whether the peer should be excluded
    • noteIncompleteLeaseSet

      void noteIncompleteLeaseSet(long now)
      Note that some pool published an incomplete LeaseSet, which is a direct signal that first-hop supply is too narrow to fill one.
      Parameters:
      now - current time in ms
    • hasRecentIncompleteLeaseSet

      boolean hasRecentIncompleteLeaseSet(long now)
      Whether an incomplete-LeaseSet observation is recent enough to still justify relaxing the participation share. Decays on its own, so it cannot be left stuck on by a pool that was destroyed mid-renewal.
      Parameters:
      now - current time in ms
      Returns:
      whether relief applies
    • logShareLimit

      private void logShareLimit(long now, int basePct, int max, double buildSuccess, boolean firewalled, boolean incompleteLeaseSet, int excluded)
      Rate-limited log of the participation share limit actually in force, so a surprising exclusion count can be read against the reason for it instead of guessed at.
      Parameters:
      now - the current time in ms, for the log rate limit
      basePct - the base participation share, percent
      max - the effective share limit after adjustments, percent
      buildSuccess - the tunnel build success fraction, 0 to 1
      firewalled - whether the router is firewalled
      incompleteLeaseSet - whether a recent incomplete lease set relaxed the share
      excluded - the number of peers excluded from selection
    • isFirewalled

      public boolean isFirewalled()
      Report whether the router is firewalled on either address family.
      Returns:
      true if the router is firewalled
    • getInboundClientPools

      public Map<Hash, TunnelPool> getInboundClientPools()
      For TunnelRenderer in router console.
      Specified by:
      getInboundClientPools in interface TunnelManagerFacade
      Returns:
      snapshot of the inbound pools, keyed by destination hash
    • getOutboundClientPools

      public Map<Hash, TunnelPool> getOutboundClientPools()
      For TunnelRenderer in router console.
      Specified by:
      getOutboundClientPools in interface TunnelManagerFacade
      Returns:
      snapshot of the outbound pools, keyed by destination hash
    • getInboundExploratoryPool

      public TunnelPool getInboundExploratoryPool()
      For TunnelRenderer in router console.
      Specified by:
      getInboundExploratoryPool in interface TunnelManagerFacade
      Returns:
      the inbound exploratory pool, never null
    • getOutboundExploratoryPool

      public TunnelPool getOutboundExploratoryPool()
      For TunnelRenderer in router console.
      Specified by:
      getOutboundExploratoryPool in interface TunnelManagerFacade
      Returns:
      the outbound exploratory pool, never null
    • getInboundPool

      public TunnelPool getInboundPool(Hash client)
      The client's inbound pool, creating it if needed.
      Specified by:
      getInboundPool in interface TunnelManagerFacade
      Parameters:
      client - hash of the destination that owns the pool
      Returns:
      pool or null
    • getOutboundPool

      public TunnelPool getOutboundPool(Hash client)
      The client's outbound pool, creating it if needed.
      Specified by:
      getOutboundPool in interface TunnelManagerFacade
      Parameters:
      client - hash of the destination that owns the pool
      Returns:
      pool or null
    • ensurePoolsFor

      public int ensurePoolsFor(Hash client)
      Nudge both of a local client's pools to run their ensure logic. Throttled inside each pool, so failure floods stay cheap.
      Specified by:
      ensurePoolsFor in interface TunnelManagerFacade
      Parameters:
      client - the LOCAL client hash (the pool-map key)
      Returns:
      how many pools were nudged; 0 when none are registered
    • checkAndRecoverPools

      public int checkAndRecoverPools()
      Emergency pool recovery: Check all registered clients have valid tunnel pools. Recreates missing pools to prevent service interruption. Called periodically by BuildExecutor.
      Returns:
      number of pools recovered
    • logPoolHealth

      public void logPoolHealth()
      Log pool health summary for monitoring.
    • fail

      public void fail(Hash peer)
      Fail all outbound tunnels with this peer as first hop, and all inbound tunnels with this peer as the last hop, because we can't contact it any more. This is most likely to be triggered by an outbound tunnel.
      Specified by:
      fail in interface TunnelManagerFacade
      Parameters:
      peer - hash of the unreachable peer
    • failTunnelsWithFirstHop

      private void failTunnelsWithFirstHop(TunnelPool pool, Hash peer)
      Fail all (outbound) tunnels with this peer as first hop (not counting us).
      Parameters:
      pool - the pool whose tunnels are scanned
      peer - the banlisted peer looked for at the first hop
    • failTunnelsWithLastHop

      private void failTunnelsWithLastHop(TunnelPool pool, Hash peer)
      Fail all (inbound) tunnels with this peer as last hop (not counting us).
      Parameters:
      pool - the pool whose tunnels are scanned
      peer - the banlisted peer looked for at the last hop
    • noPoolLine

      static String noPoolLine(boolean inbound, Hash destination)
      The entry for a destination with no client pool of the given direction, so a null return from the selector carries a reason in the log.
      Parameters:
      inbound - true to name an inbound pool, false for an outbound one
      destination - the destination whose pool is missing
      Returns:
      the log entry, never null