Java Code Examples for java.lang.management.OperatingSystemMXBean

The following are top voted examples for showing how to use java.lang.management.OperatingSystemMXBean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: CentauriCloud   File: LoadTimer.java   Source Code and License 7 votes vote down vote up
private void sendLoad() {
	long freeRam = 0;
	double cpuLoad = 0;

	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
		method.setAccessible(true);
		if (method.getName().startsWith("get")
				&& Modifier.isPublic(method.getModifiers())) {
			Object value = 0;
			try {
				value = method.invoke(operatingSystemMXBean);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (method.getName().equals("getFreePhysicalMemorySize"))
				freeRam = (long) value;
			if (method.getName().equals("getSystemCpuLoad"))
				cpuLoad = (double) value;
		}
	}

	Daemon.getInstance().getClient().getChannel().writeAndFlush(new PacketServerLoad(freeRam, cpuLoad));
}
 
Example 2
Project: MantaroRPG   File: AsyncInfoMonitor.java   Source Code and License 7 votes vote down vote up
public static void start() {
	if (started) throw new IllegalStateException("Already Started.");
	OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
	ThreadMXBean thread = ManagementFactory.getThreadMXBean();
	Runtime r = Runtime.getRuntime();
	int mb = 0x100000;

	lastSystemTime = System.nanoTime();
	lastProcessCpuTime = calculateProcessCpuTime(os);

	Async.task("AsyncInfoMonitorThread", () -> {
		threadCount = thread.getThreadCount();
		availableProcessors = r.availableProcessors();
		freeMemory = Runtime.getRuntime().freeMemory() / mb;
		maxMemory = Runtime.getRuntime().maxMemory() / mb;
		totalMemory = Runtime.getRuntime().totalMemory() / mb;
		cpuUsage = calculateCpuUsage(os);
		vpsCPUUsage = getVpsCPUUsage(os);
		vpsFreeMemory = calculateVPSFreeMemory(os);
		vpsMaxMemory = calculateVPSMaxMemory(os);
		vpsUsedMemory = vpsMaxMemory - vpsFreeMemory;
	}, 1);
	started = true;
}
 
Example 3
Project: Java-Snippets   File: EnvironmentInfo.java   Source Code and License 7 votes vote down vote up
public static void getOsInfo() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    //os general info
    String osName = osBean.getName();
    String osVersion = osBean.getVersion();
    String osArch = osBean.getArch();

    //CPU
    int cores = osBean.getAvailableProcessors();
    String cpuName = System.getenv("PROCESSOR_IDENTIFIER");
    //only on *nix systems
    double loadAvg = osBean.getSystemLoadAverage();

    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        getExtendedOsInfo((com.sun.management.OperatingSystemMXBean) osBean);
    }
}
 
Example 4
Project: incubator-servicecomb-java-chassis   File: MetricsServoRegistry.java   Source Code and License 6 votes vote down vote up
@Override
public String call() {
  Map<String, String> memoryMap = new HashMap<>();
  OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
  double cpu = osMxBean.getSystemLoadAverage();
  memoryMap.put("cpuLoad", String.format(doubleStringFormatter, round(cpu, doubleRoundPlaces)));

  ThreadMXBean threadmxBean = ManagementFactory.getThreadMXBean();
  int threadCount = threadmxBean.getThreadCount();
  memoryMap.put("cpuRunningThreads", String.valueOf(threadCount));

  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage memHeapUsage = memBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memBean.getNonHeapMemoryUsage();
  memoryMap.put("heapInit", String.valueOf(memHeapUsage.getInit()));
  memoryMap.put("heapMax", String.valueOf(memHeapUsage.getMax()));
  memoryMap.put("heapCommit", String.valueOf(memHeapUsage.getCommitted()));
  memoryMap.put("heapUsed", String.valueOf(memHeapUsage.getUsed()));
  memoryMap.put("nonHeapInit", String.valueOf(nonHeapUsage.getInit()));
  memoryMap.put("nonHeapMax", String.valueOf(nonHeapUsage.getMax()));
  memoryMap.put("nonHeapCommit", String.valueOf(nonHeapUsage.getCommitted()));
  memoryMap.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed()));
  return memoryMap.toString();
}
 
Example 5
Project: rapidminer   File: SystemInfoUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * Returns free physical memory in MB. If it is run in a 32-bit JVM it may return only a maximum
 * of 2GB even if more memory is available.
 * <p>
 * <strong>Attention:</strong> The returned value is dependant on the OS. For example on Linux
 * you might see less memory than there is actually available due to the OS using it for disk
 * caching. That memory is not actually blocked because the OS would release it if requested,
 * however this method will return the free memory which does NOT contain the ram used for disk
 * caching. Use with care!
 * </p>
 *
 * @return the free phsycial memory in MB or <code>-1</code> if we cannot determine it
 * @since 6.0.004
 *
 */
public static Long getFreePhysicalMemorySize() {
	OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();

	long memory = 0L;

	// if the system bean is an implementation by sun, we are almost done
	try {
		memory = ((com.sun.management.OperatingSystemMXBean) operatingSystemBean).getFreePhysicalMemorySize();
	} catch (Throwable t) { // NOPMD
		// fallback due to sun implementation not being available
		// in this case we behave as before 6.0.004 where we did not take free memory into
		// account
		return -1L;
	}

	memory /= TENTH_POWER_OF_TWO; // kbyte
	memory /= TENTH_POWER_OF_TWO; // mbyte
	return memory;
}
 
Example 6
Project: mycat-src-1.6.1-RELEASE   File: EnvironmentInformation.java   Source Code and License 6 votes vote down vote up
/**
 * The maximum JVM heap size, in bytes.
 * 
 * @return The maximum JVM heap size, in bytes.
 */
