net.i2p.router.tunnel.pool

## Class TunnelPool

- java.lang.Object
- - net.i2p.router.tunnel.pool.TunnelPool

- Direct Known Subclasses:
    AliasedTunnelPool

      public class TunnelPool
      extends Object

  A group of tunnels for the router or a particular client, in a single direction. Public only for TunnelRenderer in router console.

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected boolean` | `_alive`
    `protected RouterContext` | `_context`
    `protected Log` | `_log`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `TunnelPool(RouterContext ctx, TunnelPoolManager mgr, TunnelPoolSettings settings, TunnelPeerSelector sel)`

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `protected void` | `addTunnel(TunnelInfo info)` Add a tunnel to the pool.
    `(package private) void` | `buildComplete(PooledTunnelCreatorConfig cfg, BuildExecutor.Result result)` Remove from the _inprogress list and call addTunnel() if result is SUCCESS.
    `(package private) boolean` | `buildFallback()` This will build a fallback tunnel only if: - Exploratory pool: 0-hop fallback allowed - Client pool with allowZeroHop=true AND configured for 0 hops: 0-hop fallback allowed - Client pool configured for 1 hop: 1-hop fallback allowed - Otherwise: build multi-hop tunnel (enforce 2-hop minimum)
    `(package private) void` | `buildFinished(boolean isInbound)` Record that a tunnel build has completed for this pool.
    `(package private) void` | `buildStarted(boolean isInbound)` Record that a tunnel build has started for this pool.
    `(package private) boolean` | `canStartBuild(boolean isInbound)` Check if we can start a new tunnel build for the given direction.
    `(package private) void` | `cleanupDuplicatePeerTunnels()` Scan pool for tunnels with duplicate peer sequences and remove duplicates.
    `(package private) PooledTunnelCreatorConfig` | `configureNewTunnel()` This only sets the peers and creation/expiration times in the configuration.
    `(package private) int` | `countHowManyToBuild()` Gather the data to see how many tunnels to build, and then actually compute that value (delegated to the countHowManyToBuild function below)
    `int` | `getAvgBWPerTunnel()` Get the average bandwidth per tunnel in the pool.
    `(package private) int` | `getConcurrentInboundBuilds()` Get the current count of concurrent builds for inbound direction.
    `(package private) int` | `getConcurrentOutboundBuilds()` Get the current count of concurrent builds for outbound direction.
    `(package private) int` | `getConsecutiveBuildTimeouts()` Get the count of consecutive tunnel build timeouts.
    `int` | `getInProgressCount()` Get the count of tunnels currently being built for this pool.
    `long` | `getLifetimeProcessed()` Total lifetime processed bytes for this pool.
    `String` | `getRateName()` RateStat name for the bandwidth graph
    `TunnelPoolSettings` | `getSettings()`
    `int` | `getTotalQuantity()` Get the adjusted total quantity of tunnels we want for this pool.
    `TunnelInfo` | `getTunnel(TunnelId gatewayId)` Get a tunnel by its gateway tunnel ID.
    `(package private) int` | `getTunnelCount()` duplicate of size(), let's pick one
    `boolean` | `isAlive()` 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.
    `List<PooledTunnelCreatorConfig>` | `listPending()` list of tunnelInfo instances of tunnels currently being built
    `List<TunnelInfo>` | `listTunnels()` Return a list of tunnels in the pool
    `protected LeaseSet` | `locked_buildNewLeaseSet()` Build a leaseSet with the required tunnels that aren't about to expire.
    `(package private) boolean` | `needFallback()` Do we really need more fallbacks? Used to prevent a zillion of them.
    `(package private) void` | `refreshLeaseSet()` noop for outbound and exploratory
    `(package private) void` | `removeTunnel(TunnelInfo info)` Remove a tunnel from the pool.
    `(package private) TunnelInfo` | `selectTunnel()` Pull a random tunnel out of the pool.
    `(package private) TunnelInfo` | `selectTunnel(Hash closestTo)` Return the tunnel from the pool that is XOR-closest to the target.
    `(package private) void` | `setSettings(TunnelPoolSettings settings)`
    `(package private) void` | `shutdown()` Shut down the pool and clean up resources.
    `int` | `size()` duplicate of getTunnelCount(), let's pick one
    `(package private) void` | `startup()` 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.
    `String` | `toString()`
    `(package private) void` | `triggerReplacementBuild()` Trigger an immediate replacement build for this pool.
    `(package private) void` | `tunnelFailed(TunnelInfo cfg)` Remove tunnel and blame all peers (not necessarily equally).
    `(package private) void` | `tunnelFailed(TunnelInfo cfg, Hash blamePeer)` Remove the tunnel and blame only one peer.

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

- - ### Field Detail

    - #### _alive

          protected volatile boolean _alive

    - #### _context

          protected final RouterContext _context

    - #### _log

          protected final Log _log

  - ### Constructor Detail

    - #### TunnelPool

          TunnelPool(RouterContext ctx,
                     TunnelPoolManager mgr,
                     TunnelPoolSettings settings,
                     TunnelPeerSelector sel)

  - ### Method Detail

    - #### addTunnel

          protected void addTunnel(TunnelInfo info)

      Add a tunnel to the pool.
      Parameters:
        `info` - the tunnel to add

    - #### buildComplete

          void buildComplete(PooledTunnelCreatorConfig cfg,
                             BuildExecutor.Result result)

      Remove from the _inprogress list and call addTunnel() if result is SUCCESS. Updates consecutive build timeout count.
      Parameters:
        `cfg` - the completed tunnel configuration
        `result` - the build result

    - #### buildFallback

          boolean buildFallback()

      This will build a fallback tunnel only if: - Exploratory pool: 0-hop fallback allowed - Client pool with allowZeroHop=true AND configured for 0 hops: 0-hop fallback allowed - Client pool configured for 1 hop: 1-hop fallback allowed - Otherwise: build multi-hop tunnel (enforce 2-hop minimum)
      Returns:
        true if a fallback tunnel is built, false otherwise

    - #### buildFinished

          void buildFinished(boolean isInbound)

      Record that a tunnel build has completed for this pool. Should be called when the build finishes (success or failure).
      Parameters:
        `isInbound` - true for inbound pool, false for outbound

    - #### buildStarted

          void buildStarted(boolean isInbound)

      Record that a tunnel build has started for this pool. Should be called when the build is actually sent to the network.
      Parameters:
        `isInbound` - true for inbound pool, false for outbound

    - #### canStartBuild

          boolean canStartBuild(boolean isInbound)

      Check if we can start a new tunnel build for the given direction. Limits concurrent builds per pool per direction to prevent overcompensation when builds are failing.
      Parameters:
        `isInbound` - true for inbound pool, false for outbound
      Returns:
        true if a new build can be started

    - #### cleanupDuplicatePeerTunnels

          void cleanupDuplicatePeerTunnels()

      Scan pool for tunnels with duplicate peer sequences and remove duplicates. Ensures at least one tunnel remains per pool (inbound/outbound separately). This handles existing duplicate tunnels that were in the pool before detection. Called periodically from countHowManyToBuild(). Skips cleanup during attacks since replacements are hard to build.

    - #### configureNewTunnel

          PooledTunnelCreatorConfig configureNewTunnel()

      This only sets the peers and creation/expiration times in the configuration. For the crypto, see BuildRequestor and BuildMessageGenerator.
      Returns:
        null on failure

    - #### countHowManyToBuild

          int countHowManyToBuild()

      Gather the data to see how many tunnels to build, and then actually compute that value (delegated to the countHowManyToBuild function below)
      Returns:
        the number of tunnels to build

    - #### getAvgBWPerTunnel

          public int getAvgBWPerTunnel()

      Get the average bandwidth per tunnel in the pool.
      Returns:
        average bandwidth per configured tunnel in Bps

    - #### getConcurrentInboundBuilds

          int getConcurrentInboundBuilds()

      Get the current count of concurrent builds for inbound direction.
      Returns:
        number of concurrent inbound builds

    - #### getConcurrentOutboundBuilds

          int getConcurrentOutboundBuilds()

      Get the current count of concurrent builds for outbound direction.
      Returns:
        number of concurrent outbound builds

    - #### getConsecutiveBuildTimeouts

          int getConsecutiveBuildTimeouts()

      Get the count of consecutive tunnel build timeouts.
      Returns:
        the number of consecutive build timeouts

    - #### getInProgressCount

          public int getInProgressCount()

      Get the count of tunnels currently being built for this pool.
      Returns:
        number of tunnels in progress

    - #### getLifetimeProcessed

          public long getLifetimeProcessed()

      Total lifetime processed bytes for this pool.
      Returns:
        the total number of bytes processed through this pool

    - #### getRateName

          public String getRateName()

      RateStat name for the bandwidth graph
      Returns:
        non-null

    - #### getSettings

          public TunnelPoolSettings getSettings()

    - #### getTotalQuantity

          public int getTotalQuantity()

      Get the adjusted total quantity of tunnels we want for this pool.
      Returns:
        the wanted number of tunnels

    - #### getTunnel

          public TunnelInfo getTunnel(TunnelId gatewayId)

      Get a tunnel by its gateway tunnel ID.
      Parameters:
        `gatewayId` - for inbound, the GW rcv tunnel ID; for outbound, the GW send tunnel ID.
      Returns:
        the tunnel with the matching gateway ID, or null if not found

    - #### getTunnelCount

          int getTunnelCount()

      duplicate of size(), let's pick one
      Returns:
        the number of tunnels in the pool

    - #### isAlive

          public boolean isAlive()

      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.
      Returns:
        true if the pool is alive and should be tracked

    - #### listPending

          public List<PooledTunnelCreatorConfig> listPending()

      list of tunnelInfo instances of tunnels currently being built
      Returns:
        the list of tunnels currently being built

    - #### listTunnels

          public List<TunnelInfo> listTunnels()

      Return a list of tunnels in the pool
      Returns:
        A copy of the list of TunnelInfo objects

    - #### locked_buildNewLeaseSet

          protected LeaseSet locked_buildNewLeaseSet()

      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.
      Returns:
        null on failure

    - #### needFallback

          boolean needFallback()

      Do we really need more fallbacks? Used to prevent a zillion of them. Does not check config, only call if config allows zero hop.
      Returns:
        true if more fallback tunnels are needed

    - #### refreshLeaseSet

          void refreshLeaseSet()

      noop for outbound and exploratory

    - #### removeTunnel

          void removeTunnel(TunnelInfo info)

      Remove a tunnel from the pool.
      Parameters:
        `info` - tunnel to remove

    - #### selectTunnel

          TunnelInfo selectTunnel()

      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.
      Returns:
        null on failure, but it should always build and return a fallback

    - #### selectTunnel

          TunnelInfo selectTunnel(Hash closestTo)

      Return the tunnel from the pool that is XOR-closest 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.
      Parameters:
        `closestTo` - the hash to find the closest tunnel to
      Returns:
        the tunnel closest to the target, or null on failure

    - #### setSettings

          void setSettings(TunnelPoolSettings settings)

    - #### shutdown

          void shutdown()

      Shut down the pool and clean up resources.

    - #### size

          public int size()

      duplicate of getTunnelCount(), let's pick one
      Returns:
        the number of tunnels in the pool

    - #### startup

          void startup()

      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)

    - #### toString

          public String toString()

      Overrides:
        `toString` in class `Object`

    - #### triggerReplacementBuild

          void triggerReplacementBuild()

      Trigger an immediate replacement build for this pool. Called when a tunnel is marked as last resort (only tunnel remaining). Wakes up the BuildExecutor to prioritize building a replacement.

    - #### tunnelFailed

          void tunnelFailed(TunnelInfo cfg)

      Remove tunnel and blame all peers (not necessarily equally). This may be called multiple times from TestJob. Enhanced with intelligent failure analysis and recovery.
      Parameters:
        `cfg` - the tunnel that failed

    - #### tunnelFailed

          void tunnelFailed(TunnelInfo cfg,
                            Hash blamePeer)

      Remove the tunnel and blame only one peer. This may be called multiple times.
      Parameters:
        `cfg` - the tunnel that failed
        `blamePeer` - the peer to blame