java.lang.management.OperatingSystemMXBean Java Examples

The following examples show how to use java.lang.management.OperatingSystemMXBean. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NativeManager.java    From LagMonitor with MIT License 6 votes vote down vote up
public void setupNativeAdapter() {
    try {
        if (!loadExternalJNI()) {
            if (!(osBean instanceof com.sun.management.OperatingSystemMXBean)) {
                logger.severe("You're not using Oracle Java nor using the native library. " +
                        "You won't be able to read some native data");
            }

            return;
        }
    } catch (IOException | ReflectiveOperationException ex) {
        logger.log(Level.WARNING, "Cannot load JNA library. We continue without it", ex);
        return;
    }

    logger.info("Found JNA native library. Enabling extended native data support to display more data");
    try {
        info = new SystemInfo();

        //make a test call
        pid = info.getOperatingSystem().getProcessId();
    } catch (UnsatisfiedLinkError | NoClassDefFoundError linkError) {
        logger.log(Level.INFO, "Cannot load native library. Continuing without it...", linkError);
        info = null;
    }
}
 
Example #2
Source File: JmxUtils.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Nullable
public synchronized static Method getOperatingSystemMBeanMethod(OperatingSystemMXBean operatingSystemBean, String methodName) {
    if (!initialized) {
        // lazy initialization - try loading the classes as late as possible
        init();
    }
    if (operatingSystemBeanClass == null) {
        return null;
    }
    try {
        // ensure the Bean we have is actually an instance of the interface
        operatingSystemBeanClass.cast(operatingSystemBean);
        return operatingSystemBeanClass.getMethod(methodName);
    } catch (ClassCastException | NoSuchMethodException | SecurityException e) {
        return null;
    }
}
 
Example #3
Source File: CpuMonitorProbe.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
CpuMonitorProbe(MonitoredDataResolver resolver, Application application,
                Jvm jvm) {
    super(2, createItemDescriptors(), resolver);
    cpuSupported = jvm.isCpuMonitoringSupported();
    gcSupported = jvm.isCollectionTimeSupported();
    int pCount = 1;
    JmxModel jmxModel = JmxModelFactory.getJmxModelFor(application);
    if (jmxModel != null && jmxModel.getConnectionState() == ConnectionState.CONNECTED) {
        JvmMXBeans mxbeans = JvmMXBeansFactory.getJvmMXBeans(jmxModel);
        if (mxbeans != null) {
            OperatingSystemMXBean osbean = mxbeans.getOperatingSystemMXBean();
            if (osbean != null) pCount = osbean.getAvailableProcessors();
        }
    }
    processorsCount = pCount;
}
 
Example #4
Source File: SystemInfoHandlerTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testMagickGetter() throws Exception {

    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();

    // make one directly
    SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
    info.add( "name", os.getName() );
    info.add( "version", os.getVersion() );
    info.add( "arch", os.getArch() );

    // make another using MetricUtils.addMXBeanMetrics()
    SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
    MetricUtils.addMXBeanMetrics( os, OperatingSystemMXBean.class, null, (k, v) -> {
      info2.add(k, ((Gauge)v).getValue());
    } );

    // make sure they got the same thing
    for (String p : Arrays.asList("name", "version", "arch")) {
      assertEquals(info.get(p), info2.get(p));
    }
  }
 
