Example usage for java.lang.management ManagementFactory getOperatingSystemMXBean

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

Introduction

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

Prototype

public static OperatingSystemMXBean getOperatingSystemMXBean() 

Source Link

Document

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

Usage

From source file:net.centro.rtb.monitoringcenter.metrics.system.os.OperatingSystemMetricSet.java

public OperatingSystemMetricSet() {
    this.operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    this.rootFilePath = new File("/");

    // Set up iowait retrieval job if needed
    Double ioWaitPercentage = fetchIoWaitPercentage();
    if (ioWaitPercentage != null) {
        this.ioWaitPercentageHolder = new AtomicReference<>(ioWaitPercentage);

        this.executorService = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setNameFormat("OperatingSystemMetricSet-%d").build());
        this.executorService.scheduleWithFixedDelay(new Runnable() {
            @Override/*ww  w.  j  a va 2 s .  c  o  m*/
            public void run() {
                Double ioWaitPercentage = fetchIoWaitPercentage();
                if (ioWaitPercentage != null) {
                    ioWaitPercentageHolder.set(ioWaitPercentage);
                }
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

    // ----- Init and assign metrics -----
    this.metricsByNames = new HashMap<>();

    // Available everywhere
    this.availableLogicalProcessorsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return operatingSystemMXBean.getAvailableProcessors();
        }
    };
    metricsByNames.put("availableLogicalProcessors", availableLogicalProcessorsGauge);

    if (operatingSystemMXBean.getSystemLoadAverage() >= 0) { // Where available
        this.systemLoadAverageGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                return operatingSystemMXBean.getSystemLoadAverage();
            }
        };
        metricsByNames.put("systemLoadAverage", systemLoadAverageGauge);

        this.systemLoadAveragePerLogicalProcessorGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                return operatingSystemMXBean.getSystemLoadAverage()
                        / operatingSystemMXBean.getAvailableProcessors();
            }
        };
        metricsByNames.put("systemLoadAveragePerLogicalProcessor", systemLoadAveragePerLogicalProcessorGauge);
    }

    // Sun JVMs, incl. OpenJDK
    if (com.sun.management.OperatingSystemMXBean.class.isAssignableFrom(operatingSystemMXBean.getClass())) {
        final com.sun.management.OperatingSystemMXBean sunOsMxBean = com.sun.management.OperatingSystemMXBean.class
                .cast(operatingSystemMXBean);

        if (sunOsMxBean.getProcessCpuLoad() >= 0) {
            this.jvmCpuBusyPercentageGauge = new Gauge<Double>() {
                @Override
                public Double getValue() {
                    return sunOsMxBean.getProcessCpuLoad() * 100;
                }
            };
            metricsByNames.put("jvmCpuBusyPercentage", jvmCpuBusyPercentageGauge);
        }

        if (sunOsMxBean.getSystemCpuLoad() >= 0) {
            this.systemCpuBusyPercentageGauge = new Gauge<Double>() {
                @Override
                public Double getValue() {
                    return sunOsMxBean.getSystemCpuLoad() * 100;
                }
            };
            metricsByNames.put("systemCpuBusyPercentage", systemCpuBusyPercentageGauge);
        }

        if (sunOsMxBean.getCommittedVirtualMemorySize() >= 0) {
            this.committedVirtualMemorySizeInBytesGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return sunOsMxBean.getCommittedVirtualMemorySize();
                }
            };
            metricsByNames.put("committedVirtualMemorySizeInBytes", committedVirtualMemorySizeInBytesGauge);
        }

        // Physical Memory
        String physicalMemoryNamespace = "physicalMemory";

        this.totalPhysicalMemorySizeInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return sunOsMxBean.getTotalPhysicalMemorySize();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(physicalMemoryNamespace, "totalInBytes"),
                totalPhysicalMemorySizeInBytesGauge);

        this.freePhysicalMemorySizeInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return sunOsMxBean.getFreePhysicalMemorySize();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(physicalMemoryNamespace, "freeInBytes"),
                freePhysicalMemorySizeInBytesGauge);

        this.usedPhysicalMemoryPercentageGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                long totalPhysicalMemorySize = sunOsMxBean.getTotalPhysicalMemorySize();
                if (totalPhysicalMemorySize == 0) {
                    return 0.0;
                }

                long usedPhysicalMemorySize = totalPhysicalMemorySize - sunOsMxBean.getFreePhysicalMemorySize();
                return Double.valueOf(usedPhysicalMemorySize) / totalPhysicalMemorySize * 100;
            }
        };
        metricsByNames.put(MetricNamingUtil.join(physicalMemoryNamespace, "usedPercentage"),
                usedPhysicalMemoryPercentageGauge);

        // Swap Space
        String swapSpaceNamespace = "swapSpace";

        this.totalSwapSpaceSizeInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return sunOsMxBean.getTotalSwapSpaceSize();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(swapSpaceNamespace, "totalInBytes"),
                totalSwapSpaceSizeInBytesGauge);

        this.freeSwapSpaceSizeInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return sunOsMxBean.getFreeSwapSpaceSize();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(swapSpaceNamespace, "freeInBytes"),
                freeSwapSpaceSizeInBytesGauge);

        this.usedSwapSpacePercentageGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                long totalSwapSpaceSize = sunOsMxBean.getTotalSwapSpaceSize();
                if (totalSwapSpaceSize == 0) {
                    return 0.0;
                }

                long usedSwapSpaceSize = totalSwapSpaceSize - sunOsMxBean.getFreeSwapSpaceSize();
                return Double.valueOf(usedSwapSpaceSize) / totalSwapSpaceSize * 100;
            }
        };
        metricsByNames.put(MetricNamingUtil.join(swapSpaceNamespace, "usedPercentage"),
                usedSwapSpacePercentageGauge);
    }

    // File descriptors (e.g., sockets)
    String fileDescriptorsNamespace = "fileDescriptors";

    if (UnixOperatingSystemMXBean.class.isAssignableFrom(operatingSystemMXBean.getClass())) {
        final UnixOperatingSystemMXBean unixOsMxBean = UnixOperatingSystemMXBean.class
                .cast(operatingSystemMXBean);

        this.maxFileDescriptorsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return unixOsMxBean.getMaxFileDescriptorCount();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(fileDescriptorsNamespace, "max"), maxFileDescriptorsGauge);

        this.openFileDescriptorsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return unixOsMxBean.getOpenFileDescriptorCount();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(fileDescriptorsNamespace, "open"), openFileDescriptorsGauge);

        this.usedFileDescriptorsPercentageGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                long maxFileDescriptors = unixOsMxBean.getMaxFileDescriptorCount();
                if (maxFileDescriptors == 0) {
                    return 0.0;
                }
                return Double.valueOf(unixOsMxBean.getOpenFileDescriptorCount()) / maxFileDescriptors * 100;
            }
        };
        metricsByNames.put(MetricNamingUtil.join(fileDescriptorsNamespace, "usedPercentage"),
                usedFileDescriptorsPercentageGauge);
    }

    // Disk space
    String diskSpaceNamespace = "diskSpace";

    if (rootFilePath.getTotalSpace() > 0) {
        this.totalDiskSpaceInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return rootFilePath.getTotalSpace();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(diskSpaceNamespace, "totalInBytes"),
                totalDiskSpaceInBytesGauge);

        this.freeDiskSpaceInBytesGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return rootFilePath.getFreeSpace();
            }
        };
        metricsByNames.put(MetricNamingUtil.join(diskSpaceNamespace, "freeInBytes"), freeDiskSpaceInBytesGauge);

        this.usedDiskSpacePercentageGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                long totalDiskSpace = rootFilePath.getTotalSpace();
                if (totalDiskSpace == 0) {
                    return 0.0;
                }

                long usedDiskSpace = totalDiskSpace - rootFilePath.getFreeSpace();
                return Double.valueOf(usedDiskSpace) / totalDiskSpace * 100;
            }
        };
        metricsByNames.put(MetricNamingUtil.join(diskSpaceNamespace, "usedPercentage"),
                usedDiskSpacePercentageGauge);
    }

    // CPU IO Wait
    if (ioWaitPercentageHolder != null) {
        this.ioWaitPercentageGauge = new Gauge<Double>() {
            @Override
            public Double getValue() {
                return ioWaitPercentageHolder.get();
            }
        };
        metricsByNames.put("ioWaitPercentage", ioWaitPercentageGauge);
    }

    this.shutdown = new AtomicBoolean(false);
}

