下面列出了java.lang.management.PlatformManagedObject#java.lang.management.OperatingSystemMXBean 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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;
}
}
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));
}
}
@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;
}
}
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);
}
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;
}
/**
* 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;
}
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());
}
public static short getLoadAndScaleToPercent(Method method, OperatingSystemMXBean osMxBean) {
if (method != null) {
try {
double load = (double) method.invoke(osMxBean);
if (load >= 0) {
return (short) (load * 100);
}
} catch (Exception e) {
return -1;
}
}
return -1;
}
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();
}
return -1;
}
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);
}
private long getOpenFileDescriptors() {
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
if (os instanceof UnixOperatingSystemMXBean) {
return ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
} else {
return -1;
}
}
@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;
}
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 ;
}
private void analyzeCpuUsage(final List<String> details) {
final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
final double loadAverage = os.getSystemLoadAverage();
final int availableProcs = os.getAvailableProcessors();
if (loadAverage > availableProcs) {
details.add(String.format("1-minute CPU Load Average is %1$.2f, which exceeds the %2$d available cores. CPU is over-utilized.", loadAverage, availableProcs));
} else if (loadAverage > 0.9 * availableProcs) {
details.add(String.format("1-minute CPU Load Average is %1$.2f, which exceeds 90%% of the %2$d available cores. CPU may struggle to keep up.", loadAverage, availableProcs));
}
}
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 ;
}
/**
* This method uses a Sun specific class (implementation of the Operating System MX Bean.
* @return the CPU system load, or {@literal -1.0} if not available.
*/
private Double getSystemCpuLoad() {
if (bean instanceof com.sun.management.OperatingSystemMXBean) { //NOSONAR
return ((com.sun.management.OperatingSystemMXBean) bean).getSystemCpuLoad() * 100.0; //NOSONAR
} else {
return -1.0;
}
}
private OperatingSystemMXBean getOperatingSystemMXBeanProxy() {
if (osServiceProxy == null) {
try {
setConnection();
} catch (Exception ex) {
throwException("Can't create proxy of OperatingSystemMXBean",
ex);
}
}
return osServiceProxy;
}
/**
* Creates a new gauge using the given OS bean.
*
* @param os an {@link OperatingSystemMXBean}
*/
public FileDescriptorRatioGauge(OperatingSystemMXBean os, long timeout, TimeUnit unit) {
this.os = os;
cachedRatio = new CachedGauge<Ratio>(timeout, unit) {
@Override
protected Ratio loadValue() {
return getRatioInternal();
}
};
}
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();
}
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 ;
}
/**
* Get number of available processors.
* @return number of available processors.
*/
public static int getAvailableProcessors() {
final OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
if (bean != null) {
return bean.getAvailableProcessors();
}
throw new IllegalStateException();
}
/**
* 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);
}
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;
}
@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;
}
public static long getLongFromOperatingSystem(OperatingSystemMXBean operatingSystem, String methodName) {
try {
final Method method = operatingSystem.getClass().getMethod(methodName, (Class<?>[]) null);
method.setAccessible(true);
return (Long) method.invoke(operatingSystem, (Object[]) null);
} catch (final Exception e) {
LOG.info(String.format("OperatingSystemMXBean %s failed, Exception = %s ", methodName, e.getMessage()));
}
return -1;
}
/**
* Initializes the metrics registry
*
* @return metric registry bean
*/
@Bean
public MetricRegistry metricRegistry() {
final MetricRegistry bean = new MetricRegistry();
// add JVM metrics
bean.register("jvm.gc", new GarbageCollectorMetricSet());
bean.register("jvm.memory", new MemoryUsageGaugeSet());
bean.register("jvm.thread-states", new ThreadStatesGaugeSet());
bean.register("jvm.fd", new FileDescriptorRatioGauge());
bean.register("jvm.load-average", new Gauge<Double>() {
private OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
public Double getValue() {
try {
return mxBean.getSystemLoadAverage();
} catch (Exception e) {
// not supported
return -1d;
}
}
});
// add Logback metrics
final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
final InstrumentedAppender appender = new InstrumentedAppender(bean);
appender.setContext(root.getLoggerContext());
appender.start();
root.addAppender(appender);
return bean;
}
@Override
public void setDetail() {
Runtime runt = Runtime.getRuntime();
int i = 0;
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
add(i++, new String[] { "JVM", "Available processors", "" + runt.availableProcessors() });
add(i++, new String[] { "Runtime", "Uptime", "" + NumFormat.time(rt.getUptime()*1e6) });
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
for (Method method : os.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
try {
String name = split(method.getName());
if (name.contains("Size"))
add(i++, new String[] { "OS", name, NumFormat.bytes(Double.parseDouble(method.invoke(os).toString())) });
else if (name.contains("Time"))
add(i++, new String[] { "OS", name, NumFormat.time(Double.parseDouble(method.invoke(os).toString())) });
else if (name.contains("Load"))
add(i++, new String[] { "OS", name, NumFormat.nice(100 * Double.parseDouble(method.invoke(os).toString()))+"%" });
else
add(i++, new String[] { "OS", name, "" + method.invoke(os).toString() });
}
catch (Exception e) {
}
}
}
}
public static double getLoad() {
try {
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
return os.getSystemLoadAverage();
}
catch (Exception ex) {
}
return 0;
}
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);
}