Search in sources :

Example 1 with RouterContext

use of net.i2p.router.RouterContext in project i2p.i2p by i2p.

the class SummaryRenderer method render.

/**
 *  Single or two-data-source graph.
 *
 *  @param lsnr2 2nd data source to plot on same graph, or null. Not recommended for events.
 *  @param titleOverride If non-null, overrides the title
 *  @since 0.9.6 consolidated from StatSummarizer for bw.combined
 */
public void render(OutputStream out, int width, int height, boolean hideLegend, boolean hideGrid, boolean hideTitle, boolean showEvents, int periodCount, int endp, boolean showCredit, SummaryListener lsnr2, String titleOverride) throws IOException {
    // prevent NaNs if we are skewed ahead of system time
    long end = Math.min(_listener.now(), System.currentTimeMillis()) - 75 * 1000;
    long period = _listener.getRate().getPeriod();
    if (endp > 0)
        end -= period * endp;
    if (periodCount <= 0 || periodCount > _listener.getRows())
        periodCount = _listener.getRows();
    long start = end - (period * periodCount);
    // long begin = System.currentTimeMillis();
    ImageOutputStream ios = null;
    try {
        RrdGraphDef def = new RrdGraphDef();
        // Override defaults
        def.setColor(RrdGraphDef.COLOR_BACK, BACK_COLOR);
        def.setColor(RrdGraphDef.COLOR_SHADEA, SHADEA_COLOR);
        def.setColor(RrdGraphDef.COLOR_SHADEB, SHADEB_COLOR);
        def.setColor(RrdGraphDef.COLOR_GRID, GRID_COLOR);
        def.setColor(RrdGraphDef.COLOR_MGRID, MGRID_COLOR);
        def.setColor(RrdGraphDef.COLOR_FONT, FONT_COLOR);
        def.setColor(RrdGraphDef.COLOR_FRAME, FRAME_COLOR);
        def.setFont(RrdGraphDef.FONTTAG_DEFAULT, new Font(DEFAULT_FONT_NAME, Font.PLAIN, 10));
        def.setFont(RrdGraphDef.FONTTAG_TITLE, new Font(DEFAULT_FONT_NAME, Font.PLAIN, 10));
        def.setFont(RrdGraphDef.FONTTAG_AXIS, new Font("Droid Sans Mono", Font.PLAIN, 10));
        def.setFont(RrdGraphDef.FONTTAG_UNIT, new Font(DEFAULT_FONT_NAME, Font.PLAIN, 10));
        def.setFont(RrdGraphDef.FONTTAG_LEGEND, new Font("Droid Sans Mono", Font.PLAIN, 10));
        // improve text legibility
        String lang = Messages.getLanguage(_context);
        Font small = def.getSmallFont();
        Font large = def.getLargeFont();
        if ("ar".equals(lang) || "jp".equals(lang) || ("zh".equals(lang) && !IS_WIN)) {
            small = small.deriveFont(small.getSize2D() + 2.0f);
            large = large.deriveFont(Font.PLAIN, large.getSize2D() + 3.0f);
        } else {
            // small = small.deriveFont(small.getSize2D() + 1.0f);
            // if specified font family is missing, jrobin will use fallback
            small = new Font("Droid Sans Mono", Font.PLAIN, 10);
            // large = large.deriveFont(large.getSize2D() + 1.0f);
            large = new Font("Droid Sans", Font.PLAIN, 13);
        }
        def.setSmallFont(small);
        def.setLargeFont(large);
        def.setTimeSpan(start / 1000, end / 1000);
        def.setMinValue(0d);
        String name = _listener.getRate().getRateStat().getName();
        // if ((name.startsWith("bw.") || name.indexOf("Size") >= 0 || name.indexOf("Bps") >= 0 || name.indexOf("memory") >= 0)
        if ((name.indexOf("Size") >= 0 || name.indexOf("memory") >= 0) && !showEvents)
            def.setBase(1024);
        if (titleOverride != null) {
            def.setTitle(titleOverride);
        } else if (!hideTitle) {
            String title;
            String p;
            // we want the formatting and translation of formatDuration2(), except not zh, and not the &nbsp;
            if (IS_WIN && "zh".equals(Messages.getLanguage(_context)))
                p = DataHelper.formatDuration(period);
            else
                p = DataHelper.formatDuration2(period).replace("&nbsp;", " ");
            if (showEvents)
                title = name + ' ' + _t("events in {0}", p);
            else
                title = name + ' ' + _t("averaged for {0}", p);
            def.setTitle(title);
        }
        String path = _listener.getData().getPath();
        String[] dsNames = _listener.getData().getDsNames();
        String plotName;
        String descr;
        if (showEvents) {
            // include the average event count on the plot
            plotName = dsNames[1];
            descr = _t("Events per period");
        } else {
            // include the average value
            plotName = dsNames[0];
            // The descriptions are not tagged in the createRateStat calls
            // (there are over 500 of them)
            // but the descriptions for the default graphs are tagged in
            // Strings.java
            descr = _t(_listener.getRate().getRateStat().getDescription());
        }
        // long started = ((RouterContext)_context).router().getWhenStarted();
        // if (started > start && started < end)
        // def.vrule(started / 1000, RESTART_BAR_COLOR, _t("Restart"), 4.0f);
        def.datasource(plotName, path, plotName, SummaryListener.CF, _listener.getBackendName());
        if (descr.length() > 0) {
            def.area(plotName, AREA_COLOR, descr + "\\l");
        } else {
            def.area(plotName, AREA_COLOR);
        }
        if (!hideLegend) {
            def.gprint(plotName, SummaryListener.CF, "   " + _t("Avg") + ": %.2f%s");
            def.gprint(plotName, "MAX", ' ' + _t("Max") + ": %.2f%S");
            def.gprint(plotName, "LAST", ' ' + _t("Now") + ": %.2f%S\\l");
        }
        String plotName2 = null;
        if (lsnr2 != null) {
            String[] dsNames2 = lsnr2.getData().getDsNames();
            plotName2 = dsNames2[0];
            String path2 = lsnr2.getData().getPath();
            String descr2 = _t(lsnr2.getRate().getRateStat().getDescription());
            def.datasource(plotName2, path2, plotName2, SummaryListener.CF, lsnr2.getBackendName());
            def.line(plotName2, LINE_COLOR, descr2 + "\\l", 2);
            if (!hideLegend) {
                def.gprint(plotName2, SummaryListener.CF, "   " + _t("Avg") + ": %.2f%s");
                def.gprint(plotName2, "MAX", ' ' + _t("Max") + ": %.2f%S");
                def.gprint(plotName2, "LAST", ' ' + _t("Now") + ": %.2f%S\\l");
            }
        }
        if (!hideLegend) {
            // '07 Jul 21:09' with month name in the system locale
            // TODO: Fix Arabic time display
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMM HH:mm");
            Map<Long, String> events = ((RouterContext) _context).router().eventLog().getEvents(EventLog.STARTED, start);
            for (Map.Entry<Long, String> event : events.entrySet()) {
                long started = event.getKey().longValue();
                if (started > start && started < end) {
                    // String legend = _t("Restart") + ' ' + sdf.format(new Date(started)) + " UTC " + event.getValue() + "\\l";
                    if ("ar".equals(lang)) {
                        String legend = _t("Restart") + ' ' + sdf.format(new Date(started)) + " - " + event.getValue() + "\\l";
                        def.vrule(started / 1000, RESTART_BAR_COLOR, legend, 2.0f);
                    } else {
                        String legend = _t("Restart") + ' ' + sdf.format(new Date(started)) + " [" + event.getValue() + "]\\l";
                        def.vrule(started / 1000, RESTART_BAR_COLOR, legend, 2.0f);
                    }
                }
            }
            def.comment(sdf.format(new Date(start)) + " — " + sdf.format(new Date(end)) + " UTC\\r");
        }
        if (!showCredit)
            def.setShowSignature(false);
        /*
            // these four lines set up a graph plotting both values and events on the same chart
            // (but with the same coordinates, so the values may look pretty skewed)
                def.datasource(dsNames[0], path, dsNames[0], "AVERAGE", "MEMORY");
                def.datasource(dsNames[1], path, dsNames[1], "AVERAGE", "MEMORY");
                def.area(dsNames[0], AREA_COLOR, _listener.getRate().getRateStat().getDescription());
                def.line(dsNames[1], LINE_COLOR, "Events per period");
            */
        if (hideLegend)
            def.setNoLegend(true);
        if (hideGrid) {
            def.setDrawXGrid(false);
            def.setDrawYGrid(false);
        }
        // System.out.println("rendering: path=" + path + " dsNames[0]=" + dsNames[0] + " dsNames[1]=" + dsNames[1] + " lsnr.getName=" + _listener.getName());
        def.setAntiAliasing(false);
        // System.out.println("Rendering: \n" + def.exportXmlTemplate());
        // System.out.println("*****************\nData: \n" + _listener.getData().dump());
        def.setWidth(width);
        def.setHeight(height);
        def.setImageFormat("PNG");
        def.setLazy(true);
        RrdGraph graph;
        try {
            // NPE here if system is missing fonts - see ticket #915
            graph = new RrdGraph(def);
        } catch (NullPointerException npe) {
            _log.error("Error rendering", npe);
            StatSummarizer.setDisabled();
            throw new IOException("Error rendering - disabling graph generation. Missing font? See http://trac.i2p2.i2p/ticket/915");
        }
        int totalWidth = graph.getRrdGraphInfo().getWidth();
        int totalHeight = graph.getRrdGraphInfo().getHeight();
        BufferedImage img = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_USHORT_565_RGB);
        Graphics gfx = img.getGraphics();
        graph.render(gfx);
        ios = new MemoryCacheImageOutputStream(out);
        ImageIO.write(img, "png", ios);
    // System.out.println("Graph created");
    // File t = File.createTempFile("jrobinData", ".xml");
    // _listener.getData().dumpXml(new FileOutputStream(t));
    // System.out.println("plotted: " + (data != null ? data.length : 0) + " bytes in " + timeToPlot
    // ); // + ", data written to " + t.getAbsolutePath());
    } catch (RrdException re) {
        _log.error("Error rendering", re);
        throw new IOException("Error plotting: " + re.getMessage());
    } catch (IOException ioe) {
        // typically org.mortbay.jetty.EofException extends java.io.EOFException
        if (_log.shouldLog(Log.WARN))
            _log.warn("Error rendering", ioe);
        throw ioe;
    } catch (OutOfMemoryError oom) {
        _log.error("Error rendering", oom);
        throw new IOException("Error plotting: " + oom.getMessage());
    } finally {
        // this does not close the underlying stream
        if (ios != null)
            try {
                ios.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : RrdGraph(org.jrobin.graph.RrdGraph) RouterContext(net.i2p.router.RouterContext) IOException(java.io.IOException) Font(java.awt.Font) Date(java.util.Date) BufferedImage(java.awt.image.BufferedImage) RrdGraphDef(org.jrobin.graph.RrdGraphDef) Graphics(java.awt.Graphics) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) RrdException(org.jrobin.core.RrdException) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Example 2 with RouterContext

use of net.i2p.router.RouterContext in project i2p.i2p by i2p.

the class ConfigRestartBean method renderStatus.

/**
 * this also initiates the restart/shutdown based on action
 */
public static String renderStatus(String urlBase, String action, String nonce) {
    RouterContext ctx = ContextHelper.getContext(null);
    String systemNonce = getNonce();
    if ((nonce != null) && (systemNonce.equals(nonce)) && (action != null)) {
        // Normal browsers send value, IE sends button label
        if ("shutdownImmediate".equals(action) || _t("Shutdown immediately", ctx).equals(action)) {
            if (ctx.hasWrapper())
                ConfigServiceHandler.registerWrapperNotifier(ctx, Router.EXIT_HARD, false);
            // ctx.router().shutdown(Router.EXIT_HARD); // never returns
            // give the UI time to respond
            ctx.router().shutdownGracefully(Router.EXIT_HARD);
        } else if ("cancelShutdown".equals(action) || _t("Cancel shutdown", ctx).equals(action) || _t("Cancel restart", ctx).equals(action)) {
            ctx.router().cancelGracefulShutdown();
        } else if ("restartImmediate".equals(action) || _t("Restart immediately", ctx).equals(action)) {
            if (ctx.hasWrapper())
                ConfigServiceHandler.registerWrapperNotifier(ctx, Router.EXIT_HARD_RESTART, false);
            // ctx.router().shutdown(Router.EXIT_HARD_RESTART); // never returns
            // give the UI time to respond
            ctx.router().shutdownGracefully(Router.EXIT_HARD_RESTART);
        } else if ("restart".equals(action) || _t("Restart", ctx).equals(action)) {
            if (ctx.hasWrapper())
                ConfigServiceHandler.registerWrapperNotifier(ctx, Router.EXIT_GRACEFUL_RESTART, false);
            ctx.router().shutdownGracefully(Router.EXIT_GRACEFUL_RESTART);
        } else if ("shutdown".equals(action) || _t("Shutdown", ctx).equals(action)) {
            if (ctx.hasWrapper())
                ConfigServiceHandler.registerWrapperNotifier(ctx, Router.EXIT_GRACEFUL, false);
            ctx.router().shutdownGracefully();
        }
    }
    boolean shuttingDown = isShuttingDown(ctx);
    boolean restarting = isRestarting(ctx);
    long timeRemaining = ctx.router().getShutdownTimeRemaining();
    StringBuilder buf = new StringBuilder(128);
    if ((shuttingDown || restarting) && timeRemaining <= 5 * 1000) {
        buf.append("<h4>");
        if (restarting)
            buf.append(_t("Restart imminent", ctx));
        else
            buf.append(_t("Shutdown imminent", ctx));
        buf.append("</h4>");
    } else if (shuttingDown) {
        buf.append("<h4>");
        buf.append(_t("Shutdown in {0}", DataHelper.formatDuration2(timeRemaining), ctx));
        int tuns = ctx.tunnelManager().getParticipatingCount();
        if (tuns > 0) {
            buf.append("<br>").append(ngettext("Please wait for routing commitment to expire for {0} tunnel", "Please wait for routing commitments to expire for {0} tunnels", tuns, ctx));
        }
        buf.append("</h4><hr>");
        buttons(ctx, buf, urlBase, systemNonce, SET1);
    } else if (restarting) {
        buf.append("<h4>");
        buf.append(_t("Restart in {0}", DataHelper.formatDuration2(timeRemaining), ctx));
        int tuns = ctx.tunnelManager().getParticipatingCount();
        if (tuns > 0) {
            buf.append("<br>").append(ngettext("Please wait for routing commitment to expire for {0} tunnel", "Please wait for routing commitments to expire for {0} tunnels", tuns, ctx));
        }
        buf.append("</h4><hr>");
        buttons(ctx, buf, urlBase, systemNonce, SET2);
    } else {
        if (ctx.hasWrapper())
            buttons(ctx, buf, urlBase, systemNonce, SET3);
        else
            buttons(ctx, buf, urlBase, systemNonce, SET4);
    }
    return buf.toString();
}
Also used : RouterContext(net.i2p.router.RouterContext)

Example 3 with RouterContext

use of net.i2p.router.RouterContext in project i2p.i2p by i2p.

the class LocalClientManager method main.

public static void main(String[] args) {
    int dropX1000 = 0, jitter = 0, latency = 0;
    boolean error = false;
    Getopt g = new Getopt("router", args, "d:j:l:");
    try {
        int c;
        while ((c = g.getopt()) != -1) {
            switch(c) {
                case 'd':
                    dropX1000 = (int) (1000 * Double.parseDouble(g.getOptarg()));
                    if (dropX1000 < 0 || dropX1000 >= 100 * 1000)
                        error = true;
                    break;
                case 'j':
                    jitter = Integer.parseInt(g.getOptarg());
                    if (jitter < 0)
                        error = true;
                    break;
                case 'l':
                    latency = Integer.parseInt(g.getOptarg());
                    if (latency < 0)
                        error = true;
                    break;
                default:
                    error = true;
            }
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
        error = true;
    }
    if (error || args.length - g.getOptind() > 0) {
        usage();
        System.exit(1);
    }
    RouterContext ctx = new RouterContext(null);
    int port = ClientManagerFacadeImpl.DEFAULT_PORT;
    LocalClientManager mgr = new LocalClientManager(ctx, port);
    mgr.dropX1000 = dropX1000;
    mgr.jitter = jitter;
    mgr.latency = latency;
    mgr.start();
    System.out.println("Listening on port " + port);
    try {
        Thread.sleep(60 * 60 * 1000);
    } catch (InterruptedException ie) {
    }
    System.out.println("Done listening on port " + port);
}
Also used : Getopt(gnu.getopt.Getopt) RouterContext(net.i2p.router.RouterContext)

Example 4 with RouterContext

use of net.i2p.router.RouterContext in project i2p.i2p by i2p.

the class InstallUpdate method installUpdates.

/**
 * Context must be available.
 * Unzip update file found in the router dir OR base dir, to the base dir
 *
 * If successful, will call exit() and never return.
 *
 * If we can't write to the base dir, write message to System.out and return.
 * Note: _log not available here.
 */
public static void installUpdates(Router r) {
    RouterContext context = r.getContext();
    File updateFile = new File(context.getRouterDir(), Router.UPDATE_FILE);
    boolean exists = updateFile.exists();
    if (!exists) {
        updateFile = new File(context.getBaseDir(), Router.UPDATE_FILE);
        exists = updateFile.exists();
    }
    if (exists) {
        // do a simple permissions test, if it fails leave the file in place and don't restart
        File test = new File(context.getBaseDir(), "history.txt");
        if ((test.exists() && !test.canWrite()) || (!context.getBaseDir().canWrite())) {
            System.out.println("ERROR: No write permissions on " + context.getBaseDir() + " to extract software update file");
            // carry on
            return;
        }
        System.out.println("INFO: Update file exists [" + Router.UPDATE_FILE + "] - installing");
        // verify the whole thing first
        // we could remember this fails, and not bother restarting, but who cares...
        boolean ok = FileUtil.verifyZip(updateFile);
        if (ok) {
            // This may be useful someday. First added in 0.8.2
            // Moved above the extract so we don't NCDFE
            Map<String, String> config = new HashMap<String, String>(4);
            config.put("router.updateLastInstalled", "" + System.currentTimeMillis());
            // Set the last version to the current version, since 0.8.13
            config.put("router.previousVersion", RouterVersion.VERSION);
            config.put("router.previousFullVersion", RouterVersion.FULL_VERSION);
            r.saveConfig(config, null);
            ok = FileUtil.extractZip(updateFile, context.getBaseDir());
        }
        // Ideally, do not use I2P classes at all, new or not.
        try {
            if (ok) {
                // We do this here so we may delete old jars before we restart
                deleteListedFiles(context);
                System.out.println("INFO: Update installed");
            } else {
                System.out.println("ERROR: Update failed!");
            }
            if (!ok) {
                // we can't leave the file in place or we'll continually restart, so rename it
                File bad = new File(context.getRouterDir(), "BAD-" + Router.UPDATE_FILE);
                boolean renamed = updateFile.renameTo(bad);
                if (renamed) {
                    System.out.println("Moved update file to " + bad.getAbsolutePath());
                } else {
                    System.out.println("Deleting file " + updateFile.getAbsolutePath());
                    // so it will be deleted
                    ok = true;
                }
            }
            if (ok) {
                boolean deleted = updateFile.delete();
                if (!deleted) {
                    System.out.println("ERROR: Unable to delete the update file!");
                    updateFile.deleteOnExit();
                }
            }
            // exit whether ok or not
            if (context.hasWrapper())
                System.out.println("INFO: Restarting after update");
            else
                System.out.println("WARNING: Exiting after update, restart I2P");
        } catch (Throwable t) {
        // hide the NCDFE
        // hopefully the update file got deleted or we will loop
        }
        System.exit(Router.EXIT_HARD_RESTART);
    } else {
        deleteJbigiFiles(context);
        // It was here starting in 0.8.12 so it could be used the very first time
        // Now moved up so it is usually run only after an update
        // But the first time before jetty 6 it will run here...
        // Here we can't remove jars
        deleteListedFiles(context);
    }
}
Also used : HashMap(java.util.HashMap) RouterContext(net.i2p.router.RouterContext) File(java.io.File)

Example 5 with RouterContext

use of net.i2p.router.RouterContext in project i2p.i2p by i2p.

the class ProfileOrganizer method main.

/**
 * Read in all of the profiles specified and print out
 * their calculated values.  Usage: <pre>
 *  ProfileOrganizer [filename]*
 * </pre>
 */
public static void main(String[] args) {
    // new net.i2p.router.Router());
    RouterContext ctx = new RouterContext(null);
    ProfileOrganizer organizer = new ProfileOrganizer(ctx);
    organizer.setUs(Hash.FAKE_HASH);
    ProfilePersistenceHelper helper = new ProfilePersistenceHelper(ctx);
    for (int i = 0; i < args.length; i++) {
        PeerProfile profile = helper.readProfile(new java.io.File(args[i]));
        if (profile == null) {
            System.err.println("Could not load profile " + args[i]);
            continue;
        }
        organizer.addProfile(profile);
    }
    organizer.reorganize();
    DecimalFormat fmt = new DecimalFormat("0,000.0");
    fmt.setPositivePrefix("+");
    for (Hash peer : organizer.selectAllPeers()) {
        PeerProfile profile = organizer.getProfile(peer);
        if (!profile.getIsActive()) {
            System.out.println("Peer " + profile.getPeer().toBase64().substring(0, 4) + " [" + (organizer.isFast(peer) ? "IF+R" : organizer.isHighCapacity(peer) ? "IR  " : organizer.isFailing(peer) ? "IX  " : "I   ") + "]: " + "\t Speed:\t" + fmt.format(profile.getSpeedValue()) + " Capacity:\t" + fmt.format(profile.getCapacityValue()) + " Integration:\t" + fmt.format(profile.getIntegrationValue()) + " Active?\t" + profile.getIsActive() + " Failing?\t" + profile.getIsFailing());
        } else {
            System.out.println("Peer " + profile.getPeer().toBase64().substring(0, 4) + " [" + (organizer.isFast(peer) ? "F+R " : organizer.isHighCapacity(peer) ? "R   " : organizer.isFailing(peer) ? "X   " : "    ") + "]: " + "\t Speed:\t" + fmt.format(profile.getSpeedValue()) + " Capacity:\t" + fmt.format(profile.getCapacityValue()) + " Integration:\t" + fmt.format(profile.getIntegrationValue()) + " Active?\t" + profile.getIsActive() + " Failing?\t" + profile.getIsFailing());
        }
    }
    System.out.println("Thresholds:");
    System.out.println("Speed:       " + num(organizer.getSpeedThreshold()) + " (" + organizer.countFastPeers() + " fast peers)");
    System.out.println("Capacity:    " + num(organizer.getCapacityThreshold()) + " (" + organizer.countHighCapacityPeers() + " reliable peers)");
}
Also used : RouterContext(net.i2p.router.RouterContext) DecimalFormat(java.text.DecimalFormat) Hash(net.i2p.data.Hash)

Aggregations

RouterContext (net.i2p.router.RouterContext)12 Hash (net.i2p.data.Hash)4 RouterInfo (net.i2p.data.router.RouterInfo)3 Router (net.i2p.router.Router)2 RateStat (net.i2p.stat.RateStat)2 BeforeClass (org.junit.BeforeClass)2 Getopt (gnu.getopt.Getopt)1 Font (java.awt.Font)1 Graphics (java.awt.Graphics)1 BufferedImage (java.awt.image.BufferedImage)1 File (java.io.File)1 IOException (java.io.IOException)1 SocketException (java.net.SocketException)1 UnknownHostException (java.net.UnknownHostException)1 DecimalFormat (java.text.DecimalFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Properties (java.util.Properties)1