public static long getMaxJvmHeapMemory() {
	long maxMemory = Runtime.getRuntime().maxMemory();

	if (maxMemory == Long.MAX_VALUE) {
		// amount of free memory unknown
		try {
			// workaround for Oracle JDK
			OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
			Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
			Method method = clazz.getMethod("getTotalPhysicalMemorySize");
			maxMemory = (Long) method.invoke(operatingSystemMXBean) / 4;
		}
		catch (Throwable e) {
			throw new RuntimeException("Could not determine the amount of free memory.\n" +
					"Please set the maximum memory for the JVM, e.g. -Xmx512M for 512 megabytes.");
		}
	}
	
	return maxMemory;
}
 
Example 7
Project: mycat-src-1.6.1-RELEASE   File: EnvironmentInformation.java   Source Code and License 6 votes vote down vote up
/**
 * Gets an estimate of the size of the free heap memory. The estimate may vary, depending on the current
 * level of memory fragmentation and the number of dead objects. For a better (but more heavy-weight)
 * estimate, use {@link #getSizeOfFreeHeapMemoryWithDefrag()}.
 * 
 * @return An estimate of the size of the free heap memory, in bytes.
 */
public static long getSizeOfFreeHeapMemory() {
	Runtime r = Runtime.getRuntime();
	long maxMemory = r.maxMemory();

	if (maxMemory == Long.MAX_VALUE) {
		// amount of free memory unknown
		try {
			// workaround for Oracle JDK
			OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
			Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
			Method method = clazz.getMethod("getTotalPhysicalMemorySize");
			maxMemory = (Long) method.invoke(operatingSystemMXBean) / 4;
		} catch (Throwable e) {
			throw new RuntimeException("Could not determine the amount of free memory.\n" +
					"Please set the maximum memory for the JVM, e.g. -Xmx512M for 512 megabytes.");
		}
	}

	return maxMemory - r.totalMemory() + r.freeMemory();
}
 
Example 8
Project: micrometer   File: ProcessorMetrics.java   Source Code and License 6 votes vote down vote up
@Override
public void bindTo(MeterRegistry registry) {
    Runtime runtime = Runtime.getRuntime();

    Gauge.builder("system.cpu.count", runtime, Runtime::availableProcessors)
        .tags(tags)
        .description("The number of processors available to the Java virtual machine")
        .register(registry);

    OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
    if(operatingSystemBean != null && operatingSystemBean.getSystemLoadAverage() >= 0) {
        Gauge.builder("system.load.average.1m", operatingSystemBean, OperatingSystemMXBean::getSystemLoadAverage)
            .tags(tags)
            .description("The sum of the number of runnable entities queued to available processors and the number " +
                "of runnable entities running on the available processors averaged over a period of time")
            .register(registry);
    }
}
 
Example 9
Project: traccar-service   File: Log.java   Source Code and License 6 votes vote down vote up
public static void logSystemInfo() {
    try {
        OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
        Log.info("Operating system"
                + " name: " + operatingSystemBean.getName()
                + " version: " + operatingSystemBean.getVersion()
                + " architecture: " + operatingSystemBean.getArch());

        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        Log.info("Java runtime"
                + " name: " + runtimeBean.getVmName()
                + " vendor: " + runtimeBean.getVmVendor()
                + " version: " + runtimeBean.getVmVersion());

        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        Log.info("Memory limit"
                + " heap: " + memoryBean.getHeapMemoryUsage().getMax() / (1024 * 1024) + "mb"
                + " non-heap: " + memoryBean.getNonHeapMemoryUsage().getMax() / (1024 * 1024) + "mb");

        Log.info("Character encoding: "
                + System.getProperty("file.encoding") + " charset: " + Charset.defaultCharset());

    } catch (Exception error) {
        Log.warning("Failed to get system info");
    }
}
 
Example 10
Project: OneClient   File: OperatingSystem.java   Source Code and License 6 votes vote down vote up
private static long getOSMemory(String methodName, String warning) {
	long ram = 0;
	OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
	Method 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 {
			OneClientLogging.logger.warn(warning);
			ram = 1024;
		}
	} catch (Exception e) {
		OneClientLogging.error(e);
	}

	return ram;
}
 
Example 11
Project: uavstack   File: JVMToolHelper.java   Source Code and License 6 votes vote down vote up
public static Map<String, Double> readCPUUsage(OperatingSystemMXBean osMBean) {

        Map<String, Double> m = new LinkedHashMap<String, Double>();

        Double procCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getProcessCpuLoad", null, null);
        Double systemCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getSystemCpuLoad", null, null);

        if (procCPU == null) {
            procCPU = getProcessCpuUtilization();
            systemCPU = -1D;
        }

        DecimalFormat formatter = new DecimalFormat("00.0");

        m.put("cpu_p", Double.valueOf(formatter.format(procCPU * 100)));
        m.put("cpu_s", Double.valueOf(formatter.format(systemCPU * 100)));

        return m;
    }
 
Example 12
Project: uavstack   File: JVMToolHelper.java   Source Code and License 6 votes vote down vote up
/**
 * obtain current process cpu utilization if jdk version is 1.6 by-hongqiangwei
 */
@SuppressWarnings("restriction")
public static double getProcessCpuUtilization() {

    com.sun.management.OperatingSystemMXBean osMBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    long processCpuTime1 = osMBean.getProcessCpuTime();
    long runtime1 = runtimeMXBean.getUptime();

    ThreadHelper.suspend(50);

    long processCpuTime2 = osMBean.getProcessCpuTime();
    long runtime2 = runtimeMXBean.getUptime();

    long deltaProcessTime = processCpuTime2 - processCpuTime1;
    long deltaRunTime = (runtime2 - runtime1) * 1000000L;
    int cpuNumber = Runtime.getRuntime().availableProcessors();
    double cpuUtilization = (double) deltaProcessTime / (deltaRunTime * cpuNumber);

    return cpuUtilization;
}
 
