Example usage for java.lang.management ManagementFactory getOperatingSystemMXBean

List of usage examples for java.lang.management ManagementFactory getOperatingSystemMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getOperatingSystemMXBean.

Prototype

public static OperatingSystemMXBean getOperatingSystemMXBean() 

Source Link

Document

Returns the managed bean for the operating system on which the Java virtual machine is running.

Usage

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static double buildSystemLoadAverage() {
    // System load average for the last minute.
    // The system load average is the sum of
    // the number of runnable entities queued to the available processors
    // and the number of runnable entities running on the available processors
    // averaged over a period of time.
    final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
    if (operatingSystem.getSystemLoadAverage() >= 0) {
        // systemLoadAverage n'existe qu' partir du jdk 1.6
        return operatingSystem.getSystemLoadAverage();
    }/*from   ww w.ja va  2  s .c om*/
    return -1;
}

From source file:deincraftlauncher.InstallController.java

private int getDefaultRam() {
    int RAM;// w w w  . j  av  a 2s  .  c  o  m
    long memorySize = ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean())
            .getTotalPhysicalMemorySize();
    long RAMinMB = memorySize / 1024 / 1024;
    if (RAMinMB >= 8000) {
        RAM = 4096;
    } else if (RAMinMB >= 6000) {
        RAM = 2572;
    } else if (RAMinMB >= 4000) {
        RAM = 2048;
    } else {
        RAM = 1536;
    }

    return RAM;
}

From source file:com.all.ultrapeer.UltrapeerMonitor.java

private double calculateCpuUsage() throws InterruptedException {
    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    int numCpus = operatingSystemMXBean.getAvailableProcessors();
    long prevUpTime = runtimeMXBean.getUptime();
    long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
    Thread.sleep(500);//  w  w w . j a  v  a2 s .  com
    long upTime = runtimeMXBean.getUptime();
    long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
    if (prevUpTime > 0L && upTime > prevUpTime) {
        long elapsedCpu = processCpuTime - prevProcessCpuTime;
        long elapsedTime = upTime - prevUpTime;
        return Math.min(99F, elapsedCpu / (elapsedTime * 10000F * numCpus));
    }
    return 0.001;
}

From source file:org.powertac.visualizer.services.VisualizerServiceTournament.java

