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:org.apache.flink.runtime.metrics.util.MetricUtils.java

private static void instantiateCPUMetrics(MetricGroup metrics) {
    try {/*from  ww  w .  jav  a 2s  .  co  m*/
        final OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();

        final Method fetchCPULoadMethod = Class.forName("com.sun.management.OperatingSystemMXBean")
                .getMethod("getProcessCpuLoad");
        // verify that we can invoke the method
        fetchCPULoadMethod.invoke(mxBean);

        final Method fetchCPUTimeMethod = Class.forName("com.sun.management.OperatingSystemMXBean")
                .getMethod("getProcessCpuTime");
        // verify that we can invoke the method
        fetchCPUTimeMethod.invoke(mxBean);

        metrics.gauge("Load", new Gauge<Double>() {
            @Override
            public Double getValue() {
                try {
                    return (Double) fetchCPULoadMethod.invoke(mxBean);
                } catch (IllegalAccessException | InvocationTargetException
                        | IllegalArgumentException ignored) {
                    return -1.0;
                }
            }
        });
        metrics.gauge("Time", new Gauge<Long>() {
            @Override
            public Long getValue() {
                try {
                    return (Long) fetchCPUTimeMethod.invoke(mxBean);
                } catch (IllegalAccessException | InvocationTargetException
                        | IllegalArgumentException ignored) {
                    return -1L;
                }
            }
        });
    } catch (ClassNotFoundException | InvocationTargetException | SecurityException | NoSuchMethodException
            | IllegalArgumentException | IllegalAccessException ignored) {
        LOG.warn("Cannot access com.sun.management.OperatingSystemMXBean.getProcessCpuLoad()"
                + " - CPU load metrics will not be available.");
        // make sure that a metric still exists for the given name
        metrics.gauge("Load", new Gauge<Double>() {
            @Override
            public Double getValue() {
                return -1.0;
            }
        });
        metrics.gauge("Time", new Gauge<Long>() {
            @Override
            public Long getValue() {
                return -1L;
            }
        });
    }
}

From source file:org.springframework.xd.batch.hsqldb.server.HSQLServerBean.java

/**
 * On UNIX operating systems, return the number of open file descriptors. On non UNIX operating systems this returns
 * -1./*w ww  . j  ava2s. co m*/
 * 
 * @return number of open file descriptors if this is executing on a UNIX operating system
 */
private long getOpenFileDescriptorCount() {
    OperatingSystemMXBean osStats = ManagementFactory.getOperatingSystemMXBean();
    return osStats instanceof UnixOperatingSystemMXBean
            ? ((UnixOperatingSystemMXBean) osStats).getOpenFileDescriptorCount()
            : -1;
}

From source file:org.cloudfoundry.identity.statsd.UaaMetricsEmitter.java

@Scheduled(fixedRate = 5000, initialDelay = 3000)
public void emitJvmVitals() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    String prefix = "vitals.jvm.";
    invokeIfPresent(prefix + "cpu.load", osBean, "getProcessCpuLoad", d -> (long) (d.doubleValue() * 100));
    statsDClient.gauge(prefix + "thread.count", threadBean.getThreadCount());
    Map<String, MemoryUsage> memory = new HashMap<>();
    memory.put("heap", memoryBean.getHeapMemoryUsage());
    memory.put("non-heap", memoryBean.getNonHeapMemoryUsage());
    memory.entrySet().stream().forEach(m -> {
        statsDClient.gauge(prefix + m.getKey() + ".init", m.getValue().getInit());
        statsDClient.gauge(prefix + m.getKey() + ".committed", m.getValue().getCommitted());
        statsDClient.gauge(prefix + m.getKey() + ".used", m.getValue().getUsed());
        statsDClient.gauge(prefix + m.getKey() + ".max", m.getValue().getMax());
    });/*from w  w  w .  j  a  va2 s . c  om*/

}

From source file:org.liferayhub.pc.service.impl.PowerConsoleServiceImpl.java