From source file:io.hawkcd.agent.AgentConfiguration.java

private static void configureEnvironmentInfo() {
    File file = new File("/");
    int gb = 1024 * 1024 * 1024;

    environmentInfo.setOsName(System.getProperty("os.name"));
    environmentInfo.setTotalDiskSpaceGBytes(file.getFreeSpace() / gb);
    environmentInfo.setFreeDiskSpaceGBytes(file.getTotalSpace() / gb);
    environmentInfo.setTotalRamMBytes(//from  ww  w .j  av  a 2 s. co m
            ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize()
                    * 1024);
    environmentInfo.setFreeRamMBytes(
            ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getFreePhysicalMemorySize()
                    * 1024);
}

From source file:com.kixeye.chassis.support.ChassisConfiguration.java

/**
 * Initializes the metrics registry/* w  ww .  ja  va  2 s .c om*/
 *
 * @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;
}

From source file:org.craftercms.commons.monitoring.VersionMonitor.java

private void initOS() {
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    operating_system = os.getName() + "-" + os.getVersion();
    os_architecture = os.getArch();//  www  .  java 2  s . co  m
    system_encoding = System.getProperty(FILE_ENCODING_SYSTEM_PROP_KEY);
}

From source file:edu.harvard.i2b2.eclipse.Application.java