Example 13
Project: uavstack   File: JVMStateCapHandler.java   Source Code and License 6 votes vote down vote up
protected void readCPUUsage(MonitorElementInstance inst) {

        OperatingSystemMXBean osMBean = ManagementFactory.getOperatingSystemMXBean();
        Double procCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getProcessCpuLoad", null, null);
        Double systemCPU = (Double) ReflectionHelper.invoke("com.sun.management.OperatingSystemMXBean", osMBean,
                "getSystemCpuLoad", null, null);

        if (procCPU == null) {
            procCPU = JVMToolHelper.getProcessCpuUtilization();
            systemCPU = -1D;
        }

        inst.setValue("cpu_p", Double.valueOf(formatter.format(procCPU * 100)));
        inst.setValue("cpu_s", Double.valueOf(formatter.format(systemCPU * 100)));
    }
 
Example 14
Project: GabrielBot   File: AsyncInfoMonitor.java   Source Code and License 6 votes vote down vote up
public static void start() {
    if (started) throw new IllegalStateException("Already Started.");
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean thread = ManagementFactory.getThreadMXBean();
    Runtime r = Runtime.getRuntime();
    int mb = 0x100000;

    lastSystemTime = System.nanoTime();
    lastProcessCpuTime = calculateProcessCpuTime(os);

    Async.task("AsyncInfoMonitorThread", () -> {
        threadCount = thread.getThreadCount();
        availableProcessors = r.availableProcessors();
        freeMemory = Runtime.getRuntime().freeMemory() / mb;
        maxMemory = Runtime.getRuntime().maxMemory() / mb;
        totalMemory = Runtime.getRuntime().totalMemory() / mb;
        cpuUsage = calculateCpuUsage(os);
        vpsCPUUsage = getVpsCPUUsage(os);
        vpsFreeMemory = calculateVPSFreeMemory(os);
        vpsMaxMemory = calculateVPSMaxMemory(os);
        vpsUsedMemory = vpsMaxMemory - vpsFreeMemory;
    }, 1);
    started = true;
}
 
Example 15
Project: ThriftyPaxos   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Scale the value with the available memory. If 1 GB of RAM is available,
 * the value is returned, if 2 GB are available, then twice the value, and
 * so on.
 *
 * @param value the value to scale
 * @return the scaled value
 */
public static int scaleForAvailableMemory(int value) {
    long maxMemory = Runtime.getRuntime().maxMemory();
    if (maxMemory != Long.MAX_VALUE) {
        // we are limited by an -XmX parameter
        return (int) (value * maxMemory / (1024 * 1024 * 1024));
    }
    try {
        OperatingSystemMXBean mxBean = ManagementFactory
                .getOperatingSystemMXBean();
        // this method is only available on the class
        // com.sun.management.OperatingSystemMXBean, which mxBean
        // is an instance of under the Oracle JDK, but it is not present on
        // Android and other JDK's
        Method method = Class.forName(
                "com.sun.management.OperatingSystemMXBean").
                getMethod("getTotalPhysicalMemorySize");
        long physicalMemorySize = ((Number) method.invoke(mxBean)).longValue();
        return (int) (value * physicalMemorySize / (1024 * 1024 * 1024));
    } catch (Exception e) {
        // ignore
    }
    return value;
}
 
Example 16
Project: stallion-core   File: HealthInfo.java   Source Code and License 6 votes vote down vote up
public HealthInfo hydrateSystemHealth() {
    Runtime rt = Runtime.getRuntime();
    long memUsage = (rt.totalMemory() - rt.freeMemory());
    long usedMB = memUsage / 1024 / 1024;
    system.setJvmMemoryUsage(memUsage);
    system.setJvmMemoryUsageMb(usedMB);
    system.setDiskFreeAppDirectory(new File(Settings.instance().getTargetFolder()).getUsableSpace());
    system.setDiskFreeDataDirectory(new File(Settings.instance().getDataDirectory()).getUsableSpace());
    system.setDiskFreeDataDirectoryMb(new File(Settings.instance().getDataDirectory()).getUsableSpace() / 1024 / 1024);
    system.setDiskFreeLogDirectory(new File("/tmp").getUsableSpace());
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    if(os instanceof UnixOperatingSystemMXBean){
        UnixOperatingSystemMXBean unixBean = (UnixOperatingSystemMXBean) os;
        //unixBean.
        // get system load
        // get process CPU load

        system.setFileHandlesOpen(unixBean.getOpenFileDescriptorCount());
    }
    return this;
}
 
Example 17
Project: bigstreams   File: QuorumBase.java   Source Code and License 6 votes vote down vote up
@Override
public void tearDown() throws Exception {
    LOG.info("TearDown started");
    
    OperatingSystemMXBean osMbean =
        ManagementFactory.getOperatingSystemMXBean();
    if (osMbean != null && osMbean instanceof UnixOperatingSystemMXBean) {
        UnixOperatingSystemMXBean unixos =
            (UnixOperatingSystemMXBean)osMbean;
        LOG.info("fdcount after test is: "
                + unixos.getOpenFileDescriptorCount());
    }

    shutdownServers();

    for (String hp : hostPort.split(",")) {
        Assert.assertTrue("waiting for server down",
                   ClientBase.waitForServerDown(hp,
                                       ClientBase.CONNECTION_TIMEOUT));
        LOG.info(hp + " is no longer accepting client connections");
    }

    JMXEnv.tearDown();
}
 