Example #5
Source File: MonitorSaveTask.java    From LagMonitor with MIT License 6 votes vote down vote up
private int save() {
    Runtime runtime = Runtime.getRuntime();
    int maxMemory = LagUtils.byteToMega(runtime.maxMemory());
    //we need the free ram not the free heap
    int usedRam = LagUtils.byteToMega(runtime.totalMemory() - runtime.freeMemory());
    int freeRam = maxMemory - usedRam;

    float freeRamPct = round((freeRam * 100) / maxMemory, 4);

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    float loadAvg = round(osBean.getSystemLoadAverage(), 4);
    if (loadAvg < 0) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeManager nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float processUsage = round(nativeData.getProcessCPULoad() * 100, 4);

    int totalOsMemory = LagUtils.byteToMega(nativeData.getTotalMemory());
    int freeOsRam = LagUtils.byteToMega(nativeData.getFreeMemory());

    float freeOsRamPct = round((freeOsRam * 100) / totalOsMemory, 4);
    return storage.saveMonitor(processUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
 
Example #6
Source File: SystemUsage.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Check how active the system is (CPU) or if not available, using system load average.
 * <p>
 * - On some OSes CPU usage information is not available, and system load average is used instead.
 * - On some OSes system load average is not available.
 *
 * @return 0.0 to 100.0 if CPU, or system load average, or -1 if nothing is available.
 */
public static double getAverageSystemLoad() {
    double averageUsage;

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean nativeOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
        averageUsage = nativeOsBean.getSystemCpuLoad();
    } else {
        int availableProcessors = osBean.getAvailableProcessors();
        averageUsage = osBean.getSystemLoadAverage() / availableProcessors;
    }
    if (averageUsage < 0) {
        averageUsage = -1; // If unavailable, getSystemLoadAverage() returns -1
    }
    return averageUsage * 100.0;
}
 
Example #7
Source File: MonitorSaveTask.java    From LagMonitor with MIT License 6 votes vote down vote up
private int save() {
    Runtime runtime = Runtime.getRuntime();
    int maxMemory = LagUtils.byteToMega(runtime.maxMemory());
    //we need the free ram not the free heap
    int usedRam = LagUtils.byteToMega(runtime.totalMemory() - runtime.freeMemory());
    int freeRam = maxMemory - usedRam;

    float freeRamPct = round((freeRam * 100) / maxMemory, 4);

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    float loadAvg = round(osBean.getSystemLoadAverage(), 4);
    if (loadAvg < 0) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeManager nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float processUsage = round(nativeData.getProcessCPULoad() * 100, 4);

    int totalOsMemory = LagUtils.byteToMega(nativeData.getTotalMemory());
    int freeOsRam = LagUtils.byteToMega(nativeData.getFreeMemory());

    float freeOsRamPct = round((freeOsRam * 100) / totalOsMemory, 4);
    return storage.saveMonitor(processUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
 
Example #8
Source File: LoadStatusChecker.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class<?>[0]);
	    load = (Double)method.invoke(operatingSystemMXBean, new Object[0]);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu);
}
 
Example #9
Source File: MXBeanInteropTest1.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private final int doOperatingSystemMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- OperatingSystemMXBean") ;

    try {
        ObjectName operationName =
                new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(operationName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        OperatingSystemMXBean operation = null ;

        operation =
                JMX.newMXBeanProxy(mbsc,
                operationName,
                OperatingSystemMXBean.class) ;
        System.out.println("getArch\t\t"
                + operation.getArch());
        System.out.println("getAvailableProcessors\t\t"
                + operation.getAvailableProcessors());
        System.out.println("getName\t\t"
                + operation.getName());
        System.out.println("getVersion\t\t"
                + operation.getVersion());

        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example #10
Source File: LoadStatusChecker.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class<?>[0]);
	    load = (Double)method.invoke(operatingSystemMXBean, new Object[0]);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu);
}
 
Example #11
Source File: ServerWatch.java    From ping with Apache License 2.0 5 votes vote down vote up
public JsonObject osInfo() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    return Json.createObjectBuilder().
            add("System Load Average", osBean.getSystemLoadAverage()).
            add("Available CPUs", osBean.getAvailableProcessors()).
            add("Architecture", osBean.getArch()).
            add("OS Name", osBean.getName()).
            add("Version", osBean.getVersion()).build();

}
 
Example #12
Source File: Performance.java    From XRTB with Apache License 2.0 5 votes vote down vote up
/**
 * Get CPU performance as a String, adjusted by cores
 * 
 * @return String. Returns a cpu percentage string
 */
public static String getCpuPerfAsString() {
	OperatingSystemMXBean mx = java.lang.management.ManagementFactory.getOperatingSystemMXBean();
	int cores = Runtime.getRuntime().availableProcessors();
	double d = mx.getSystemLoadAverage() * 100 / cores;
       return formatter.format(d);
}
 
Example #13
Source File: JVMMetrics.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
private long getProcessCPUTimeNs() {
  if (osMbean instanceof com.sun.management.OperatingSystemMXBean) {
    final com.sun.management.OperatingSystemMXBean sunOsMbean =
        (com.sun.management.OperatingSystemMXBean) osMbean;
    return sunOsMbean.getProcessCpuTime();
  }

  return -1;
}
 
Example #14
Source File: LoadStatusChecker.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class<?>[0]);
	    load = (Double)method.invoke(operatingSystemMXBean, new Object[0]);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), "Load: " + load + " / CPU: " + cpu);
}
 