/**
 * Method to check the maximum heap size and the physical memory size
 * // ww  w  .  j  av  a2  s.c o m
 * @return  true/false
 * 
 * 
 */
private boolean checkMemorySetting() {
    boolean status = true;

    OperatingSystemMXBean mxbean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    long memory = mxbean.getTotalPhysicalMemorySize() / 1000000;

    //RuntimeMXBean mxbean1 = ManagementFactory.getRuntimeMXBean();

    long vmSize = Runtime.getRuntime().maxMemory() / 1000000;//getXmxFromi2b2Properties();

    if (memory < vmSize) {
        status = false;

        Shell activeShell = new Shell();

        //java.lang.management.OperatingSystemMXBean mxbean =  ManagementFactory.getOperatingSystemMXBean();
        //System.out.println("In Application total physical memory: "+(mxbean.getTotalPhysicalMemorySize()/1000000));

        MessageBox mBox = new MessageBox(activeShell, SWT.ICON_INFORMATION | SWT.OK);
        mBox.setText(Messages.getString("Application.MemoryPopup")); //$NON-NLS-1$
        mBox.setMessage(Messages.getString("Application.MemoryPopupText1") + memory //$NON-NLS-1$
                + Messages.getString("Application.MemoryPopupText2") //$NON-NLS-1$
                + Messages.getString("Application.MemoryPopupText3") + vmSize //$NON-NLS-1$
                + Messages.getString("Application.MemoryPopupText4") //$NON-NLS-1$
                + Messages.getString("Application.MemoryPopupText5") //$NON-NLS-1$
                + Messages.getString("Application.MemoryPopupText6")); //$NON-NLS-1$
        mBox.open();
    }

    return status;
}

From source file:com.spotify.reaper.service.SegmentRunner.java

/**
 * This method is intended to be temporary, until we find the root issue of too many open files
 * issue.//ww  w  .  jav a  2s .  c om
 */
private long getOpenFilesAmount() {
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    long amountOfOpenFiles = -1;
    if (os instanceof UnixOperatingSystemMXBean) {
        amountOfOpenFiles = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
    }
    return amountOfOpenFiles;
}

From source file:org.artifactory.webapp.wicket.page.config.advanced.SystemInfoPage.java

/**
 * Return a formatted string of the system info to display
 *
 * @return//ww w. ja va 2 s.c  o  m
 */
