Changeset c0b9fe0


Ignore:
Timestamp:
Nov 29, 2011 3:25:40 PM (8 years ago)
Author:
zzz <zzz@…>
Branches:
master
Children:
9a2a515
Parents:
d3564df
Message:
  • Router: Refactor periodic tasks to their own files
Files:
8 added
2 edited
1 moved

Legend:

Unmodified
Added
Removed
  • apps/routerconsole/java/bundle-messages.sh

    rd3564df rc0b9fe0  
    4545ROUTERFILES="\
    4646   ../../../core/java/src/net/i2p/data/DataHelper.java \
    47    ../../../router/java/src/net/i2p/router/Router.java \
     47   ../../../router/java/src/net/i2p/router/tasks/CoalesceStatsEvent.java \
    4848   ../../../router/java/src/net/i2p/router/RouterThrottleImpl.java \
    4949   ../../../router/java/src/net/i2p/router/tunnel/pool/BuildHandler.java \
  • router/java/src/net/i2p/router/Router.java

    rd3564df rc0b9fe0  
    1616import java.io.IOException;
    1717import java.io.Writer;
    18 import java.text.DecimalFormat;
    19 import java.util.Calendar;
    2018import java.util.Collections;
    2119import java.util.Date;
    22 import java.util.GregorianCalendar;
    2320import java.util.HashSet;
    2421import java.util.Iterator;
     
    4441import net.i2p.router.startup.StartupJob;
    4542import net.i2p.router.startup.WorkingDir;
     43import net.i2p.router.tasks.*;
    4644import net.i2p.router.transport.FIFOBandwidthLimiter;
    4745import net.i2p.router.transport.udp.UDPTransport;
    48 import net.i2p.stat.Rate;
    4946import net.i2p.stat.RateStat;
    5047import net.i2p.stat.StatManager;
     
    5855import net.i2p.util.SimpleByteCache;
    5956import net.i2p.util.SimpleScheduler;
    60 import net.i2p.util.SimpleTimer;
    6157
    6258/**
     
    9591   
    9692    /** coalesce stats this often - should be a little less than one minute, so the graphs get updated */
    97     private static final int COALESCE_TIME = 50*1000;
     93    public static final int COALESCE_TIME = 50*1000;
    9894
    9995    /** this puts an 'H' in your routerInfo **/
     
    311307   
    312308    /** @since 0.8.8 */
    313     private static final void clearCaches() {
     309    public static final void clearCaches() {
    314310        ByteCache.clearAll();
    315311        SimpleByteCache.clearAll();
     
    511507            if (!ri.isValid())
    512508                throw new DataFormatException("Our RouterInfo has a bad signature");
    513             Republish r = new Republish();
     509            Republish r = new Republish(_context);
    514510            if (blockingRebuild)
    515511                r.timeReached();
     
    520516        }
    521517    }
    522    
    523     private class Republish implements SimpleTimer.TimedEvent {
    524         public void timeReached() {
    525             try {
    526                 _context.netDb().publish(getRouterInfo());
    527             } catch (IllegalArgumentException iae) {
    528                 _log.log(Log.CRIT, "Local router info is invalid?  rebuilding a new identity", iae);
    529                 rebuildNewIdentity();
    530             }
    531         }
    532     }
    533    
     518
    534519    // publicize our ballpark capacity
    535520    public static final char CAPABILITY_BW12 = 'K';
     
    10331018    /**
    10341019     *  Cancel the JVM runtime hook before calling this.
    1035      */
    1036     private void shutdown2(int exitCode) {
     1020     *  NOT to be called by others, use shutdown().
     1021     */
     1022    public void shutdown2(int exitCode) {
    10371023        // So we can get all the way to the end
    10381024        // No, you can't do Thread.currentThread.setDaemon(false)
     
    17401726        return Math.max(send, recv);
    17411727    }
    1742    
    1743     /**
    1744      *  Mark a string for extraction by xgettext and translation.
    1745      *  Use this only in static initializers.
    1746      *  It does not translate!
    1747      *  @return s
    1748      *  @since 0.8.7
    1749      */
    1750     private static final String _x(String s) {
    1751         return s;
    1752     }
    1753 
    1754 /* following classes are now private static inner classes, didn't bother to reindent */
    1755 
    1756 private static final long LOW_MEMORY_THRESHOLD = 5 * 1024 * 1024;
    1757 
    1758 /**
    1759  * coalesce the stats framework every minute
    1760  *
    1761  */
    1762 private static class CoalesceStatsEvent implements SimpleTimer.TimedEvent {
    1763     private RouterContext _ctx;
    1764     private long _maxMemory;
    1765 
    1766     public CoalesceStatsEvent(RouterContext ctx) {
    1767         _ctx = ctx;
    1768         // NOTE TO TRANSLATORS - each of these phrases is a description for a statistic
    1769         // to be displayed on /stats.jsp and in the graphs on /graphs.jsp.
    1770         // Please keep relatively short so it will fit on the graphs.
    1771         ctx.statManager().createRequiredRateStat("bw.receiveBps", _x("Message receive rate (bytes/sec)"), "Bandwidth", new long[] { 60*1000, 5*60*1000, 60*60*1000 });
    1772         ctx.statManager().createRequiredRateStat("bw.sendBps", _x("Message send rate (bytes/sec)"), "Bandwidth", new long[] { 60*1000, 5*60*1000, 60*60*1000 });
    1773         ctx.statManager().createRequiredRateStat("bw.sendRate", _x("Low-level send rate (bytes/sec)"), "Bandwidth", new long[] { 60*1000l, 5*60*1000l, 10*60*1000l, 60*60*1000l });
    1774         ctx.statManager().createRequiredRateStat("bw.recvRate", _x("Low-level receive rate (bytes/sec)"), "Bandwidth", new long[] { 60*1000l, 5*60*1000l, 10*60*1000l, 60*60*1000l });
    1775         ctx.statManager().createRequiredRateStat("router.activePeers", _x("How many peers we are actively talking with"), "Throttle", new long[] { 60*1000, 5*60*1000, 60*60*1000 });
    1776         ctx.statManager().createRateStat("router.activeSendPeers", "How many peers we've sent to this minute", "Throttle", new long[] { 60*1000, 5*60*1000, 60*60*1000 });
    1777         ctx.statManager().createRateStat("router.highCapacityPeers", "How many high capacity peers we know", "Throttle", new long[] { 5*60*1000, 60*60*1000 });
    1778         ctx.statManager().createRequiredRateStat("router.fastPeers", _x("Known fast peers"), "Throttle", new long[] { 5*60*1000, 60*60*1000 });
    1779         _maxMemory = Runtime.getRuntime().maxMemory();
    1780         String legend = "(Bytes)";
    1781         if (_maxMemory < Long.MAX_VALUE)
    1782             legend += " Max is " + DataHelper.formatSize(_maxMemory) + 'B';
    1783         // router.memoryUsed currently has the max size in the description so it can't be tagged
    1784         ctx.statManager().createRequiredRateStat("router.memoryUsed", legend, "Router", new long[] { 60*1000 });
    1785     }
    1786     private RouterContext getContext() { return _ctx; }
    1787     public void timeReached() {
    1788         int active = getContext().commSystem().countActivePeers();
    1789         getContext().statManager().addRateData("router.activePeers", active, 60*1000);
    1790 
    1791         int activeSend = getContext().commSystem().countActiveSendPeers();
    1792         getContext().statManager().addRateData("router.activeSendPeers", activeSend, 60*1000);
    1793 
    1794         int fast = getContext().profileOrganizer().countFastPeers();
    1795         getContext().statManager().addRateData("router.fastPeers", fast, 60*1000);
    1796 
    1797         int highCap = getContext().profileOrganizer().countHighCapacityPeers();
    1798         getContext().statManager().addRateData("router.highCapacityPeers", highCap, 60*1000);
    1799 
    1800         getContext().statManager().addRateData("bw.sendRate", (long)getContext().bandwidthLimiter().getSendBps(), 0);
    1801         getContext().statManager().addRateData("bw.recvRate", (long)getContext().bandwidthLimiter().getReceiveBps(), 0);
    1802        
    1803         long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    1804         getContext().statManager().addRateData("router.memoryUsed", used, 0);
    1805         if (_maxMemory - used < LOW_MEMORY_THRESHOLD)
    1806             clearCaches();
    1807 
    1808         getContext().tunnelDispatcher().updateParticipatingStats(COALESCE_TIME);
    1809 
    1810         getContext().statManager().coalesceStats();
    1811 
    1812         RateStat receiveRate = getContext().statManager().getRate("transport.receiveMessageSize");
    1813         if (receiveRate != null) {
    1814             Rate rate = receiveRate.getRate(60*1000);
    1815             if (rate != null) {
    1816                 double bytes = rate.getLastTotalValue();
    1817                 double bps = (bytes*1000.0d)/rate.getPeriod();
    1818                 getContext().statManager().addRateData("bw.receiveBps", (long)bps, 60*1000);
    1819             }
    1820         }
    1821 
    1822         RateStat sendRate = getContext().statManager().getRate("transport.sendMessageSize");
    1823         if (sendRate != null) {
    1824             Rate rate = sendRate.getRate(60*1000);
    1825             if (rate != null) {
    1826                 double bytes = rate.getLastTotalValue();
    1827                 double bps = (bytes*1000.0d)/rate.getPeriod();
    1828                 getContext().statManager().addRateData("bw.sendBps", (long)bps, 60*1000);
    1829             }
    1830         }
    1831     }
    18321728}
    1833 
    1834 /**
    1835  * Update the routing Key modifier every day at midnight (plus on startup).
    1836  * This is done here because we want to make sure the key is updated before anyone
    1837  * uses it.
    1838  */
    1839 private static class UpdateRoutingKeyModifierJob extends JobImpl {
    1840     private Log _log;
    1841     private Calendar _cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    1842     public UpdateRoutingKeyModifierJob(RouterContext ctx) {
    1843         super(ctx);
    1844     }
    1845     public String getName() { return "Update Routing Key Modifier"; }
    1846     public void runJob() {
    1847         _log = getContext().logManager().getLog(getClass());
    1848         getContext().routingKeyGenerator().generateDateBasedModData();
    1849         requeue(getTimeTillMidnight());
    1850     }
    1851     private long getTimeTillMidnight() {
    1852         long now = getContext().clock().now();
    1853         _cal.setTime(new Date(now));
    1854         _cal.set(Calendar.YEAR, _cal.get(Calendar.YEAR));               // gcj <= 4.0 workaround
    1855         _cal.set(Calendar.DAY_OF_YEAR, _cal.get(Calendar.DAY_OF_YEAR)); // gcj <= 4.0 workaround
    1856         _cal.add(Calendar.DATE, 1);
    1857         _cal.set(Calendar.HOUR_OF_DAY, 0);
    1858         _cal.set(Calendar.MINUTE, 0);
    1859         _cal.set(Calendar.SECOND, 0);
    1860         _cal.set(Calendar.MILLISECOND, 0);
    1861         long then = _cal.getTime().getTime();
    1862         long howLong = then - now;
    1863         if (howLong < 0) // hi kaffe
    1864             howLong = 24*60*60*1000l + howLong;
    1865         if (_log.shouldLog(Log.DEBUG))
    1866             _log.debug("Time till midnight: " + howLong + "ms");
    1867         return howLong;
    1868     }
    1869 }
    1870 
    1871 /**
    1872  *  Write a timestamp to the ping file where
    1873  *  other routers trying to use the same configuration can see it
    1874  */
    1875 private static class MarkLiveliness implements SimpleTimer.TimedEvent {
    1876     private final Router _router;
    1877     private final File _pingFile;
    1878 
    1879     public MarkLiveliness(Router router, File pingFile) {
    1880         _router = router;
    1881         _pingFile = pingFile;
    1882         _pingFile.deleteOnExit();
    1883     }
    1884 
    1885     public void timeReached() {
    1886         if (_router.isAlive())
    1887             ping();
    1888         else
    1889             _pingFile.delete();
    1890     }
    1891 
    1892     private void ping() {
    1893         FileOutputStream fos = null;
    1894         try {
    1895             fos = new SecureFileOutputStream(_pingFile);
    1896             fos.write(("" + System.currentTimeMillis()).getBytes());
    1897         } catch (IOException ioe) {
    1898             System.err.println("Error writing to ping file");
    1899             ioe.printStackTrace();
    1900         } finally {
    1901             if (fos != null) try { fos.close(); } catch (IOException ioe) {}
    1902         }
    1903     }
    1904 }
    1905 
    1906 /**
    1907  *  Just for failsafe. Standard shutdown should cancel this.
    1908  */
    1909 private static class ShutdownHook extends Thread {
    1910     private final RouterContext _context;
    1911     private static int __id = 0;
    1912     private final int _id;
    1913 
    1914     public ShutdownHook(RouterContext ctx) {
    1915         _context = ctx;
    1916         _id = ++__id;
    1917     }
    1918 
    1919     @Override
    1920     public void run() {
    1921         setName("Router " + _id + " shutdown");
    1922         Log l = _context.logManager().getLog(Router.class);
    1923         l.log(Log.CRIT, "Shutting down the router...");
    1924         _context.router().shutdown2(Router.EXIT_HARD);
    1925     }
    1926 }
    1927 
    1928 /** update the router.info file whenever its, er, updated */
    1929 private static class PersistRouterInfoJob extends JobImpl {
    1930     public PersistRouterInfoJob(RouterContext ctx) {
    1931         super(ctx);
    1932     }
    1933 
    1934     public String getName() { return "Persist Updated Router Information"; }
    1935 
    1936     public void runJob() {
    1937         Log _log = getContext().logManager().getLog(PersistRouterInfoJob.class);
    1938         if (_log.shouldLog(Log.DEBUG))
    1939             _log.debug("Persisting updated router info");
    1940 
    1941         String infoFilename = getContext().getProperty(PROP_INFO_FILENAME, PROP_INFO_FILENAME_DEFAULT);
    1942         File infoFile = new File(getContext().getRouterDir(), infoFilename);
    1943 
    1944         RouterInfo info = getContext().router().getRouterInfo();
    1945 
    1946         FileOutputStream fos = null;
    1947         synchronized (getContext().router().routerInfoFileLock) {
    1948             try {
    1949                 fos = new SecureFileOutputStream(infoFile);
    1950                 info.writeBytes(fos);
    1951             } catch (DataFormatException dfe) {
    1952                 _log.error("Error rebuilding the router information", dfe);
    1953             } catch (IOException ioe) {
    1954                 _log.error("Error writing out the rebuilt router information", ioe);
    1955             } finally {
    1956                 if (fos != null) try { fos.close(); } catch (IOException ioe) {}
    1957             }
    1958         }
    1959     }
    1960 }
    1961 
    1962 }
  • router/java/src/net/i2p/router/tasks/RouterWatchdog.java

    rd3564df rc0b9fe0  
    1 package net.i2p.router;
     1package net.i2p.router.tasks;
    22
    33import java.io.File;
    44
    55import net.i2p.data.DataHelper;
     6import net.i2p.router.Job;
     7import net.i2p.router.Router;
     8import net.i2p.router.RouterContext;
    69import net.i2p.stat.Rate;
    710import net.i2p.stat.RateStat;
     
    1417 *
    1518 */
    16 class RouterWatchdog implements Runnable {
     19public class RouterWatchdog implements Runnable {
    1720    private final Log _log;
    1821    private final RouterContext _context;
Note: See TracChangeset for help on using the changeset viewer.