Example #15
Source File: SystemLoadHealthCheck.java    From watcher with Apache License 2.0 5 votes vote down vote up
@Override
protected Result check() throws Exception {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load = operatingSystemMXBean.getSystemLoadAverage();
	int cpu = operatingSystemMXBean.getAvailableProcessors();
	if (load < cpu) {
		return Result.healthy();
	} else {
		return Result.unhealthy("load:%s,cpu:%s", load, cpu);
	}
	
}
 
Example #16
Source File: OperatingSystemMetrice.java    From neural with MIT License 5 votes vote down vote up
/**
 * 系统平均负载(满负荷状态为1.00*CPU核数)
 */
public Double getData() {
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    double load;
    try {
        Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage");
        load = (Double) method.invoke(operatingSystemMXBean, new Object[0]);
    } catch (Throwable e) {
        load = -1;
    }
    int cpu = operatingSystemMXBean.getAvailableProcessors();
    return Double.valueOf(String.format("%.4f", load / cpu));
}
 
Example #17
Source File: LoadStatusChecker.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage");
	    load = (Double)method.invoke(operatingSystemMXBean);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), (load < 0 ? "" : "load:" + load + ",") + "cpu:" + cpu);
}
 
Example #18
Source File: StoreUtil.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("restriction")
public static long getTotalPhysicalMemorySize() {
    long physicalTotal = 1024 * 1024 * 1024 * 24L;
    OperatingSystemMXBean osmxb = ManagementFactory.getOperatingSystemMXBean();
    if (osmxb instanceof com.sun.management.OperatingSystemMXBean) {
        physicalTotal = ((com.sun.management.OperatingSystemMXBean) osmxb).getTotalPhysicalMemorySize();
    }

    return physicalTotal;
}
 
Example #19
Source File: LoadStatusChecker.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Status check() {
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	double load;
	try {
	    Method method = OperatingSystemMXBean.class.getMethod("getSystemLoadAverage", new Class<?>[0]);
	    load = (Double)method.invoke(operatingSystemMXBean, new Object[0]);
	} catch (Throwable e) {
	    load = -1;
	}
	int cpu = operatingSystemMXBean.getAvailableProcessors();
    return new Status(load < 0 ? Status.Level.UNKNOWN : (load < cpu ? Status.Level.OK : Status.Level.WARN), (load < 0 ? "" : "load:" + load + ",") + "cpu:" + cpu);
}
 
Example #20
Source File: OperatingSystemDiagnosticTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public DiagnosticsDumpElement captureDump(final boolean verbose) {
    final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    final List<String> details = new ArrayList<>();

    final NumberFormat numberFormat = NumberFormat.getInstance();

    try {
        final SortedMap<String, String> attributes = new TreeMap<>();

        final ObjectName osObjectName = os.getObjectName();
        final MBeanInfo mbeanInfo = ManagementFactory.getPlatformMBeanServer().getMBeanInfo(osObjectName);
        for (final MBeanAttributeInfo attributeInfo : mbeanInfo.getAttributes()) {
            final String attributeName = attributeInfo.getName();
            if (IGNORABLE_ATTRIBUTE_NAMES.contains(attributeName)) {
                continue;
            }

            final Object attributeValue = ManagementFactory.getPlatformMBeanServer().getAttribute(osObjectName, attributeName);

            if (attributeValue instanceof Number) {
                attributes.put(attributeName, numberFormat.format(attributeValue));
            } else {
                attributes.put(attributeName, String.valueOf(attributeValue));
            }
        }

        attributes.forEach((key, value) -> details.add(key + " : " + value));
    } catch (final Exception e) {
        logger.error("Failed to obtain Operating System details", e);
        return new StandardDiagnosticsDumpElement("Operating System / Hardware", Collections.singletonList("Failed to obtain Operating System details"));
    }

    return new StandardDiagnosticsDumpElement("Operating System / Hardware", details);
}
 
Example #21
Source File: NativeManager.java    From LagMonitor with MIT License 5 votes vote down vote up
public long getTotalMemory() {
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean nativeOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
        return nativeOsBean.getTotalPhysicalMemorySize();
    } else if (info != null) {
        return info.getHardware().getMemory().getTotal();
    }

    return -1;
}
 
Example #22
Source File: JmxSupport.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
int getAvailableProcessors() {
    JvmMXBeans jmx = getJvmMXBeans();
    if (jmx != null) {
        OperatingSystemMXBean osMXBean = jmx.getOperatingSystemMXBean();

        if (osMXBean != null) {
            return osMXBean.getAvailableProcessors();
        }
    }
    return -1;
}
 