Example 18
Project: bigstreams   File: QuorumBase.java   Source Code and License 6 votes vote down vote up
@Override
public void tearDown() throws Exception {
    LOG.info("TearDown started");
    
    OperatingSystemMXBean osMbean =
        ManagementFactory.getOperatingSystemMXBean();
    if (osMbean != null && osMbean instanceof UnixOperatingSystemMXBean) {
        UnixOperatingSystemMXBean unixos =
            (UnixOperatingSystemMXBean)osMbean;
        LOG.info("fdcount after test is: "
                + unixos.getOpenFileDescriptorCount());
    }

    shutdownServers();

    for (String hp : hostPort.split(",")) {
        Assert.assertTrue("waiting for server down",
                   ClientBase.waitForServerDown(hp,
                                       ClientBase.CONNECTION_TIMEOUT));
        LOG.info(hp + " is no longer accepting client connections");
    }

    JMXEnv.tearDown();
}
 
Example 19
Project: JavaGraphicsEngine   File: PerformanceMonitor.java   Source Code and License 6 votes vote down vote up
public synchronized double getProcessorUsage() {
	if (lastSystemTime == 0) {
		baselineCounters();
		return -1;
	}
	
	long systemTime = System.nanoTime();
	long processCPUTime = 0;
	
	if ( bean instanceof com.sun.management.OperatingSystemMXBean )
		processCPUTime = ( (com.sun.management.OperatingSystemMXBean) bean).getProcessCpuTime();
	
	double cpuUsage = (processCPUTime - lastProcessCPUTime) / ((double) (systemTime - lastSystemTime));
	lastSystemTime = systemTime;
	lastProcessCPUTime = processCPUTime;
	
	return cpuUsage / availableProcessors;
}
 
Example 20
Project: scelight   File: LUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the system info.
 * 
 * @return the system info
 */
public static SysInfoBean getSysInfo() {
	final SysInfoBean sysInfo = new SysInfoBean();
	
	final OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
	sysInfo.setOsName( bean.getName() );
	sysInfo.setOsVersion( bean.getVersion() );
	sysInfo.setAvailProcs( bean.getAvailableProcessors() );
	
	sysInfo.setUserName( System.getProperty( "user.name" ) );
	sysInfo.setUserCountry( System.getProperty( "user.country" ) );
	// Set time zone using TimeZone class, "user.timezone" property is not guaranteed to be present
	// (See javadoc of System.getProperties())
	sysInfo.setUserTimeZone( TimeZone.getDefault().getID() );
	
	sysInfo.setDate( new Date() );
	
	try {
		// On windows "/" is the root of the current drive, so use "c:/" instead
		sysInfo.setMainRootSize( Files.getFileStore( Paths.get( LEnv.OS == OpSys.WINDOWS ? "c:/" : "/" ) ).getTotalSpace() );
	} catch ( final IOException ie ) {
		LEnv.LOGGER.error( "Failed to get main root size!", ie );
	}
	
	return sysInfo;
}
 
Example 21
Project: Legacy-GN4R   File: SystemInfo.java   Source Code and License 6 votes vote down vote up
public void printUsage()
{
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods())
    {
        method.setAccessible(true);
        if (method.getName().startsWith("get")
                && Modifier.isPublic(method.getModifiers()))
        {
            Object value;
            try
            {
                value = method.invoke(operatingSystemMXBean);
            }
            catch (Exception e)
            {
                value = e;
            } // try
            System.out.println(method.getName() + " = " + value);
        } // if
    } // for
}
 
Example 22
Project: cibet   File: VMLoadControlJMXBean.java   Source Code and License 6 votes vote down vote up
private static synchronized int systemCpuLoadAvailable() {
   if (systemCpuLoadAvailable == -1) {
      Object systemLoad = retrieveLoadAttribute(SYSTEMATTRIBUTE);
      if (systemLoad == null) {
         OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
         double averageLoad = operatingSystemMXBean.getSystemLoadAverage();
         if (averageLoad >= 0) {
            log.info(
                  "System CPU load is measured with the Java method getSystemLoadAverage() of the OperatingSystemMXBean.");
            systemCpuLoadAvailable = 1;
         } else {
            log.warn("Unable to measure System CPU load on this operating system and Java VM");
            systemCpuLoadAvailable = 0;
         }

      } else {
         log.warn("System CPU load is measured with attribute " + SYSTEMATTRIBUTE + " of OperatingSystemMXBean. "
               + "This may be an expensive method dependend on the operating system and Java VM");
         systemCpuLoadAvailable = 2;
      }
   }
   return systemCpuLoadAvailable;
}
 
Example 23
Project: cibet   File: VMLoadControlJMXBean.java   Source Code and License 6 votes vote down vote up
@JMXBeanAttribute(name = "CPU: System Load Average (%)", description = "the recent cpu usage for the whole system. -1 if not available", sortValue = "f1")
public double getSystemCpuLoad() {
   switch (systemCpuLoadAvailable) {
   case 0:
      return -1;
   case 1:
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      double load = operatingSystemMXBean.getSystemLoadAverage() * 100
            / operatingSystemMXBean.getAvailableProcessors();
      return load;

   case 2:
      return (double) retrieveLoadAttribute(SYSTEMATTRIBUTE) * 100;

   default:
      return -1;
   }
}
 
