- All Implemented Interfaces:
RouterClock.ClockShiftListener
For embedded use, instantiate, call setKillVMOnEnd(false), and then call runRouter().
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate classLogs the UPnP scan and port mapping results.private static enumState management - startup / shutdown states.Field Summary
Modifier and TypeFieldDescriptionprivate BandwidthHistoryHistory of our bandwidth over time.private doubleCached share of tunnels offered to clients.private StringConfig string the cached share percentage was parsed from.The router's config properties.private final ObjectLock guarding writes to router.config.private StringFull path to the config file.private final RouterContextThe router context.private longHow long the router was down before this run.private final EventLogLog of events shown on the notifications page.private FamilyKeyCryptoSigner for our router family, if configured.private booleanWhether loading the family key failed.final ObjectLock protecting the family key crypto.private intExit code set before a graceful shutdown.private I2PThreadThread watching for a shutdown request.private ObjectLock for the shutdown request flag.private booleanWhether shutdown exits the JVM.private charThe congestion cap last logged, to skip repeat warnings.private LogLogger for the router.private MarkLivelinessThread touching the watchdog timestamp.private final intThe network id we communicate on.private I2PThread.OOMEventListenerListener notified on out-of-memory errors.private static final String[]Ugly list of files that we need to kill if we are building a new identity.private HashHash of our router identity.private RouterIdentityOur router identity.private RouterInfoOur router info, null until we have one.private final ReentrantReadWriteLockLock guarding the router info.private ShutdownHookHook run when the JVM exits.private longWhen the router was started.private Router.StateCurrent state of the router.private final ObjectLock guarding the router state.private UPnPScannerCallbackCallback logging the UPnP scan results.private RouterWatchdogWatchdog that restarts a hung router.private ThreadThread running the watchdog.private static final booleanDisable dynamic key functionality for the moment, as it may be harmful and doesn't add meaningful anonymity.private static final StringBundle holding the translated console strings.static final charBandwidth class capability for unlimited bandwidth.static final charBandwidth class capability for 12 KB/s, publicizing our ballpark capacity.static final charBandwidth class capability for 128 KB/s.static final charBandwidth class capability for 256 KB/s.static final charBandwidth class capability for 32 KB/s.static final charBandwidth class capability for 512 KB/s.static final charBandwidth class capability for 64 KB/s.static final charCongestion capability: the peer reports moderate, sustained congestion (proposal 162, alongsideCAPABILITY_CONGESTION_SEVEREandCAPABILITY_NO_TUNNELS).static final charCongestion capability: the peer reports severe congestion, at the level where it should stop being selected for new tunnels.static final charCongestion capability: the peer reports that it is up but cannot build tunnels, so it can still serve existing ones.static final charReachability capability.static final charUnreachability capability.static final longLet clocks be off by 30 seconds (reduced from 60s to improve lease renewal timing).static final intCoalesce stats this often - should be a little less than one minute, so the graphs get updated.private static final booleanWhether congestion capability letters are published.private static final intUsed to differentiate routerInfo files on different networks.static final intDefault share, as a percentage of the configured bandwidth limits.private static final StringFile name for the event log.static final intShut down after all tunnels are gone.static final intShut down after all tunnels are gone, and tell the wrapper to restart.static final intShut down immediately.static final intShut down immediately, and tell the wrapper to restart.static final intShut down immediately.private static final longInterval between watchdog liveliness touches, one minute.static final intIn binary (1024) Kbytes.static final intIn binary (1024) Kbytes.static final intIn binary (1024) Kbytes.static final intIn binary (1024) Kbytes.static final intIn binary (1024) Kbytes.static final intIn binary (1024) Kbytes.static final intIn binary (1024) Kbytes.private static final StringTimezone the router started with, restored on shutdown.private static final StringConfig key for the console's advanced mode.static final StringProperty naming the share of our bandwidth that tunnels may consume.static final StringConfig property for the router config file location.static final StringNew router keys at every restart.static final StringFor testing.static final StringFor testing.static final StringThis puts an 'H' in your routerInfo *.static final StringThis does not put an 'H' in your routerInfo *.static final StringConfig property for the inbound exploratory pool random key.private static final StringConfig key recording the loaded jbigi resource.private static final StringConfig key recording the processor the jbigi was chosen for.private static final StringConfig key for the network id.static final StringConfig property for the outbound exploratory pool random key.static final StringNew router keys once only.private static final StringConfig key relaxing the congestion cap rules.private static final StringDeprecated, usegracefulShutdownInProgress().final ObjectNot for external use.private static final intSeconds allowed for a graceful shutdown.private static final Set<Router.State> For efficiency.private static final Set<Router.State> States counted as the final shutdown.private static final Set<Router.State> States counted as a graceful shutdown.static final StringThe update zip file name.Constructor Summary
ConstructorsConstructorDescriptionRouter()Instantiation only.Instantiation only.Router(String configFilename, Properties envProps) Instantiation only.Router(Properties envProps) Instantiation only.Method Summary
Modifier and TypeMethodDescriptionprivate voidStart a thread that will periodically update the file "router.ping".voidCancel any prior request to shut the router down gracefully.private voidchangeState(Router.State state) Advance the router state machine, starting or stopping components as needed.static final voidNot for external use.voidclockShift(long delta) The clock shift listener.eventLog()The router's event log, shared with the console pages that render it.private voidfinalShutdown(int exitCode) Cancel the JVM runtime hook before calling this.intMax of inbound and outbound rate in bytes per second.intget15sRate(boolean outboundOnly) When outboundOnly is false, outbound rate in bytes per second.intInbound rate in bytes per second.intMax of inbound and outbound rate in bytes per second.intget1mRate(boolean outboundOnly) When outboundOnly is false, outbound rate in bytes per second.intInbound rate in bytes per second.intMax of inbound and outbound rate in bytes per second.intget1sRate(boolean outboundOnly) When outboundOnly is false, outbound rate in bytes per second.intInbound rate in bytes per second.charThe current bandwidth class.For building our RI.private static PropertiesgetConfig(RouterContext ctx, String filename) This does not use ctx.getConfigDir(), must provide a full path in filename Caller must synchronize.The absolute path to the router configuration file.An unmodifiable map of all configuration settings.getConfigSetting(String name) Retrieve a configuration setting by name.An unmodifiable set of all configuration property names.Non-null, but take care when accessing context items before runRouter() is called as the context will not be initialized.longHow long this router was down before it started, or 0 if unknown.Family Key Crypto Signer / Verifier.booleanCheck whether the router is configured to kill the JVM on shutdown.intThe network ID.private FileReturns the file recording when the router last ran.Our current router hash.Our current router identity.Our current router info.doubleWhat fraction of the bandwidth specified in our bandwidth limits should we allow to be consumed by participating tunnels?longHow long until the graceful shutdown will kill us?For Android only.longWall clock uptime.longUsed only by routerconsole..booleanIs a graceful shutdown in progress? This may be cancelled.booleanWhether advanced mode is enabled.booleanisAlive()Check if the router is alive (in startup or running state).booleanIs a final shutdown in progress? This may not be cancelled.booleanisHidden()Whether the router is hidden.private booleanCheck the file "router.ping", but if that file already exists and was recently written to, return false as there is another instance running.booleanWhether the router is RESTARTING (soft restart).booleanWhether the router is RUNNING, i.e.voidkillKeys()Not for external use.private voidlocked_rebuildRouterInfo(List<RouterAddress> addresses) Rebuild and republish our routerInfo since something significant has changed.static voidUsage: Router [rebuild] No other options allowed, for now Instantiates Router(), and either installs updates and exits, or calls runRouter().voidThis updates the config with all settings found in the file.voidRebuild a new identity the hard way - delete all of our old identity files, then reboot the router.voidRebuild and republish our routerInfo since something significant has changed.voidrebuildRouterInfo(boolean blockingRebuild) Rebuild and republish our routerInfo since something significant has changed.voidrestart()A "soft" restart, primarily of the comm system, after a port change or large step-change in system time.voidThis must be called after instantiation.booleanSave the current config options (returning true if save was successful, false otherwise)booleansaveConfig(String name, String value) Updates the current config with the given key/value and then saves it.booleansaveConfig(Map toAdd, Collection<String> toRemove) Updates the current config and then saves it.intWhat exit code do we plan on using when we shut down (or -1, if there isn't a graceful shutdown planned).voidsetEstimatedDowntime(long downtime) Only for soft restart.voidOnly for Tunnel Building, after we have non-zero-hop expl.voidOnly for Restarter, after soft restart is complete.voidsetKillVMOnEnd(boolean shouldDie) Configure the router to kill the JVM when the router shuts down, as well as whether to explicitly halt the JVM during the hard fail process.voidOnly for NetDB, after RIs are loaded.voidsetRouterInfo(RouterInfo info) Caller must ensure info is valid - no validation done here.voidsetUPnPScannerCallback(UPnPScannerCallback callback) For Android only.voidshutdown(int exitCode) Shutdown with no chance of cancellation.voidshutdown2(int exitCode) Cancel the JVM runtime hook before calling this.voidNon-blocking shutdown.voidshutdownGracefully(int exitCode) Non-blocking shutdown.private voidshutdownOne(String name, boolean debug, boolean advanced, Runnable task) Shut down a single subsystem, with error logging appropriate to verbosity.private voidShut down all router subsystems.private static voidstartupLog(String msg) Writes a startup line to stderr, before the log system exists.private voidInitializes the RouterContext.private voidCould block for 10 seconds or forever.
Field Details
_log
Logger for the router._context
The router context._config
_configFilename
Full path to the config file._routerInfo
Our router info, null until we have one._routerInfoLock
Lock guarding the router info._routerIdent
Our router identity._routerHash
Hash of our router identity.routerInfoFileLock
Not for external use._configFileLock
Lock guarding writes to router.config._started
private long _startedWhen the router was started._killVMOnEnd
private volatile boolean _killVMOnEndWhether shutdown exits the JVM._gracefulExitCode
private int _gracefulExitCodeExit code set before a graceful shutdown._oomListener
Listener notified on out-of-memory errors._shutdownHook
Hook run when the JVM exits._gracefulShutdownDetector
Thread watching for a shutdown request._gracefulShutdownLock
Lock for the shutdown request flag._watchdog
Watchdog that restarts a hung router._watchdogThread
Thread running the watchdog._markLiveliness
Thread touching the watchdog timestamp._eventLog
Log of events shown on the notifications page._stateLock
Lock guarding the router state._state
Current state of the router._familyKeyCrypto
Signer for our router family, if configured._familyKeyCryptoFail
private boolean _familyKeyCryptoFailWhether loading the family key failed._familyKeyLock
Lock protecting the family key crypto._upnpScannerCallback
Callback logging the UPnP scan results._downtime
private long _downtimeHow long the router was down before this run._lastCongestionCap
private char _lastCongestionCapThe congestion cap last logged, to skip repeat warnings._bandwidthHistory
History of our bandwidth over time.BUNDLE_NAME
Bundle holding the translated console strings.- See Also:
PROP_CONFIG_FILE
Config property for the router config file location.- See Also:
CLOCK_FUDGE_FACTOR
public static final long CLOCK_FUDGE_FACTORLet clocks be off by 30 seconds (reduced from 60s to improve lease renewal timing).- See Also:
DEFAULT_NETWORK_ID
private static final int DEFAULT_NETWORK_IDUsed to differentiate routerInfo files on different networks.- See Also:
PROP_NETWORK_ID
Config key for the network id.- See Also:
_networkID
private final int _networkIDThe network id we communicate on.COALESCE_TIME
public static final int COALESCE_TIMECoalesce stats this often - should be a little less than one minute, so the graphs get updated.- See Also:
PROP_HIDDEN
This puts an 'H' in your routerInfo *.- See Also:
PROP_HIDDEN_HIDDEN
This does not put an 'H' in your routerInfo *.- See Also:
PROP_DYNAMIC_KEYS
New router keys at every restart. Disabled.- See Also:
PROP_REBUILD_KEYS
New router keys once only.- See Also:
PROP_SHUTDOWN_IN_PROGRESS
Deprecated, usegracefulShutdownInProgress().- See Also:
PROP_IB_RANDOM_KEY
Config property for the inbound exploratory pool random key.- See Also:
PROP_OB_RANDOM_KEY
Config property for the outbound exploratory pool random key.- See Also:
EVENTLOG
PROP_JBIGI
Config key recording the loaded jbigi resource.- See Also:
PROP_JBIGI_PROCESSOR
Config key recording the processor the jbigi was chosen for.- See Also:
UPDATE_FILE
CONGESTION_CAPS
private static final boolean CONGESTION_CAPSWhether congestion capability letters are published.- See Also:
SHUTDOWN_WAIT_SECS
private static final int SHUTDOWN_WAIT_SECSSeconds allowed for a graceful shutdown.- See Also:
PROP_ADVANCED
Config key for the console's advanced mode.- See Also:
PROP_RELAX_CONGESTION_CAP
Config key relaxing the congestion cap rules.- See Also:
ORIGINAL_TIMEZONE_ID
Timezone the router started with, restored on shutdown.STATES_ALIVE
For efficiency. EnumSets are bitmasks.STATES_GRACEFUL
States counted as a graceful shutdown.STATES_FINAL
States counted as the final shutdown.CAPABILITY_BW12
public static final char CAPABILITY_BW12Bandwidth class capability for 12 KB/s, publicizing our ballpark capacity.- See Also:
CAPABILITY_BW32
public static final char CAPABILITY_BW32Bandwidth class capability for 32 KB/s.- See Also:
CAPABILITY_BW64
public static final char CAPABILITY_BW64Bandwidth class capability for 64 KB/s.- See Also:
CAPABILITY_BW128
public static final char CAPABILITY_BW128Bandwidth class capability for 128 KB/s.- See Also:
CAPABILITY_BW256
public static final char CAPABILITY_BW256Bandwidth class capability for 256 KB/s.- See Also:
CAPABILITY_BW512
public static final char CAPABILITY_BW512Bandwidth class capability for 512 KB/s.- See Also:
CAPABILITY_BW_UNLIMITED
public static final char CAPABILITY_BW_UNLIMITEDBandwidth class capability for unlimited bandwidth.- See Also:
PROP_FORCE_BWCLASS
CAPABILITY_REACHABLE
CAPABILITY_UNREACHABLE
public static final char CAPABILITY_UNREACHABLEUnreachability capability.- See Also:
CAPABILITY_CONGESTION_MODERATE
public static final char CAPABILITY_CONGESTION_MODERATECongestion capability: the peer reports moderate, sustained congestion (proposal 162, alongsideCAPABILITY_CONGESTION_SEVEREandCAPABILITY_NO_TUNNELS).- See Also:
CAPABILITY_CONGESTION_SEVERE
public static final char CAPABILITY_CONGESTION_SEVERECongestion capability: the peer reports severe congestion, at the level where it should stop being selected for new tunnels.- See Also:
CAPABILITY_NO_TUNNELS
public static final char CAPABILITY_NO_TUNNELSCongestion capability: the peer reports that it is up but cannot build tunnels, so it can still serve existing ones.- See Also:
PROP_FORCE_UNREACHABLE
MIN_BW_K
MIN_BW_L
MIN_BW_M
MIN_BW_N
MIN_BW_O
MIN_BW_P
MIN_BW_X
_rebuildFiles
Ugly list of files that we need to kill if we are building a new identity.EXIT_GRACEFUL
public static final int EXIT_GRACEFULShut down after all tunnels are gone.- See Also:
EXIT_HARD
EXIT_OOM
EXIT_HARD_RESTART
public static final int EXIT_HARD_RESTARTShut down immediately, and tell the wrapper to restart.- See Also:
EXIT_GRACEFUL_RESTART
public static final int EXIT_GRACEFUL_RESTARTShut down after all tunnels are gone, and tell the wrapper to restart.- See Also:
ALLOW_DYNAMIC_KEYS
private static final boolean ALLOW_DYNAMIC_KEYSDisable dynamic key functionality for the moment, as it may be harmful and doesn't add meaningful anonymity.- See Also:
LIVELINESS_DELAY
private static final long LIVELINESS_DELAYInterval between watchdog liveliness touches, one minute.- See Also:
PROP_BANDWIDTH_SHARE_PERCENTAGE
Property naming the share of our bandwidth that tunnels may consume.- See Also:
DEFAULT_SHARE_PERCENTAGE
public static final int DEFAULT_SHARE_PERCENTAGEDefault share, as a percentage of the configured bandwidth limits.- See Also:
Constructor Details
Router
public Router()Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.Config file name is "
router.config" unlessrouter.configLocationset in system properties.See two-arg constructor for more information.
- Throws:
IllegalStateException- since 0.9.19 if another router with this config is running
Router
Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.Config file name is "
router.config" unlessrouter.configLocationset in envProps or system properties.See two-arg constructor for more information.
- Parameters:
envProps- may be null- Throws:
IllegalStateException- since 0.9.19 if another router with this config is running
Router
Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.See two-arg constructor for more information.
- Parameters:
configFilename- may be null- Throws:
IllegalStateException- since 0.9.19 if another router with this config is running
Router
Instantiation only. Starts no threads. Does not install updates. RouterContext is created but not initialized. You must call runRouter() after any constructor to start things up.If configFilename is non-null, configuration is read in from there. Else if envProps is non-null, configuration is read in from the location given in the
router.configLocationproperty. Else it's read in from the System propertyrouter.configLocation. Else from the file "router.config".The most important properties are
i2p.dir.base(the install directory, may be read-only) andi2p.dir.config(the user's configuration/data directory).i2p.dir.basedefaults to user.dir (CWD) but should almost always be set.i2p.dir.configdefault depends on OS, user name (to detect if running as a service or not), and auto-detection of whether there appears to be previous data files in the base dir. See WorkingDir for details. If the config dir does not exist, it will be created, and files migrated from the base dir, in this constructor. If files in an existing config dir indicate that another router is already running with this directory, the constructor will delay for several seconds to be sure, and then throw an IllegalStateException.- Parameters:
configFilename- may be nullenvProps- may be null- Throws:
IllegalStateException- since 0.9.19 if another router with this config is running
Method Details
isAdvanced
public boolean isAdvanced()Whether advanced mode is enabled.- Returns:
- true if advanced mode is enabled
startupStuff
private void startupStuff()Initializes the RouterContext. Starts some threads. Does not install updates. All this was in the constructor.Could block for 10 seconds or forever if waiting for entropy.
clearCaches
public static final void clearCaches()Not for external use.setKillVMOnEnd
public void setKillVMOnEnd(boolean shouldDie) Configure the router to kill the JVM when the router shuts down, as well as whether to explicitly halt the JVM during the hard fail process.Defaults to true. Set to false for embedded before calling runRouter().
- Parameters:
shouldDie- true to kill VM on shutdown, false for embedded use
getKillVMOnEnd
public boolean getKillVMOnEnd()Check whether the router is configured to kill the JVM on shutdown.- Returns:
- true if VM will be killed on router shutdown
getConfigFilename
The absolute path to the router configuration file.- Returns:
- absolute path to the configuration file
getConfigSetting
getConfigSettings
An unmodifiable set of all configuration property names.Warning: this is a live view of the configuration - use
saveConfig()orsaveConfig(String, String)when you modify the returned set, otherwise the router may race with a concurrent write.- Returns:
- unmodifiable Set of configuration property names (unsorted)
getConfigMap
getRouterInfo
Our current router info. Warning, may be null if called very early.Warning - risk of deadlock - do not call while holding locks
Note: Due to lock contention, especially during a rebuild of the router info, this may take a long time. For determining the current status of the router, use
RouterContext.commSystem()getStatus().- Returns:
- the router info
getRouterIdentity
Our current router identity. Warning, may be null if called very early. Lockless.- Returns:
- the router identity
getRouterHash
Our current router hash. Warning, may be null if called very early. Lockless.- Returns:
- the router hash
setRouterInfo
Caller must ensure info is valid - no validation done here. Not for external use.Warning - risk of deadlock - do not call while holding locks.
- Parameters:
info- the router info to adopt as ours; the caller must ensure it is valid
getWhenStarted
public long getWhenStarted()Used only by routerconsole.. to be deprecated?- Returns:
- System time, NOT context time
getUptime
public long getUptime()Wall clock uptime. This uses System time, NOT context time, so context clock shifts will not affect it. This is important if NTP fails and the clock then shifts from a SSU peer source just after startup.- Returns:
- the uptime in milliseconds since the router started
getNetworkID
public int getNetworkID()The network ID. Default 2. May be changed with the config propertyrouter.networkID(restart required). Change only if running a test network to prevent cross-network contamination.- Returns:
- 2 - 254
getContext
Non-null, but take care when accessing context items before runRouter() is called as the context will not be initialized.- Returns:
- non-null
setUPnPScannerCallback
For Android only. MUST be set before runRouter() is called.- Parameters:
callback- the callback or null to clear it
getUPnPScannerCallback
For Android only.- Returns:
- the callback or null if none
runRouter
public void runRouter()This must be called after instantiation. Starts the threads. Does not install updates. This is for embedded use. Standard standalone installation usesmain(String[])instead, which checks for updates and then calls this.This may take quite a while, especially if NTP fails or the system lacks entropy.
- Throws:
IllegalStateException- if called more than once
readConfig
public void readConfig()This updates the config with all settings found in the file. It does not clear the config first, so settings not found in the file will remain in the config.This is synchronized with
saveConfig(). Not for external use.getConfig
This does not use ctx.getConfigDir(), must provide a full path in filename Caller must synchronize.- Parameters:
ctx- will be null at startup when called from constructorfilename- full path of the config file to read- Returns:
- the settings read from that file, empty if the file does not exist
changeState
Advance the router state machine, starting or stopping components as needed.- Parameters:
state- the new state to advance to
isAlive
public boolean isAlive()Check if the router is alive (in startup or running state). True during initial startup, false during soft restart.- Returns:
- true if router is in an alive state
isRunning
public boolean isRunning()Whether the router is RUNNING, i.e. NetDB and expl. tunnels are ready.- Returns:
- true if router is RUNNING, i.e NetDB and Expl. tunnels are ready.
isRestarting
public boolean isRestarting()Whether the router is RESTARTING (soft restart).- Returns:
- true if router is RESTARTING (soft restart)
setIsAlive
public void setIsAlive()Only for Restarter, after soft restart is complete. Not for external use.setNetDbReady
public void setNetDbReady()Only for NetDB, after RIs are loaded. Not for external use.setExplTunnelsReady
public void setExplTunnelsReady()Only for Tunnel Building, after we have non-zero-hop expl. tunnels. Not for external use.gracefulShutdownInProgress
public boolean gracefulShutdownInProgress()Is a graceful shutdown in progress? This may be cancelled. Note that this also returns true if an uncancellable final shutdown is in progress.- Returns:
- true while a graceful or final shutdown is running
isFinalShutdownInProgress
public boolean isFinalShutdownInProgress()Is a final shutdown in progress? This may not be cancelled.- Returns:
- whether final shutdown in progress
rebuildRouterInfo
public void rebuildRouterInfo()Rebuild and republish our routerInfo since something significant has changed. This is a non-blocking rebuild.Not for external use.
Warning - risk of deadlock - do not call while holding locks.
rebuildRouterInfo
public void rebuildRouterInfo(boolean blockingRebuild) Rebuild and republish our routerInfo since something significant has changed. Not for external use.Warning - risk of deadlock - do not call while holding locks.
- Parameters:
blockingRebuild- ignored, operation is always nonblocking
locked_rebuildRouterInfo
Rebuild and republish our routerInfo since something significant has changed.- Parameters:
addresses- the current router addresses to publish
getFamilyKeyCrypto
Family Key Crypto Signer / Verifier. Not for external use. If family key is set, first call Will take a while to generate keys. Warning - risk of deadlock - do not call while holding locks (other than routerInfoLock).- Returns:
- null on initialization failure
getBandwidthClass
public char getBandwidthClass()The current bandwidth class. For building our RI. Not for external use.- Returns:
- a character to be added to the RI, one of "KLMNOPX"
getCapabilities
For building our RI. Not for external use.- Returns:
- a capabilities string to be added to the RI
isHidden
public boolean isHidden()Whether the router is hidden. This checks the config only. We don't check the current RI due to deadlocks.- Returns:
- true if the router is hidden
eventLog
The router's event log, shared with the console pages that render it.- Returns:
- the router's event log, which the console pages render
killKeys
public void killKeys()Not for external use.rebuildNewIdentity
public void rebuildNewIdentity()Rebuild a new identity the hard way - delete all of our old identity files, then reboot the router.Calls exit(), never returns.
Not for external use.
warmupCrypto
private void warmupCrypto()Could block for 10 seconds or forever.shutdown
public void shutdown(int exitCode) Shutdown with no chance of cancellation. Blocking, will call exit() and not return unless setKillVMOnExit(false) was previously called, or a final shutdown is already in progress. May take several seconds as it runs all the shutdown hooks.- Parameters:
exitCode- one of the EXIT_* values, non-negative- Throws:
IllegalArgumentException- if exitCode negative
shutdown2
public void shutdown2(int exitCode) Cancel the JVM runtime hook before calling this. Called by the ShutdownHook. NOT to be called by others, use shutdown().- Parameters:
exitCode- one of the EXIT_* values, non-negative- Throws:
IllegalArgumentException- if exitCode negative
shutdownSubsystems
private void shutdownSubsystems()Shut down all router subsystems. Error handling level depends on log verbosity: debug → full stack trace, advanced → message only, else → silent.shutdownOne
Shut down a single subsystem, with error logging appropriate to verbosity.- Parameters:
name- subsystem name for loggingdebug- if true, log full stack trace on erroradvanced- if true, log message-only on errortask- the shutdown operation
finalShutdown
private void finalShutdown(int exitCode) Cancel the JVM runtime hook before calling this.- Parameters:
exitCode- one of the EXIT_* values, non-negative
shutdownGracefully
public void shutdownGracefully()Non-blocking shutdown.Call this if we want the router to kill itself as soon as we aren't participating in any more tunnels (etc). This will not block and doesn't guarantee any particular time frame for shutting down. To shut the router down immediately, use
shutdown(int). If you want to cancel the graceful shutdown (prior to actual shutdown ;), callcancelGracefulShutdown().Exit code will be EXIT_GRACEFUL.
Shutdown delay will be from zero to 11 minutes.
shutdownGracefully
public void shutdownGracefully(int exitCode) Non-blocking shutdown.Call this with EXIT_HARD or EXIT_HARD_RESTART for a non-blocking, hard, non-graceful shutdown with a brief delay to allow a UI response
Returns silently if a final shutdown is already in progress.
- Parameters:
exitCode- one of the EXIT_* values, non-negative- Throws:
IllegalArgumentException- if exitCode negative
cancelGracefulShutdown
public void cancelGracefulShutdown()Cancel any prior request to shut the router down gracefully.Returns silently if a final shutdown is already in progress.
scheduledGracefulExitCode
public int scheduledGracefulExitCode()What exit code do we plan on using when we shut down (or -1, if there isn't a graceful shutdown planned).- Returns:
- one of the EXIT_* values or -1
getShutdownTimeRemaining
public long getShutdownTimeRemaining()How long until the graceful shutdown will kill us?- Returns:
- -1 if no shutdown in progress.
saveConfig
public boolean saveConfig()Save the current config options (returning true if save was successful, false otherwise)Synchronized with file read in
getConfig(RouterContext, String).- Returns:
- true if the properties were written, false if the write failed
saveConfig
Updates the current config with the given key/value and then saves it. Prevents a race in the interval between _config.put()/_config.remove() and saveConfig(), Synchronized with getConfig() / saveConfig().- Parameters:
name- setting to add/change/remove before savingvalue- if non-null, updated value; if null, setting will be removed- Returns:
- true if the config file was written
saveConfig
Updates the current config and then saves it. Prevents a race in the interval between _config.putAll()/_config.remove() and saveConfig(), Synchronized with getConfig() / saveConfig().- Parameters:
toAdd- settings to add/change before saving, may be null or emptytoRemove- settings to remove before saving, may be null or empty- Returns:
- true if the config file was written
clockShift
public void clockShift(long delta) The clock shift listener. Restart the router if we should.- Specified by:
clockShiftin interfaceRouterClock.ClockShiftListener- Parameters:
delta- The system clock and adjusted clock just changed by this much, in milliseconds (approximately)
restart
public void restart()A "soft" restart, primarily of the comm system, after a port change or large step-change in system time. Does not stop the whole JVM, so it is safe even in the absence of the wrapper. This is not a graceful restart - all peer connections are dropped immediately.As of 0.8.8, this returns immediately and does the actual restart in a separate thread. Poll
isAlive()if you need to know when the restart is complete.Not recommended for external use.
main
Usage: Router [rebuild] No other options allowed, for now Instantiates Router(), and either installs updates and exits, or calls runRouter().Not recommended for embedded use. Applications bundling I2P should instantiate a Router and call runRouter().
- Parameters:
args- null ok- Throws:
IllegalArgumentException- if an unrecognized option is given, or more than one argument is passed
getPingFile
startupLog
Writes a startup line to stderr, before the log system exists. The service wrapper prefixes its own level to every stderr line, so the message carries none.- Parameters:
msg- the line to write
isOnlyRouterRunning
private boolean isOnlyRouterRunning()Check the file "router.ping", but if that file already exists and was recently written to, return false as there is another instance running.- Returns:
- true if the router is the only one running
beginMarkingLiveliness
private void beginMarkingLiveliness()Start a thread that will periodically update the file "router.ping".isOnlyRouterRunning()MUST have been called previously.getEstimatedDowntime
public long getEstimatedDowntime()How long this router was down before it started, or 0 if unknown.This may be used for a determination of whether to regenerate keys, for example. We use the timestamp of the previous ping file left behind on crash, as set by isOnlyRouterRunning(), if present. Otherwise, the last STOPPED entry in the event log.
May take a while to run the first time, if it has to go through the event log. Once called, the result is cached.
- Returns:
- the estimated downtime
setEstimatedDowntime
public void setEstimatedDowntime(long downtime) Only for soft restart. Not for external use.- Parameters:
downtime- the expected downtime in milliseconds, clamped up to a minimum of 1
get1sRate
public int get1sRate()Max of inbound and outbound rate in bytes per second.- Returns:
- the 1s rate
get1sRate
public int get1sRate(boolean outboundOnly) When outboundOnly is false, outbound rate in bytes per second. When true, max of inbound and outbound rate in bytes per second.- Parameters:
outboundOnly- true to report just the outbound rate, false for the larger of the two- Returns:
- the 1s rate
get1sRateIn
public int get1sRateIn()Inbound rate in bytes per second.- Returns:
- the 1s rate in
get15sRate
public int get15sRate()Max of inbound and outbound rate in bytes per second.- Returns:
- the 15s rate
get15sRate
public int get15sRate(boolean outboundOnly) When outboundOnly is false, outbound rate in bytes per second. When true, max of inbound and outbound rate in bytes per second.- Parameters:
outboundOnly- true to report just the outbound rate, false for the larger of the two- Returns:
- the 15s rate
get15sRateIn
public int get15sRateIn()Inbound rate in bytes per second.- Returns:
- the 15s rate in
get1mRate
public int get1mRate()Max of inbound and outbound rate in bytes per second.- Returns:
- the 1m rate
get1mRate
public int get1mRate(boolean outboundOnly) When outboundOnly is false, outbound rate in bytes per second. When true, max of inbound and outbound rate in bytes per second.- Parameters:
outboundOnly- true to report just the outbound rate, false for the larger of the two- Returns:
- the 1m rate
get1mRateIn
public int get1mRateIn()Inbound rate in bytes per second.- Returns:
- the 1m rate in