Example #23
Source File: StoreUtil.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("restriction")
public static long getTotalPhysicalMemorySize() {
    long physicalTotal = 1024 * 1024 * 1024 * 24L;
    OperatingSystemMXBean osmxb = ManagementFactory.getOperatingSystemMXBean();
    if (osmxb instanceof com.sun.management.OperatingSystemMXBean) {
        physicalTotal = ((com.sun.management.OperatingSystemMXBean) osmxb).getTotalPhysicalMemorySize();
    }

    return physicalTotal;
}
 
Example #24
Source File: StoreUtil.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("restriction")
public static long getTotalPhysicalMemorySize() {
    long physicalTotal = 1024 * 1024 * 1024 * 24L;
    OperatingSystemMXBean osmxb = ManagementFactory.getOperatingSystemMXBean();
    if (osmxb instanceof com.sun.management.OperatingSystemMXBean) {
        physicalTotal = ((com.sun.management.OperatingSystemMXBean) osmxb).getTotalPhysicalMemorySize();
    }

    return physicalTotal;
}
 
Example #25
Source File: FileDescriptorMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void fileDescriptorMetricsUnsupportedOsBeanMock() {
    final OperatingSystemMXBean osBean = mock(UnsupportedOperatingSystemMXBean.class);
    new FileDescriptorMetrics(osBean, Tags.of("some", "tag")).bindTo(registry);

    assertThat(registry.find("process.files.open").gauge()).isNull();
    assertThat(registry.find("process.files.max").gauge()).isNull();
}
 
Example #26
Source File: NativeManager.java    From LagMonitor with MIT License 5 votes vote down vote up
public double getProcessCPULoad() {
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean nativeOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
        return nativeOsBean.getProcessCpuLoad();
    }

    return -1;
}
 
Example #27
Source File: SystemMonitor.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
Report(OperatingSystemMXBean osBean) {
    map.put(OS_NAME, osBean.getName());
    map.put(OS_VERSION, osBean.getVersion());
    map.put(OS_ARCH, osBean.getArch());
    map.put(SYSTEM_AVAILABLE_PROCESSORS, osBean.getAvailableProcessors());
    map.put(SYSTEM_LOAD_AVERAGE, osBean.getSystemLoadAverage());
}
 
Example #28
Source File: SysUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 操作系统信息
 * @author JiangZhiYong
 * @QQ 359135103
 * 2017年10月12日 下午5:21:19
 * @param spliteStr
 * @return
 */
public static String osInfo(String spliteStr) {
	OperatingSystemMXBean bean=ManagementFactory.getOperatingSystemMXBean();
	StringBuilder sb = new StringBuilder();
	sb.append("操作系统架构:   ").append(bean.getArch()).append(spliteStr);
	sb.append("可使用的cpu数量:   ").append(bean.getAvailableProcessors()).append(spliteStr);
	sb.append("操作系统名称:   ").append(bean.getName()).append(spliteStr);
	sb.append("1分钟cpu消耗平均值:   ").append(bean.	getSystemLoadAverage()).append(spliteStr);
	sb.append("操作系统版本:   ").append(bean.getVersion()).append(spliteStr);
	return sb.toString();
}
 
Example #29
Source File: MXBeanInteropTest1.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private final int doOperatingSystemMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- OperatingSystemMXBean") ;

    try {
        ObjectName operationName =
                new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME) ;
        MBeanInfo mbInfo = mbsc.getMBeanInfo(operationName);
        errorCount += checkNonEmpty(mbInfo);
        System.out.println("getMBeanInfo\t\t" + mbInfo);
        OperatingSystemMXBean operation = null ;

        operation =
                JMX.newMXBeanProxy(mbsc,
                operationName,
                OperatingSystemMXBean.class) ;
        System.out.println("getArch\t\t"
                + operation.getArch());
        System.out.println("getAvailableProcessors\t\t"
                + operation.getAvailableProcessors());
        System.out.println("getName\t\t"
                + operation.getName());
        System.out.println("getVersion\t\t"
                + operation.getVersion());

        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example #30
Source File: NativeManager.java    From LagMonitor with MIT License 5 votes vote down vote up
public long getFreeSwap() {
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        com.sun.management.OperatingSystemMXBean nativeOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
        return nativeOsBean.getFreeSwapSpaceSize();
    } else if (info != null) {
        GlobalMemory memory = info.getHardware().getMemory();
        return memory.getAvailable();
    }

    return -1;
}