Example 24
Project: little_mitm   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static long getOpenFileDescriptorsAndPrintMemoryUsage() {
    // Below courtesy of:
    // http://stackoverflow.com/questions/10999076/programmatically-print-the-heap-usage-that-is-typically-printed-on-jvm-exit-when
    MemoryUsage mu = ManagementFactory.getMemoryMXBean()
            .getHeapMemoryUsage();
    MemoryUsage muNH = ManagementFactory.getMemoryMXBean()
            .getNonHeapMemoryUsage();
    System.out.println("Init :" + mu.getInit() + "\nMax :" + mu.getMax()
            + "\nUsed :" + mu.getUsed() + "\nCommitted :"
            + mu.getCommitted() + "\nInit NH :" + muNH.getInit()
            + "\nMax NH :" + muNH.getMax() + "\nUsed NH:" + muNH.getUsed()
            + "\nCommitted NH:" + muNH.getCommitted());

    OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();

    if (osMxBean instanceof UnixOperatingSystemMXBean) {
        UnixOperatingSystemMXBean unixOsMxBean = (UnixOperatingSystemMXBean) osMxBean;
        return unixOsMxBean.getOpenFileDescriptorCount();
    } else {
        throw new UnsupportedOperationException("Unable to determine number of open file handles on non-Unix system");
    }
}
 
Example 25
Project: LagMonitor   File: EnvironmentCommand.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!isAllowed(sender, command)) {
        sender.sendMessage(ChatColor.DARK_RED + "Not whitelisted");
        return true;
    }

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

    //os general info
    sender.sendMessage(PRIMARY_COLOR + "OS Name: " + SECONDARY_COLOR + osBean.getName());
    sender.sendMessage(PRIMARY_COLOR + "Platform name: " + SECONDARY_COLOR + OS.getOs().getPlatformName());

    sender.sendMessage(PRIMARY_COLOR + "OS Version: " + SECONDARY_COLOR + osBean.getVersion());
    sender.sendMessage(PRIMARY_COLOR + "OS Arch: " + SECONDARY_COLOR + osBean.getArch());

    //CPU
    sender.sendMessage(PRIMARY_COLOR + "Cores: " + SECONDARY_COLOR + osBean.getAvailableProcessors());
    sender.sendMessage(PRIMARY_COLOR + "CPU: " + SECONDARY_COLOR + System.getenv("PROCESSOR_IDENTIFIER"));
    sender.sendMessage(PRIMARY_COLOR + "Load Average: " + SECONDARY_COLOR + osBean.getSystemLoadAverage());
    printExtendOsInfo(sender);

    displayDiskSpace(sender);
    return true;
}
 
Example 26
Project: LagMonitor   File: MonitorSaveTask.java   Source Code and License 6 votes vote down vote up
private int onMonitorSave(Storage storage) {
    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 == -1) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeData nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float procUsage = 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(procUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
 
Example 27
Project: rapidminer-studio   File: SystemInfoUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * Returns free physical memory in MB. If it is run in a 32-bit JVM it may return only a maximum
 * of 2GB even if more memory is available.
 * <p>
 * <strong>Attention:</strong> The returned value is dependant on the OS. For example on Linux
 * you might see less memory than there is actually available due to the OS using it for disk
 * caching. That memory is not actually blocked because the OS would release it if requested,
 * however this method will return the free memory which does NOT contain the ram used for disk
 * caching. Use with care!
 * </p>
 *
 * @return the free phsycial memory in MB or <code>-1</code> if we cannot determine it
 * @since 6.0.004
 *
 */
public static Long getFreePhysicalMemorySize() {
	OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();

	long memory = 0L;

	// if the system bean is an implementation by sun, we are almost done
	try {
		memory = ((com.sun.management.OperatingSystemMXBean) operatingSystemBean).getFreePhysicalMemorySize();
	} catch (Throwable t) { // NOPMD
		// fallback due to sun implementation not being available
		// in this case we behave as before 6.0.004 where we did not take free memory into
		// account
		return -1L;
	}

	memory /= TENTH_POWER_OF_TWO; // kbyte
	memory /= TENTH_POWER_OF_TWO; // mbyte
	return memory;
}
 
Example 28
Project: LagMonitor   File: MonitorSaveTask.java   Source Code and License 6 votes vote down vote up
private int onMonitorSave(Storage storage) {
    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 == -1) {
        //windows doesn't support this
        loadAvg = 0;
    }

    NativeData nativeData = plugin.getNativeData();
    float systemUsage = round(nativeData.getCPULoad() * 100, 4);
    float procUsage = 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(procUsage, systemUsage, freeRam, freeRamPct, freeOsRam, freeOsRamPct, loadAvg);
}
 
Example 29
Project: putnami-gradle-plugin   File: GwtCompileTask.java   Source Code and License 6 votes vote down vote up
private int evalWorkers(CompilerOption options) {
	long workers = Runtime.getRuntime().availableProcessors();
	OperatingSystemMXBean osMBean = ManagementFactory.getOperatingSystemMXBean();
	if (osMBean instanceof com.sun.management.OperatingSystemMXBean) {
		com.sun.management.OperatingSystemMXBean sunOsMBean = (com.sun.management.OperatingSystemMXBean) osMBean;
		long memPerWorker = 1024L * 1024L * options.getLocalWorkersMem();
		long nbFreeMemInGb = sunOsMBean.getFreePhysicalMemorySize() / memPerWorker;

		if (nbFreeMemInGb < workers) {
			workers = nbFreeMemInGb;
		}
		if (workers < 1) {
			workers = 1;
		}
	}
	return (int) workers;
}
 
Example 30
Project: search   File: SystemInfoHandlerTest.java   Source Code and License 6 votes vote down vote up
public void testMagickGetter() {

    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 addGetterIfAvaliable 
    SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
    SystemInfoHandler.addGetterIfAvaliable( os, "name", info2 );
    SystemInfoHandler.addGetterIfAvaliable( os, "version", info2 );
    SystemInfoHandler.addGetterIfAvaliable( os, "arch", info2 );
    
    // make sure they got the same thing
    assertEquals( info.toString(), info2.toString() );
  }
 