private void tournamentLogin() {
    //log.info("Tournament URL='" + tournamentUrl + "'");
    if (tournamentUrl.isEmpty()) {
        // No TM, just connect to server
        putEvent(Event.noTm);//from w  ww  . j av a 2 s.  c  o m
        return;
    }

    OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
    double load = mxBean.getSystemLoadAverage();

    String urlString = tournamentUrl + visualizerLoginContext + "?machineName=" + machineName + "&machineLoad="
            + load;
    log.info("tourney url=" + urlString);
    URL url;
    try {
        url = new URL(urlString);
        URLConnection conn = url.openConnection();
        InputStream input = conn.getInputStream();
        log.info("Parsing message..");
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(input);

        doc.getDocumentElement().normalize();

        // Two different message types
        Node retryNode = doc.getElementsByTagName("retry").item(0);
        Node loginNode = doc.getElementsByTagName("login").item(0);

        if (retryNode != null) {
            String checkRetry = retryNode.getFirstChild().getNodeValue();
            log.info("Retry in " + checkRetry + " seconds");
            // Received retry message; spin and try again
            try {
                Thread.sleep(Integer.parseInt(checkRetry) * 1000);
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
        } else if (loginNode != null) {
            log.info("Login response received! ");
            queueName = doc.getElementsByTagName("queueName").item(0).getFirstChild().getNodeValue();
            serverQueue = doc.getElementsByTagName("serverQueue").item(0).getFirstChild().getNodeValue();
            log.info(String.format("Login message received: queueName=%s, serverQueue=%s", queueName,
                    serverQueue));

            putEvent(Event.accept);
        } else {
            // this is not working
            log.info("Invalid response from TS");
        }
    } catch (Exception e) {
        // should we have an event here?
        e.printStackTrace();
    }
}

From source file:org.apache.kylin.storage.hbase.cube.v2.coprocessor.endpoint.CubeVisitService.java

@SuppressWarnings("checkstyle:methodlength")
@Override//from  www . j  ava  2  s .  c o  m
public void visitCube(final RpcController controller, final CubeVisitProtos.CubeVisitRequest request,
        RpcCallback<CubeVisitProtos.CubeVisitResponse> done) {
    List<RegionScanner> regionScanners = Lists.newArrayList();
    HRegion region = null;

    StringBuilder sb = new StringBuilder();
    byte[] allRows;
    String debugGitTag = "";

    CubeVisitProtos.CubeVisitResponse.ErrorInfo errorInfo = null;

    String queryId = request.hasQueryId() ? request.getQueryId() : "UnknownId";
    try (SetThreadName ignored = new SetThreadName("Query %s", queryId)) {
        final long serviceStartTime = System.currentTimeMillis();

        region = (HRegion) env.getRegion();
        region.startRegionOperation();

        // if user change kylin.properties on kylin server, need to manually redeploy coprocessor jar to update KylinConfig of Env.
        KylinConfig kylinConfig = KylinConfig.createKylinConfig(request.getKylinProperties());
        KylinConfig.setKylinConfigThreadLocal(kylinConfig);

        debugGitTag = region.getTableDesc().getValue(IRealizationConstants.HTableGitTag);

        final GTScanRequest scanReq = GTScanRequest.serializer.deserialize(
                ByteBuffer.wrap(HBaseZeroCopyByteString.zeroCopyGetBytes(request.getGtScanRequest())));
        List<List<Integer>> hbaseColumnsToGT = Lists.newArrayList();
        for (IntList intList : request.getHbaseColumnsToGTList()) {
            hbaseColumnsToGT.add(intList.getIntsList());
        }
        StorageSideBehavior behavior = StorageSideBehavior.valueOf(scanReq.getStorageBehavior());
        final List<RawScan> hbaseRawScans = deserializeRawScans(
                ByteBuffer.wrap(HBaseZeroCopyByteString.zeroCopyGetBytes(request.getHbaseRawScan())));

        appendProfileInfo(sb, "start latency: " + (serviceStartTime - scanReq.getStartTime()),
                serviceStartTime);

        final List<InnerScannerAsIterator> cellListsForeachRawScan = Lists.newArrayList();

        for (RawScan hbaseRawScan : hbaseRawScans) {
            if (request.getRowkeyPreambleSize() - RowConstants.ROWKEY_CUBOIDID_LEN > 0) {
                //if has shard, fill region shard to raw scan start/end
                updateRawScanByCurrentRegion(hbaseRawScan, region,
                        request.getRowkeyPreambleSize() - RowConstants.ROWKEY_CUBOIDID_LEN);
            }

            Scan scan = CubeHBaseRPC.buildScan(hbaseRawScan);
            RegionScanner innerScanner = region.getScanner(scan);
            regionScanners.add(innerScanner);

            InnerScannerAsIterator cellListIterator = new InnerScannerAsIterator(innerScanner);
            cellListsForeachRawScan.add(cellListIterator);
        }

        final Iterator<List<Cell>> allCellLists = Iterators.concat(cellListsForeachRawScan.iterator());

        if (behavior.ordinal() < StorageSideBehavior.SCAN.ordinal()) {
            //this is only for CoprocessorBehavior.RAW_SCAN case to profile hbase scan speed
            List<Cell> temp = Lists.newArrayList();
            int counter = 0;
            for (RegionScanner innerScanner : regionScanners) {
                while (innerScanner.nextRaw(temp)) {
                    counter++;
                }
            }
            appendProfileInfo(sb, "scanned " + counter, serviceStartTime);
        }

        if (behavior.ordinal() < StorageSideBehavior.SCAN_FILTER_AGGR_CHECKMEM.ordinal()) {
            scanReq.disableAggCacheMemCheck(); // disable mem check if so told
        }

        final long storagePushDownLimit = scanReq.getStoragePushDownLimit();

        ResourceTrackingCellListIterator cellListIterator = new ResourceTrackingCellListIterator(allCellLists,
                scanReq.getStorageScanRowNumThreshold(), // for old client (scan threshold)
                !request.hasMaxScanBytes() ? Long.MAX_VALUE : request.getMaxScanBytes(), // for new client
                scanReq.getTimeout());

        IGTStore store = new HBaseReadonlyStore(cellListIterator, scanReq, hbaseRawScans.get(0).hbaseColumns,
                hbaseColumnsToGT, request.getRowkeyPreambleSize(), behavior.delayToggledOn(),
                request.getIsExactAggregate());

        IGTScanner rawScanner = store.scan(scanReq);
        IGTScanner finalScanner = scanReq.decorateScanner(rawScanner, behavior.filterToggledOn(),
                behavior.aggrToggledOn(), false, request.getSpillEnabled());

        ByteBuffer buffer = ByteBuffer.allocate(BufferedMeasureCodec.DEFAULT_BUFFER_SIZE);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
                BufferedMeasureCodec.DEFAULT_BUFFER_SIZE);//ByteArrayOutputStream will auto grow
        int finalRowCount = 0;

        try {
            for (GTRecord oneRecord : finalScanner) {
                buffer.clear();
                try {
                    oneRecord.exportColumns(scanReq.getColumns(), buffer);
                } catch (BufferOverflowException boe) {
                    buffer = ByteBuffer.allocate(oneRecord.sizeOf(scanReq.getColumns()) * 2);
                    oneRecord.exportColumns(scanReq.getColumns(), buffer);
                }

                outputStream.write(buffer.array(), 0, buffer.position());

                finalRowCount++;

                //if it's doing storage aggr, then should rely on GTAggregateScanner's limit check
                if (!scanReq.isDoingStorageAggregation() && finalRowCount >= storagePushDownLimit) {
                    //read one more record than limit
                    logger.info("The finalScanner aborted because storagePushDownLimit is satisfied");
                    break;
                }
            }
        } catch (KylinTimeoutException e) {
            logger.info("Abort scan: {}", e.getMessage());
            errorInfo = CubeVisitProtos.CubeVisitResponse.ErrorInfo.newBuilder()
                    .setType(CubeVisitProtos.CubeVisitResponse.ErrorType.TIMEOUT).setMessage(e.getMessage())
                    .build();
        } catch (ResourceLimitExceededException e) {
            logger.info("Abort scan: {}", e.getMessage());
            errorInfo = CubeVisitProtos.CubeVisitResponse.ErrorInfo.newBuilder()
                    .setType(CubeVisitProtos.CubeVisitResponse.ErrorType.RESOURCE_LIMIT_EXCEEDED)
                    .setMessage(e.getMessage()).build();
        } finally {
            finalScanner.close();
        }

        appendProfileInfo(sb, "agg done", serviceStartTime);
        logger.info("Total scanned {} rows and {} bytes", cellListIterator.getTotalScannedRowCount(),
                cellListIterator.getTotalScannedRowBytes());

        //outputStream.close() is not necessary
        byte[] compressedAllRows;
        if (errorInfo == null) {
            allRows = outputStream.toByteArray();
        } else {
            allRows = new byte[0];
        }
        if (!kylinConfig.getCompressionResult()) {
            compressedAllRows = allRows;
        } else {
            compressedAllRows = CompressionUtils.compress(allRows);
        }

        appendProfileInfo(sb, "compress done", serviceStartTime);
        logger.info("Size of final result = {} ({} before compressing)", compressedAllRows.length,
                allRows.length);

        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory
                .getOperatingSystemMXBean();
        double systemCpuLoad = operatingSystemMXBean.getSystemCpuLoad();
        double freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize();
        double freeSwapSpaceSize = operatingSystemMXBean.getFreeSwapSpaceSize();

        appendProfileInfo(sb, "server stats done", serviceStartTime);
        sb.append(" debugGitTag:" + debugGitTag);

        CubeVisitProtos.CubeVisitResponse.Builder responseBuilder = CubeVisitProtos.CubeVisitResponse
                .newBuilder();
        if (errorInfo != null) {
            responseBuilder.setErrorInfo(errorInfo);
        }
        done.run(responseBuilder.//
                setCompressedRows(HBaseZeroCopyByteString.wrap(compressedAllRows)).//too many array copies 
                setStats(CubeVisitProtos.CubeVisitResponse.Stats.newBuilder()
                        .setAggregatedRowCount(cellListIterator.getTotalScannedRowCount() - finalRowCount)
                        .setScannedRowCount(cellListIterator.getTotalScannedRowCount())
                        .setScannedBytes(cellListIterator.getTotalScannedRowBytes())
                        .setServiceStartTime(serviceStartTime).setServiceEndTime(System.currentTimeMillis())
                        .setSystemCpuLoad(systemCpuLoad).setFreePhysicalMemorySize(freePhysicalMemorySize)
                        .setFreeSwapSpaceSize(freeSwapSpaceSize)
                        .setHostname(InetAddress.getLocalHost().getHostName()).setEtcMsg(sb.toString())
                        .setNormalComplete(errorInfo == null ? 1 : 0).build())
                .build());

    } catch (IOException ioe) {
        logger.error(ioe.toString(), ioe);
        IOException wrapped = new IOException("Error in coprocessor " + debugGitTag, ioe);
        ResponseConverter.setControllerException(controller, wrapped);
    } finally {
        for (RegionScanner innerScanner : regionScanners) {
            IOUtils.closeQuietly(innerScanner);
        }
        if (region != null) {
            try {
                region.closeRegionOperation();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:com.eurelis.opencms.admin.systeminformation.CmsCPUThreadsClassesOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *//*  w w w. j ava2s .  com*/
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    setCpuCount("" + osBean.getAvailableProcessors());
    double usage = com.eurelis.opencms.admin.systeminformation.CmsCPUThreadsClassesOverviewDialog
            .getCPUUsage(getSession());
    usage = Math.round(usage * 100) / 100;
    setCpuUsage("" + 100 * usage + "%");

    setLoadedClassesCount("" + classesBean.getLoadedClassCount());
    setUnloadedClassesCount("" + classesBean.getUnloadedClassCount());
    setTotalLoadedClassesCount("" + classesBean.getTotalLoadedClassCount());

    setThreadsCount("" + threadBean.getThreadCount());
    setThreadsStartedCount("" + threadBean.getTotalStartedThreadCount());
    setThreadsPeakCount("" + threadBean.getPeakThreadCount());
    setThreadsDaemonCount("" + threadBean.getDaemonThreadCount());

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

    setParamCloseLink(getJsp().link(
            "/system/workplace/views/admin/admin-main.jsp?path=/eurelis_system_information/cpu_and_threads.jsp"));

}

From source file:io.ecarf.core.utils.Utils.java

/**
 * Log the CPU stats//from www  .  j a va2s  . c o  m
 */
public static void logCpuStats() {
    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
    long upTime = runtimeMXBean.getUptime();
    double loadAverage = operatingSystemMXBean.getSystemLoadAverage();
    log.info("Available processors: " + availableProcessors);
    log.info("JVM upTime (ms): " + upTime);
    log.info("CPU load average: " + loadAverage);
}

From source file:org.apache.accumulo.server.monitor.servlets.TServersServlet.java

static void doTserverList(HttpServletRequest req, StringBuilder sb, List<TabletServerStatus> tservers,
        String tableId, Table tServerList) {
    int guessHighLoad = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    long now = System.currentTimeMillis();

    double avgLastContact = 0.;
    for (TabletServerStatus status : tservers) {
        avgLastContact += (now - status.lastContact);
    }/*from   w  w  w  .j a  va  2  s .  com*/
    final long MINUTES = 3 * 60 * 1000;
    tServerList.addSortableColumn("Server", new TServerLinkType(), null);
    tServerList.addSortableColumn("Hosted&nbsp;Tablets", new NumberType<Integer>(0, Integer.MAX_VALUE), null);
    tServerList.addSortableColumn("Last&nbsp;Contact",
            new DurationType(0l, (long) Math.min(avgLastContact * 4, MINUTES)), null);
    tServerList.addSortableColumn("Entries", new NumberType<Long>(), "The number of key/value pairs.");
    tServerList.addSortableColumn("Ingest", new NumberType<Long>(),
            "The number of key/value pairs inserted. (Note that deletes are also 'inserted')");
    tServerList.addSortableColumn("Query", new NumberType<Long>(),
            "The number of key/value pairs returned to clients. (Not the number of scans)");
    tServerList.addSortableColumn("Hold&nbsp;Time", new DurationType(),
            "The amount of time ingest is suspended waiting for data to be written to disk.");
    tServerList.addSortableColumn("Running<br />Scans", new CompactionsType("scans"),
            "The number of scans running and queued on this tablet server.");
    tServerList.addSortableColumn("Minor<br />Compactions", new CompactionsType("minor"),
            "The number of minor compactions running and (queued waiting for resources). Minor compactions are the operations where entries are flushed from memory to disk.");
    tServerList.addSortableColumn("Major<br />Compactions", new CompactionsType("major"),
            "The number of major compactions running and (queued waiting for resources). "
                    + "Major compactions are the operations where many smaller files are grouped into a larger file, eliminating duplicates and cleaning up deletes.");
    tServerList.addSortableColumn("Index Cache<br />Hit Rate", new PercentageType(),
            "The recent index cache hit rate.");
    tServerList.addSortableColumn("Data Cache<br />Hit Rate", new PercentageType(),
            "The recent data cache hit rate.");
    tServerList.addSortableColumn("OS&nbsp;Load",
            new NumberType<Double>(0., guessHighLoad * 1., 0., guessHighLoad * 3.),
            "The Unix one minute load average. The average number of processes in the run queue over a one minute interval.");

    log.debug("tableId: " + tableId);
    for (TabletServerStatus status : tservers) {
        if (status == null)
            status = NO_STATUS;
        TableInfo summary = Monitor.summarizeTableStats(status);
        if (tableId != null)
            summary = status.tableMap.get(tableId);
        if (summary == null)
            continue;
        TableRow row = tServerList.prepareRow();
        row.add(status); // add for server name
        row.add(summary.tablets);
        row.add(now - status.lastContact);
        row.add(summary.recs);
        row.add(summary.ingestRate);
        row.add(summary.queryRate);
        row.add(status.holdTime);
        row.add(summary); // add for scans
        row.add(summary); // add for minor compactions
        row.add(summary); // add for major compactions
        double indexCacheHitRate = status.indexCacheHits / (double) Math.max(status.indexCacheRequest, 1);
        row.add(indexCacheHitRate);
        double dataCacheHitRate = status.dataCacheHits / (double) Math.max(status.dataCacheRequest, 1);
        row.add(dataCacheHitRate);
        row.add(status.osLoad);
        tServerList.addRow(row);
    }
    tServerList.generate(req, sb);
}

From source file:org.apache.accumulo.monitor.servlets.TServersServlet.java

static void doTserverList(HttpServletRequest req, StringBuilder sb, List<TabletServerStatus> tservers,
        String tableId, Table tServerList) {
    int guessHighLoad = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    long now = System.currentTimeMillis();

    double avgLastContact = 0.;
    for (TabletServerStatus status : tservers) {
        avgLastContact += (now - status.lastContact);
    }//from  w  w w . j a  v a  2  s . co m
    final long MINUTES = 3 * 60 * 1000;
    tServerList.addSortableColumn("Server", new TServerLinkType(), null);
    tServerList.addSortableColumn("Hosted&nbsp;Tablets", new NumberType<Integer>(0, Integer.MAX_VALUE), null);
    tServerList.addSortableColumn("Last&nbsp;Contact",
            new DurationType(0l, (long) Math.min(avgLastContact * 4, MINUTES)), null);
    tServerList.addSortableColumn("Entries", new NumberType<Long>(), "The number of key/value pairs.");
    tServerList.addSortableColumn("Ingest", new NumberType<Long>(),
            "The number of key/value pairs inserted. (Note that deletes are also 'inserted')");
    tServerList.addSortableColumn("Query", new NumberType<Long>(),
            "The number of key/value pairs returned to clients. (Not the number of scans)");
    tServerList.addSortableColumn("Hold&nbsp;Time", new DurationType(),
            "The amount of time ingest is suspended waiting for data to be written to disk.");
    tServerList.addSortableColumn("Running<br />Scans", new CompactionsType("scans"),
            "The number of scans running and queued on this tablet server.");
    tServerList.addSortableColumn("Minor<br />Compactions", new CompactionsType("minor"),
            "The number of minor compactions running and (queued waiting for resources). Minor compactions are the operations where entries are flushed from memory to disk.");
    tServerList.addSortableColumn("Major<br />Compactions", new CompactionsType("major"),
            "The number of major compactions running and (queued waiting for resources). "
                    + "Major compactions are the operations where many smaller files are grouped into a larger file, eliminating duplicates and cleaning up deletes.");
    tServerList.addSortableColumn("Index Cache<br />Hit Rate", new PercentageType(),
            "The recent index cache hit rate.");
    tServerList.addSortableColumn("Data Cache<br />Hit Rate", new PercentageType(),
            "The recent data cache hit rate.");
    tServerList.addSortableColumn("OS&nbsp;Load",
            new NumberType<Double>(0., guessHighLoad * 1., 0., guessHighLoad * 3.),
            "The Unix one minute load average. The average number of processes in the run queue over a one minute interval.");

    log.debug("tableId: " + tableId);
    for (TabletServerStatus status : tservers) {
        if (status == null)
            status = NO_STATUS;
        TableInfo summary = TableInfoUtil.summarizeTableStats(status);
        if (tableId != null)
            summary = status.tableMap.get(tableId);
        if (summary == null)
            continue;
        TableRow row = tServerList.prepareRow();
        row.add(status); // add for server name
        row.add(summary.tablets);
        row.add(now - status.lastContact);
        row.add(summary.recs);
        row.add(summary.ingestRate);
        row.add(summary.queryRate);
        row.add(status.holdTime);
        row.add(summary); // add for scans
        row.add(summary); // add for minor compactions
        row.add(summary); // add for major compactions
        double indexCacheHitRate = status.indexCacheHits / (double) Math.max(status.indexCacheRequest, 1);
        row.add(indexCacheHitRate);
        double dataCacheHitRate = status.dataCacheHits / (double) Math.max(status.dataCacheRequest, 1);
        row.add(dataCacheHitRate);
        row.add(status.osLoad);
        tServerList.addRow(row);
    }
    tServerList.generate(req, sb);
}

From source file:de.prozesskraft.pkraft.Manager.java

/**
 * es soll so lange der process weitergetrieben werden, bis es keine veraenderung in den stati mehr gibt
 *///from  w  w w. j a  v a 2 s. c o m
private static void pushProcessAsFarAsPossible(String pathBinary, boolean onlyPush) {
    // zeitmarker setzen fuer timerThread
    lastRun = System.currentTimeMillis();

    // prozess instanz frisch einlesen
    System.err.println("debug: rereading instance");
    Process p1 = new Process();
    p1.setInfilebinary(pathBinary);
    p1.setOutfilebinary(pathBinary);
    Process process = p1.readBinary();
    System.err.println("debug: rereading instance done");
    process.log("debug", "rereading instance done");

    // falls managerIds nicht zusammenpassen, soll beendet werden
    // und dem alternativen thread mit flag signalisieren, dass es vorbei ist
    if (!managerid.equals(process.getManagerid())) {
        System.err.println("i'm manager " + managerid + " - another instance of pkraft-manager took over "
                + process.getManagerid() + ". killing myself.");
        exit = true;
        System.exit(0);
    }

    // beenden, falls process.run == false ist
    if (!process.run) {
        System.err.println("info: process manager exits, because process.run is false");
        exit = true;
        System.exit(0);
    }

    // 1) timeSerie loadAverage
    double actLoadAverage = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
    process.getTimeSerieLoadAverage().addValue(String.valueOf(actLoadAverage));

    if ((process.getStepStartLoadAverageBelow() != null)
            && (actLoadAverage > process.getStepStartLoadAverageBelow())) {
        // warte-faktor erhoehen
        factorSleepBecauseOfLoadAverage += 0.5;
    } else {
        // warte faktor resetten
        factorSleepBecauseOfLoadAverage = 1.0f;
    }

    // 2) die groesse des binary-files festhalten
    long fileSizeInKB = fileBinary.length() / 1024;

    System.err.println("debug: file size is now " + String.valueOf(fileSizeInKB) + " kB");
    process.getTimeSerieBinarySize().addValue(String.valueOf(fileSizeInKB));
    //p3.fileBinary.length() / 1024;

    // DEBUGGING
    // 3) die groesse der einzelnen steps festhalten
    String dieGroessenAlsString = "";
    for (Step actStep : process.getStep()) {
        dieGroessenAlsString += "   " + actStep.getName() + "=" + ObjectGraphMeasurer.measure(actStep);
    }
    process.getTimeSerieStepSize().addValue(dieGroessenAlsString);
    // DEBUGGING

    process.log("debug", "manager " + managerid + ": actual infilexml is: " + process.getInfilexml());
    process.log("debug", "manager " + managerid + ": reading binary file: " + process.getInfilebinary());
    // die manager-id mit eigener vergleichen. wenn nicht gleich, dann beenden.
    if (!(process.getManagerid() == managerid)) {
        //               p3.log("warn", "manager "+managerid+": it appears that another manager (id: "+p3.getManagerid()+") took over. killing myself. bye.");
        System.err.println("it appears another instance of manager (id: " + process.getManagerid()
                + ") took over. so i'm (id: " + managerid + ") not longer needed. killing myself. byebye.");
        exit = true;
        System.exit(0);
    }

    boolean imProzessHatSichWasGeaendert = true;
    System.err.println(
            "debug: variable imProzessHatSichWasGeaendert manuell gesetzt auf " + imProzessHatSichWasGeaendert);
    process.log("debug",
            "variable imProzessHatSichWasGeaendert manuell gesetzt auf " + imProzessHatSichWasGeaendert);

    while (process.run && imProzessHatSichWasGeaendert) {
        System.err.println("debug: deshalb wird die while schleife erst mal durchlaufen");
        process.log("debug", "deshalb wird die while schleife erst mal durchlaufen");

        // prozess laufen lassen
        process.doIt(ini.get("apps", "pkraft-syscall"), ini.get("apps", "pkraft-manager"),
                ini.get("process", "domain-installation-directory"));

        // setzen der schlafdauer sleepMinutes. richtet sich nach dem feld stepStartDelayMinutes falls dieses existiert
        if (process.stepStartDelayMinutesMinimumOfInitializedSteps() != null) {
            loopMinutes = process.stepStartDelayMinutesMinimumOfInitializedSteps();
            if (loopMinutes < 1) {
                loopMinutes = 1;
            }
        } else {
            loopMinutes = 5;
        }

        // hat sich was geaendert?
        imProzessHatSichWasGeaendert = process.isStepStatusChangedWhileLastDoIt();
        System.err.println("debug: did some step changed its status? " + imProzessHatSichWasGeaendert);
        process.log("debug", "did some step changed its status? " + imProzessHatSichWasGeaendert);

        // finished
        if (process.getStatus().equals("finished")) {
            System.err.println("debug: status is finished");

            // wenn der prozess den status 'finished' hat, soll dieses programm beendet werden
            process.run = false;
            process.log("info", "manager " + managerid
                    + ": process instance is finished. goodbye from manager id " + process.getManagerid());
            process.setTimeOfProcessFinishedOrError(System.currentTimeMillis());
        }

        // error
        else if (process.getStatus().equals("error")) {
            System.err.println("debug: status is error");
            process.run = false;
            process.log("info", "error in process detected. setting run = false");
            process.log("info", "stopping manager " + process.getManagerid());
            process.setTimeOfProcessFinishedOrError(System.currentTimeMillis());

            // errorcode string erzeugen
            String exitCode = "error-in-steps:";
            for (Step actStep : process.getStepError()) {
                exitCode = exitCode + "," + actStep.getName();
            }
        }
    }

    // binary und statistik files updaten
    updateFile(process);

    // pradar updaten
    pradarAttend(process.getInfilebinary());

    if (!process.run) {
        exit = true;
        System.exit(0);
    }

    // da prozess nicht mehr weiterging, werden watchKeys auf laufende steps erstellt
    if (!onlyPush) {
        process.log("info", "creating WatchKeys on every working step");
        System.err.println("info: creating WatchKeys on every working step");
        try {
            createWatchKeysForAllRunningSteps(process);
        }
        // falls das scheitert, soll einfach 1 minute gewartet werden
        catch (IOException e) {
            // TODO Auto-generated catch block
            System.err.println("error: failed to register file watchers. sleeping 1 minute instead");
            e.printStackTrace();
        }
    }
}