public String runCommand(long userId, long companyId, String mode, String command) {
    String response = "";
    Date startDate = new Date();
    if ("server".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the Liferay Portal\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "uptime\t\t  Display the uptime of the portal\n" + "adduser\t\t Add a new user";
        } else if ("version".equalsIgnoreCase(command)) {
            response = ReleaseInfo.getReleaseInfo() + " running on "
                    + StringUtil.upperCaseFirstLetter(ServerDetector.getServerId());
        } else if ("date".equalsIgnoreCase(command)) {
            response = new Date().toString();
        } else if ("uptime".equalsIgnoreCase(command)) {
            response = getUptime(PortalUtil.getUptime().getTime());
        } else if (command.toLowerCase().startsWith("adduser")) {
            response = handleAddUser(userId, companyId, command);
        }/*from  w w  w. j  a v a  2  s.  co  m*/
    } else if ("db".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the database\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "<sql query>\t Display result of any SQL query";
        } else if ("date".equalsIgnoreCase(command)) {
            response = runSQLQuery("select now() \"\"");
        } else if ("version".equalsIgnoreCase(command)) {
            response = runSQLQuery(
                    "select '" + DBFactoryUtil.getDBFactory().getDB().getType() + "' as '', version() ''");
        } else
            response = runSQLQuery(command);
    } else if ("jvm".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\tShow this help message\n"
                    + "mem\t\t Display memory usage of the JVM\n"
                    + "osinfo\t  Display operating system info of the running JVM\n"
                    + "vminfo\t  Display VM info";
        } else if ("mem".equalsIgnoreCase(command)) {
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            response = "Heap        : " + mem.getHeapMemoryUsage().toString();
            response += "\nNon Heap    : " + mem.getNonHeapMemoryUsage().toString();
            response += "\nFinalization: " + mem.getObjectPendingFinalizationCount() + " objects pending";
        } else if ("osinfo".equalsIgnoreCase(command)) {
            OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
            response = os.getName() + "[" + os.getArch() + "] " + os.getVersion() + " ("
                    + os.getAvailableProcessors() + " processors)";
            response += "\nLoad Average: " + os.getSystemLoadAverage();
        } else if ("vminfo".equalsIgnoreCase(command)) {
            RuntimeMXBean vm = ManagementFactory.getRuntimeMXBean();
            response = vm.getVmName() + " " + vm.getVmVersion() + " by " + vm.getVmVendor();
            response += "\n" + vm.getSpecName() + " " + vm.getSpecVersion() + " by " + vm.getSpecVendor();
            response += "\nStarted at: " + DateFormat.getInstance().format(new Date(vm.getStartTime()));
            response += "\nUptime    : " + getUptime(vm.getStartTime());
        } else {
            response = UNRECOGNIZED_COMMAND;
        }
    }
    // save command to database if it is not 'help'
    if (!command.startsWith("help")) {
        try {
            // add to history
            Date endDate = new Date();
            long id = CounterLocalServiceUtil.increment(CommandHistory.class.getName());
            CommandHistory history = CommandHistoryLocalServiceUtil.createCommandHistory(id);
            history.setCommand(command);
            history.setExecutionDate(startDate);
            history.setExecutionTime(endDate.getTime() - startDate.getTime());
            history.setMode(mode);
            history.setUserId(userId);
            CommandHistoryLocalServiceUtil.updateCommandHistory(history);
            // TODO: delete the oldest entry > MAX_HISTORY_SIZE
            // get the history size
            long historySize = 100;
            List<CommandHistory> historyList = CommandHistoryLocalServiceUtil
                    .findCommandHistoryByUserId(userId);
            if (historyList.size() >= historySize) {
                CommandHistoryLocalServiceUtil.deleteCommandHistory(historyList.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    return response;
}

From source file:com.emc.ecs.sync.service.SyncJobService.java

public SyncProgress getProgress(int jobId) {
    EcsSync sync = syncCache.get(jobId);

    if (sync == null)
        return null;

    SyncProgress syncProgress = new SyncProgress();
    syncProgress.setSyncStartTime(sync.getStartTime());
    syncProgress.setSyncStopTime(sync.getStopTime());
    syncProgress.setEstimatingTotals(sync.isEstimating());
    syncProgress.setTotalBytesExpected(sync.getEstimatedTotalBytes());
    syncProgress.setTotalObjectsExpected(sync.getEstimatedTotalObjects());
    syncProgress.setBytesComplete(sync.getBytesComplete());
    syncProgress.setObjectsComplete(sync.getObjectsComplete());
    syncProgress.setObjectsFailed(sync.getObjectsFailed());
    syncProgress.setActiveQueryTasks(sync.getActiveQueryThreads());
    syncProgress.setActiveSyncTasks(sync.getActiveSyncThreads());
    syncProgress.setRuntimeMs(sync.getTotalRunTime());
    syncProgress.setCpuTimeMs(sync.getTotalCpuTime());

    OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    syncProgress.setProcessCpuLoad(osBean.getProcessCpuLoad());
    syncProgress.setProcessMemoryUsed(Runtime.getRuntime().totalMemory());

    syncProgress.setSourceReadRate(sync.getSource().getReadPerformance());
    syncProgress.setSourceWriteRate(sync.getSource().getWritePerformance());
    syncProgress.setTargetReadRate(sync.getTarget().getReadPerformance());
    syncProgress.setTargetWriteRate(sync.getTarget().getWritePerformance());
    syncProgress.setObjectCompleteRate(sync.getObjectCompleteRate());
    syncProgress.setObjectErrorRate(sync.getObjectErrorRate());

    if (sync.getRunError() != null)
        syncProgress.setRunError(SyncUtil.summarize(sync.getRunError()));

    return syncProgress;
}

From source file:gridool.util.system.SystemUtils.java

public static double getCpuLoadAverage() {
    if (preferSigar) {
        final Double cpuload;
        try {//w  w w  .  j a va 2s.  c o  m
            cpuload = (Double) sigarCpuCombinedMtd.invoke(sigarCpuPercMtd.invoke(sigarInstance));
        } catch (Exception e) {
            LogFactory.getLog(SystemUtils.class).error("Failed to obtain CPU load via Hyperic Sigar", e);
            return -1d;
        }
        return cpuload.doubleValue();
    } else {
        OperatingSystemMXBean mx = ManagementFactory.getOperatingSystemMXBean();
        com.sun.management.OperatingSystemMXBean sunmx = (com.sun.management.OperatingSystemMXBean) mx;
        double d = sunmx.getSystemLoadAverage();
        if (d > 0) {
            return d / NPROCS;
        }
        return d;
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.PluginConfigImpl.java

public String getGcProcessMaxMemory() {
    String xmx = TeamCityProperties.getProperty("teamcity.git.gcXmx");
    if (!isEmpty(xmx))
        return xmx;
    try {//from  w ww .jav  a  2s.co m
        Class.forName("com.sun.management.OperatingSystemMXBean");
    } catch (ClassNotFoundException e) {
        return "768M";
    }
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        long freeRAM = ((com.sun.management.OperatingSystemMXBean) osBean).getFreePhysicalMemorySize();
        if (freeRAM > GB)
            return "1024M";
    }
    return "768M";
}

From source file:net.ftb.util.OSUtils.java

private static long getOSMemory(String methodName, String warning) {
    long ram = 0;

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    Method m;//from   w ww . j a v  a 2 s. c  o  m
    try {
        m = operatingSystemMXBean.getClass().getDeclaredMethod(methodName);
        m.setAccessible(true);
        Object value = m.invoke(operatingSystemMXBean);
        if (value != null) {
            ram = Long.valueOf(value.toString()) / 1024 / 1024;
        } else {
            Logger.logWarn(warning);
            ram = 1024;
        }
    } catch (Exception e) {
        Logger.logError("Error while getting OS memory info", e);
    }

    return ram;
}

From source file:org.apache.hyracks.control.nc.NodeControllerService.java

public NodeControllerService(NCConfig ncConfig) throws Exception {
    this.ncConfig = ncConfig;
    id = ncConfig.nodeId;/*from  w  ww  .  j a  v a2s  . c o m*/
    ipc = new IPCSystem(new InetSocketAddress(ncConfig.clusterNetIPAddress, ncConfig.clusterNetPort),
            new NodeControllerIPCI(this), new CCNCFunctions.SerializerDeserializer());

    ioManager = new IOManager(getDevices(ncConfig.ioDevices));
    if (id == null) {
        throw new Exception("id not set");
    }
    partitionManager = new PartitionManager(this);
    netManager = new NetworkManager(ncConfig.dataIPAddress, ncConfig.dataPort, partitionManager,
            ncConfig.nNetThreads, ncConfig.nNetBuffers, ncConfig.dataPublicIPAddress, ncConfig.dataPublicPort,
            FullFrameChannelInterfaceFactory.INSTANCE);

    lccm = new LifeCycleComponentManager();
    workQueue = new WorkQueue(id, Thread.NORM_PRIORITY); // Reserves MAX_PRIORITY of the heartbeat thread.
    jobletMap = new Hashtable<>();
    timer = new Timer(true);
    serverCtx = new ServerContext(ServerContext.ServerType.NODE_CONTROLLER,
            new File(new File(NodeControllerService.class.getName()), id));
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    threadMXBean = ManagementFactory.getThreadMXBean();
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    osMXBean = ManagementFactory.getOperatingSystemMXBean();
    registrationPending = true;
    getNodeControllerInfosAcceptor = new MutableObject<>();
    memoryManager = new MemoryManager(
            (long) (memoryMXBean.getHeapMemoryUsage().getMax() * MEMORY_FUDGE_FACTOR));
    ioCounter = new IOCounterFactory().getIOCounter();
}

From source file:edu.uci.ics.hyracks.control.nc.NodeControllerService.java

public NodeControllerService(NCConfig ncConfig) throws Exception {
    this.ncConfig = ncConfig;
    id = ncConfig.nodeId;/*  w w  w .  ja v a  2  s .  c  om*/
    NodeControllerIPCI ipci = new NodeControllerIPCI();
    ipc = new IPCSystem(new InetSocketAddress(ncConfig.clusterNetIPAddress, ncConfig.clusterNetPort), ipci,
            new CCNCFunctions.SerializerDeserializer());

    this.ctx = new RootHyracksContext(this, new IOManager(getDevices(ncConfig.ioDevices)));
    if (id == null) {
        throw new Exception("id not set");
    }
    partitionManager = new PartitionManager(this);
    netManager = new NetworkManager(ncConfig.dataIPAddress, ncConfig.dataPort, partitionManager,
            ncConfig.nNetThreads, ncConfig.nNetBuffers, ncConfig.dataPublicIPAddress, ncConfig.dataPublicPort);

    lccm = new LifeCycleComponentManager();
    queue = new WorkQueue();
    jobletMap = new Hashtable<JobId, Joblet>();
    timer = new Timer(true);
    serverCtx = new ServerContext(ServerContext.ServerType.NODE_CONTROLLER,
            new File(new File(NodeControllerService.class.getName()), id));
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    threadMXBean = ManagementFactory.getThreadMXBean();
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    osMXBean = ManagementFactory.getOperatingSystemMXBean();
    registrationPending = true;
    getNodeControllerInfosAcceptor = new MutableObject<FutureValue<Map<String, NodeControllerInfo>>>();
    memoryManager = new MemoryManager(
            (long) (memoryMXBean.getHeapMemoryUsage().getMax() * MEMORY_FUDGE_FACTOR));
    ioCounter = new IOCounterFactory().getIOCounter();
}