Example 31
Project: simple-boot   File: File.java   Source Code and License 6 votes vote down vote up
@Override
protected void doHealthCheck(final Builder builder)
        throws Exception {
    final OperatingSystemMXBean os = getOperatingSystemMXBean();
    if (os instanceof UnixOperatingSystemMXBean) {
        final UnixOperatingSystemMXBean unix
                = (UnixOperatingSystemMXBean) os;
        builder.withDetail("max-file-descriptors",
                unix.getMaxFileDescriptorCount()).
                withDetail("open-file-descriptors",
                        unix.getOpenFileDescriptorCount());
    }

    final java.io.File here = new java.io.File(".");
    builder.withDetail("usable-disk", here.getUsableSpace()).
            withDetail("total-disk", here.getTotalSpace());

    builder.up();
}
 
Example 32
Project: simple-boot   File: Memory.java   Source Code and License 6 votes vote down vote up
@Override
protected void doHealthCheck(final Builder builder)
        throws Exception {
    final OperatingSystemMXBean os = getOperatingSystemMXBean();
    if (os instanceof com.sun.management.OperatingSystemMXBean) {
        final com.sun.management.OperatingSystemMXBean oracle
                = (com.sun.management.OperatingSystemMXBean) os;
        builder.withDetail("committed-virtual-memory",
                oracle.getCommittedVirtualMemorySize()).
                withDetail("free-physical-memory",
                        oracle.getFreePhysicalMemorySize()).
                withDetail("free-swap-space",
                        oracle.getFreeSwapSpaceSize()).
                withDetail("total-physical-memory",
                        oracle.getTotalPhysicalMemorySize()).
                withDetail("total-swap-space",
                        oracle.getTotalSwapSpaceSize());
        builder.up();
    }
}
 
Example 33
Project: simple-boot   File: Cpu.java   Source Code and License 6 votes vote down vote up
@Override
protected void doHealthCheck(final Builder builder)
        throws Exception {
    final OperatingSystemMXBean os = getOperatingSystemMXBean();
    builder.withDetail("processors", os.getAvailableProcessors()).
            withDetail("system-loadavg", os.getSystemLoadAverage());

    if (os instanceof com.sun.management.OperatingSystemMXBean) {
        final com.sun.management.OperatingSystemMXBean oracle
                = (com.sun.management.OperatingSystemMXBean) os;
        builder.withDetail("process-cpu-load", oracle.getProcessCpuLoad()).
                withDetail("process-cpu-time",
                        ofNanos(oracle.getProcessCpuTime()).toString()).
                withDetail("system-cpu-load", oracle.getSystemCpuLoad());
    }

    builder.up();
}
 
Example 34
Project: gerrit   File: GetSummary.java   Source Code and License 6 votes vote down vote up
private JvmSummaryInfo getJvmSummary() {
  OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
  RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

  JvmSummaryInfo jvmSummary = new JvmSummaryInfo();
  jvmSummary.vmVendor = runtimeBean.getVmVendor();
  jvmSummary.vmName = runtimeBean.getVmName();
  jvmSummary.vmVersion = runtimeBean.getVmVersion();
  jvmSummary.osName = osBean.getName();
  jvmSummary.osVersion = osBean.getVersion();
  jvmSummary.osArch = osBean.getArch();
  jvmSummary.user = System.getProperty("user.name");

  try {
    jvmSummary.host = InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
    // Ignored
  }

  jvmSummary.currentWorkingDirectory = path(Paths.get(".").toAbsolutePath().getParent());
  jvmSummary.site = path(sitePath);
  return jvmSummary;
}
 
Example 35
Project: LagMonitor   File: EnvironmentCommand.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!isAllowed(sender, command)) {
        sender.sendMessage(ChatColor.DARK_RED + "Not whitelisted");
        return true;
    }

    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

    //os general info
    sender.sendMessage(PRIMARY_COLOR + "OS Name: " + SECONDARY_COLOR + osBean.getName());
    sender.sendMessage(PRIMARY_COLOR + "Platform name: " + SECONDARY_COLOR + OS.getOs().getPlatformName());

    sender.sendMessage(PRIMARY_COLOR + "OS Version: " + SECONDARY_COLOR + osBean.getVersion());
    sender.sendMessage(PRIMARY_COLOR + "OS Arch: " + SECONDARY_COLOR + osBean.getArch());

    //CPU
    sender.sendMessage(PRIMARY_COLOR + "Cores: " + SECONDARY_COLOR + osBean.getAvailableProcessors());
    sender.sendMessage(PRIMARY_COLOR + "CPU: " + SECONDARY_COLOR + System.getenv("PROCESSOR_IDENTIFIER"));
    sender.sendMessage(PRIMARY_COLOR + "Load Average: " + SECONDARY_COLOR + osBean.getSystemLoadAverage());
    printExtendOsInfo(sender);

    displayDiskSpace(sender);
    return true;
}
 
Example 36
Project: tEFMA   File: AbstractDoubleDescriptionImpl.java   Source Code and License 6 votes vote down vote up
private void logOptions(MetabolicNetwork metaNet, EfmOutputCallback callback) {
	final RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
	final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
	final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
	LOG.info("Elemetary flux mode computation");
	LOG.info("Implementation:");
	LOG.info("..algorithm name   : " + getImplName());
	LOG.info("..model type       : " + getFactoryName(mEfmModelFactory));
	LOG.info("..memory type      : " + getFactoryName(mMemoryFactory));
	LOG.info("..output type      : " + getCallbackName(callback));
	LOG.info("System:");
	LOG.info("..hostname         : " + getHostName());
	LOG.info("..operating system : " + osBean.getArch() + "/" + osBean.getName() + "/" + osBean.getVersion());
	LOG.info("..processors       : " + osBean.getAvailableProcessors());
	LOG.info("..vm               : " + rtBean.getVmVendor() + "/" + rtBean.getVmName() + "/" + rtBean.getVmVersion());
	LOG.info("..vm-spec          : " + rtBean.getSpecVendor() + "/" + rtBean.getSpecName() + "/" + rtBean.getSpecVersion());
	LOG.info("..vm arguments     : " + rtBean.getInputArguments());
	LOG.info("..memory, commited : " + (memBean.getHeapMemoryUsage().getCommitted() / 1000 / 1000) + "M");
	LOG.info("..memory, used     : " + (memBean.getHeapMemoryUsage().getUsed() / 1000 / 1000) + "M");
	mConfig.log(LOG, Level.INFO);
}
 