private String collectSystemInfo() {
    StringBuilder infoBuilder = new StringBuilder();

    StorageProperties storageProperties = ContextHelper.get().beanForType(StorageProperties.class);
    infoBuilder.append("Storage Info:").append("\n");
    addInfo(infoBuilder, "Database Type", storageProperties.getDbType().toString());
    BinaryProviderType binariesStorageType = storageProperties.getBinariesStorageType();
    addInfo(infoBuilder, "Storage Type", binariesStorageType.toString());
    if (BinaryProviderType.S3 == binariesStorageType) {
        // S3 properties
        addInfo(infoBuilder, "s3.bucket.name", storageProperties.getS3BucketName());
        addInfo(infoBuilder, "s3.bucket.path", storageProperties.getS3BucketPath());
        addInfo(infoBuilder, "s3.endpoint", storageProperties.getS3Entpoint());
        // Retry properties
        addInfo(infoBuilder, "retry.max.retries.number",
                Integer.toString(storageProperties.getMaxRetriesNumber()));
        addInfo(infoBuilder, "retry.delay.between.retries",
                Integer.toString(storageProperties.getDelayBetweenRetries()));
        // Eventually persisted properties
        addInfo(infoBuilder, "eventually.persisted.max.number.of.threads",
                Integer.toString(storageProperties.getEventuallyPersistedMaxNumberOfThread()));
        addInfo(infoBuilder, "eventually.persisted.timeout",
                Integer.toString(storageProperties.getEventuallyPersistedTimeOut()));
        addInfo(infoBuilder, "eventually.dispatcher.sleep.time",
                Long.toString(storageProperties.getEventuallyPersistedDispatcherSleepTime()));
    }

    infoBuilder.append("\n").append("System Properties:").append("\n");
    Properties properties = System.getProperties();
    //// add Artifactory version to the properties, will be alphabetically sorted later.
    properties.setProperty(ConstantValues.artifactoryVersion.getPropertyName(),
            ConstantValues.artifactoryVersion.getString());
    AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
    addInfo(infoBuilder, "artifactory.running.mode", addonsManager.getArtifactoryRunningMode().name());
    addInfo(infoBuilder, "artifactory.running.state", ContextHelper.get().isOffline() ? "Offline" : "Online");
    addFromProperties(infoBuilder, properties);
    addHaProperties(infoBuilder);
    infoBuilder.append("\n").append("General JVM Info:").append("\n");
    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    addInfo(infoBuilder, "Available Processors", Integer.toString(systemBean.getAvailableProcessors()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();

    addInfo(infoBuilder, "Heap Memory Usage-Committed", Long.toString(heapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Heap Memory Usage-Init", Long.toString(heapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Heap Memory Usage-Max", Long.toString(heapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Heap Memory Usage-Used", Long.toString(heapMemoryUsage.getUsed()));

    MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
    addInfo(infoBuilder, "Non-Heap Memory Usage-Committed", Long.toString(nonHeapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Init", Long.toString(nonHeapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Max", Long.toString(nonHeapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Used", Long.toString(nonHeapMemoryUsage.getUsed()));

    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    StringBuilder vmArgumentBuilder = new StringBuilder();
    List<String> vmArguments = RuntimemxBean.getInputArguments();
    if (vmArguments != null) {
        for (String vmArgument : vmArguments) {
            if (InfoWriter.shouldMaskValue(vmArgument)) {
                vmArgument = Strings.maskKeyValue(vmArgument);
            }
            vmArgumentBuilder.append(vmArgument);
            if (vmArguments.indexOf(vmArgument) != (vmArguments.size() - 1)) {
                vmArgumentBuilder.append("\n");
            }
        }
    }

    infoBuilder.append("\nJVM Arguments:\n").append(vmArgumentBuilder.toString());

    return StringUtils.removeEnd(infoBuilder.toString(), "\n");
}

From source file:com.janrain.backplane.server.metrics.MetricsAccumulator.java

private Map<String, Object> outputJVMUsage() {

    long mb = 1048576;

    Map<String, Object> out = new LinkedHashMap<String, Object>();

    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    int totalLiveThreads = ManagementFactory.getThreadMXBean().getThreadCount();
    double loadAverage = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
    MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    String startTimeString = BackplaneConfig.ISO8601.format(new Date(startTime));

    out.put("type", "jvm");
    out.put("unit", "mb");
    out.put("heap_used", mu.getUsed() / mb);
    out.put("heap_free", (mu.getMax() - mu.getUsed()) / mb);
    out.put("heap_max", mu.getMax() / mb);
    out.put("jvm_start_time", startTimeString);
    out.put("total_live_threads", totalLiveThreads);
    out.put("load_average_minute", String.format("%2.2f", loadAverage));

    return out;//w w  w .j av a  2 s .  c o m

}

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

@Scheduled(fixedRate = 5000, initialDelay = 2000)
public void emitVmVitals() {
    OperatingSystemMXBean mbean = ManagementFactory.getOperatingSystemMXBean();
    String prefix = "vitals.vm.";
    statsDClient.gauge(prefix + "cpu.count", mbean.getAvailableProcessors());
    statsDClient.gauge(prefix + "cpu.load", (long) (mbean.getSystemLoadAverage() * 100));
    invokeIfPresent(prefix + "memory.total", mbean, "getTotalPhysicalMemorySize");
    invokeIfPresent(prefix + "memory.committed", mbean, "getCommittedVirtualMemorySize");
    invokeIfPresent(prefix + "memory.free", mbean, "getFreePhysicalMemorySize");
}

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

public String getFetchProcessMaxMemory() {
    String maxMemory = getExplicitFetchProcessMaxMemory();
    if (!isEmpty(maxMemory))
        return maxMemory;
    try {/* www. j  a  v  a2 s  . c o  m*/
        Class.forName("com.sun.management.OperatingSystemMXBean");
    } catch (ClassNotFoundException e) {
        return "512M";
    }
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
        long freeRAM = ((com.sun.management.OperatingSystemMXBean) osBean).getFreePhysicalMemorySize();
        if (freeRAM > GB)
            return "1024M";
    }
    return "512M";
}