Example 37
Project: logspace   File: MemoryAgent.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(AgentOrder agentOrder) {
    OperatingSystemMXBean operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();

    if (!(operatingSystemBean instanceof com.sun.management.OperatingSystemMXBean)) {
        return;
    }

    com.sun.management.OperatingSystemMXBean operatingSystem = (com.sun.management.OperatingSystemMXBean) operatingSystemBean;

    OsEventBuilder osEventBuilder = createMemoryBuilder(this.getEventBuilderData());

    osEventBuilder.setTotalMemory(operatingSystem.getTotalPhysicalMemorySize());
    osEventBuilder.setFreeMemory(operatingSystem.getFreePhysicalMemorySize());
    osEventBuilder.setUsedMemory(operatingSystem.getTotalPhysicalMemorySize() - operatingSystem.getFreePhysicalMemorySize());
    osEventBuilder.setCommittedVirtualMemory(operatingSystem.getCommittedVirtualMemorySize());

    this.sendEvent(osEventBuilder.toEvent());
}
 
Example 38
Project: incubator-netbeans   File: CPUInfo.java   Source Code and License 5 votes vote down vote up
static void logCPUInfo() {
    LogRecord log = new LogRecord(Level.FINEST, MESSAGE); // NOI18N
    OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    Object [] params = new Object[]{bean.getAvailableProcessors()};
    log.setParameters(params);
    Logger.getLogger(Installer.UI_PERFORMANCE_LOGGER_NAME).log(log);
}
 
Example 39
Project: rapidminer   File: SystemInfoUtilities.java   Source Code and License 5 votes vote down vote up
/**
 * Returns total physical memory in MB. If it is run in a 32-bit JVM it may return only a
 * maximum of 4GB even if more memory is available.
 *
 * @return the amount of physical memory in MB
 * @throws IOException
 *             if something goes wrong
 */
public static Long getTotalPhysicalMemorySize() throws IOException {
	OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();

	long memory = 0L;

	// if the system bean is an implementation by sun, we are almost done
	try {
		memory = ((com.sun.management.OperatingSystemMXBean) operatingSystemBean).getTotalPhysicalMemorySize();
	} catch (Throwable t) {  // NOPMD
		// // fallback because sun implementation is not available
		switch (getOperatingSystem()) {
			case OSX:
				memory = readOSXTotalMemory();
				break;
			case WINDOWS:
				memory = readWindowsTotalMemory();
				break;
			case UNIX:
				memory = readUnixTotalMemory();
				break;
			case SOLARIS:
				memory = readSolarisTotalMemory();
				break;
			case OTHER:
			default:
				memory = readOtherTotalMemory();
				break;
		}
	}

	memory /= TENTH_POWER_OF_TWO; // kbyte
	memory /= TENTH_POWER_OF_TWO; // mbyte
	return memory;
}
 
Example 40
Project: elasticsearch_my   File: Probes.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 41
Project: EatDubbo   File: LoadStatusChecker.java   Source Code and License 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 42
Project: EatDubbo   File: LoadStatusChecker.java   Source Code and License 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 43
Project: EatDubbo   File: LoadStatusChecker.java   Source Code and License 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 44
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: StoreUtil.java   Source Code and License 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 45
Project: MantaroRPG   File: AsyncInfoMonitor.java   Source Code and License 5 votes vote down vote up
private static double calculateCpuUsage(OperatingSystemMXBean os) {
	long systemTime = System.nanoTime();
	double processCpuTime = calculateProcessCpuTime(os);

	double cpuUsage = (processCpuTime - lastProcessCpuTime) / ((double) (systemTime - lastSystemTime));

	lastSystemTime = systemTime;
	lastProcessCpuTime = processCpuTime;

	return cpuUsage / availableProcessors;
}
 
Example 46
Project: micrometer   File: FileDescriptorMetrics.java   Source Code and License 5 votes vote down vote up
FileDescriptorMetrics(OperatingSystemMXBean osBean, Iterable<Tag> tags) {
    this.osBean = requireNonNull(osBean);
    this.tags = tags;

    this.openFdsMethod = detectMethod("getOpenFileDescriptorCount");
    this.maxFdsMethod = detectMethod("getMaxFileDescriptorCount");
}
 
Example 47
Project: micrometer   File: FileDescriptorMetricsTest.java   Source Code and License 5 votes vote down vote up
@Test
@SuppressWarnings("restriction")
void fileDescriptorMetricsRuntime() {
    // currently only supporting HotSpot JVM
    final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean);

    final MeterRegistry registry = new SimpleMeterRegistry();
    new FileDescriptorMetrics().bindTo(registry);

    registry.mustFind("process.open.fds").gauge();
    registry.mustFind("process.max.fds").gauge();
}
 
Example 48
Project: micrometer   File: FileDescriptorMetricsTest.java   Source Code and License 5 votes vote down vote up
@Test
void fileDescriptorMetricsUnsupportedOsBeanMock() {
    final MeterRegistry registry = new SimpleMeterRegistry();
    final OperatingSystemMXBean osBean = mock(OperatingSystemMXBean.class);
    new FileDescriptorMetrics(osBean, Tags.zip("some", "tag")).bindTo(registry);

    assertThat(registry.mustFind("process.open.fds").tags("some", "tag")
        .gauge().value()).isEqualTo(Double.NaN);
    assertThat(registry.mustFind("process.max.fds").tags("some", "tag")
        .gauge().value()).isEqualTo(Double.NaN);
}
 
Example 49
Project: dubbo2   File: LoadStatusChecker.java   Source Code and License 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 50
Project: dubbo2   File: LoadStatusChecker.java   Source Code and License 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 51
Project: dubbo2   File: LoadStatusChecker.java   Source Code and License 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 52
Project: Endless   File: Stats.java   Source Code and License 5 votes vote down vote up
@Override
protected void execute(CommandEvent event)
{
    String title = ":information_source: Stats of **"+event.getSelfUser().getName()+"**:";
    Color color;
    String os = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getName();
    String arch = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getArch();
    String version = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getVersion();
    os = os+" "+arch+" "+version;
    int cpus = Runtime.getRuntime().availableProcessors();
    String processCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getProcessCpuLoad());
    String systemCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getSystemCpuLoad());
    long ramUsed = ((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()) / (1024 * 1024));

    if(event.isFromType(ChannelType.PRIVATE))
        color = Color.decode("#33ff00");
    else
        color = event.getGuild().getSelfMember().getColor();
    
    EmbedBuilder builder = new EmbedBuilder();
    builder.addField("<:windows:371075985996775425> OS: ", os, true);
    builder.addField(":computer: RAM usage: ", ramUsed+"MB", true);
    builder.addField(":gear: CPU usage: ", processCpuLoad+" / "+systemCpuLoad+" ("+cpus+" Cores)", true);
    builder.addField(":map: Guilds: ", ""+event.getJDA().getGuilds().size() , true);
    builder.addField(":speech_balloon: Text Channels: ", ""+event.getJDA().getTextChannels().size(), true);
    builder.addField(":speaker: Voice Channels: ", ""+event.getJDA().getVoiceChannels().size(), true);
    builder.addField(":bust_in_silhouette: Users: ", ""+event.getJDA().getUsers().size(), true);
    builder.setFooter(event.getSelfUser().getName(), event.getSelfUser().getEffectiveAvatarUrl());
    builder.setColor(color);
    event.getChannel().sendMessage(new MessageBuilder().append(title).setEmbed(builder.build()).build()).queue();
}
 
Example 53
Project: hekate   File: JvmMetricsProvider.java   Source Code and License 5 votes vote down vote up
@Override
public List<MetricConfigBase<?>> configureMetrics() {
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean threads = ManagementFactory.getThreadMXBean();

    return Arrays.asList(
        probe("jvm.mem.used", () -> usedMem() / MB),
        probe("jvm.mem.free", () -> freeMem() / MB),
        probe("jvm.mem.committed", () -> committedMem() / MB),
        probe("jvm.mem.max", () -> maxMem() / MB),
        probe("jvm.mem.nonheap.committed", () -> nonHeapCommittedMem() / MB),
        probe("jvm.mem.nonheap.used", () -> nonHeapUsedMem() / MB),
        probe("jvm.mem.heap.committed", () -> heapCommittedMem() / MB),
        probe("jvm.mem.heap.used", () -> heapUsedMem() / MB),
        probe("jvm.threads.live", threads::getThreadCount),
        probe("jvm.threads.daemon", threads::getDaemonThreadCount),
        probe("jvm.cpu.count", () -> Runtime.getRuntime().availableProcessors()),
        probe("jvm.cpu.load", () -> {
            double avg = os.getSystemLoadAverage();

            if (avg < 0) {
                return -1;
            } else {
                return (long)(avg * 100);
            }
        })
    );
}
 
Example 54
Project: reading-and-annotate-rocketmq-3.4.6   File: StoreUtil.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("restriction")
public static long getTotalPhysicalMemorySize() {
    long physicalTotal = 1024 * 1024 * 1024 * 24;
    OperatingSystemMXBean osmxb = ManagementFactory.getOperatingSystemMXBean();
    if (osmxb instanceof com.sun.management.OperatingSystemMXBean) {
        physicalTotal = ((com.sun.management.OperatingSystemMXBean) osmxb).getTotalPhysicalMemorySize();
    }

    return physicalTotal;
}
 
Example 55
Project: otter-G   File: OtterController.java   Source Code and License 5 votes vote down vote up
public String getNodeSystemInfo() {
    OperatingSystemMXBean mbean = ManagementFactory.getOperatingSystemMXBean();
    StringBuilder buf = new StringBuilder();
    buf.append("").append(mbean.getName()).append(' ').append(mbean.getVersion()).append(' ').append(mbean.getArch());
    buf.append(" @ ").append(mbean.getAvailableProcessors()).append(" cores");
    buf.append(" , 【 load average:").append(mbean.getSystemLoadAverage()).append(" 】");
    return buf.toString();
}
 
Example 56
Project: Elasticsearch   File: Probes.java   Source Code and License 5 votes vote down vote up
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 (Throwable t) {
            return -1;
        }
    }
    return -1;
}
 
Example 57
Project: jsf-sdk   File: LoadTelnetHandler.java   Source Code and License 5 votes vote down vote up
@Override
   public String telnet(Channel channel, String message) {
	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 "load:[" + load + "] cpu:[" + cpu + "]";
}
 
Example 58
Project: github-test   File: LoadStatusChecker.java   Source Code and License 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 59
Project: github-test   File: LoadStatusChecker.java   Source Code and License 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 60
Project: dubbox-hystrix   File: LoadStatusChecker.java   Source Code and License 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);
}