Search in sources :

Example 11 with OperatingSystemMXBean

use of java.lang.management.OperatingSystemMXBean in project nifi by apache.

the class SystemDiagnosticsFactory method create.

public SystemDiagnostics create(final FlowFileRepository flowFileRepo, final ContentRepository contentRepo, ProvenanceRepository provenanceRepository) {
    final SystemDiagnostics systemDiagnostics = new SystemDiagnostics();
    final MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
    final MemoryUsage heap = memory.getHeapMemoryUsage();
    final MemoryUsage nonHeap = memory.getNonHeapMemoryUsage();
    final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    final ThreadMXBean threads = ManagementFactory.getThreadMXBean();
    final List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();
    final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    systemDiagnostics.setDaemonThreads(threads.getDaemonThreadCount());
    systemDiagnostics.setTotalThreads(threads.getThreadCount());
    systemDiagnostics.setTotalHeap(heap.getCommitted());
    systemDiagnostics.setUsedHeap(heap.getUsed());
    systemDiagnostics.setMaxHeap(heap.getMax());
    systemDiagnostics.setTotalNonHeap(nonHeap.getCommitted());
    systemDiagnostics.setUsedNonHeap(nonHeap.getUsed());
    systemDiagnostics.setMaxNonHeap(nonHeap.getMax());
    systemDiagnostics.setUptime(runtime.getUptime());
    systemDiagnostics.setAvailableProcessors(os.getAvailableProcessors());
    final double systemLoad = os.getSystemLoadAverage();
    if (systemLoad >= 0) {
        systemDiagnostics.setProcessorLoadAverage(systemLoad);
    } else {
        systemDiagnostics.setProcessorLoadAverage(-1.0);
    }
    // get the database disk usage
    final StorageUsage flowFileRepoStorageUsage = new StorageUsage();
    flowFileRepoStorageUsage.setIdentifier("FlowFile Repository");
    try {
        flowFileRepoStorageUsage.setFreeSpace(flowFileRepo.getUsableStorageSpace());
        flowFileRepoStorageUsage.setTotalSpace(flowFileRepo.getStorageCapacity());
    } catch (final IOException ioe) {
        flowFileRepoStorageUsage.setFreeSpace(0L);
        flowFileRepoStorageUsage.setTotalSpace(-1L);
        logger.warn("Unable to determine FlowFile Repository usage due to {}", ioe.toString());
        if (logger.isDebugEnabled()) {
            logger.warn("", ioe);
        }
    }
    systemDiagnostics.setFlowFileRepositoryStorageUsage(flowFileRepoStorageUsage);
    // get the file repository disk usage
    final Set<String> containerNames = contentRepo.getContainerNames();
    final Map<String, StorageUsage> fileRepositoryUsage = new LinkedHashMap<>(containerNames.size());
    for (final String containerName : containerNames) {
        long containerCapacity = -1L;
        long containerFree = 0L;
        try {
            containerFree = contentRepo.getContainerUsableSpace(containerName);
            containerCapacity = contentRepo.getContainerCapacity(containerName);
        } catch (final IOException ioe) {
            logger.warn("Unable to determine Content Repository usage for container {} due to {}", containerName, ioe.toString());
            if (logger.isDebugEnabled()) {
                logger.warn("", ioe);
            }
        }
        final StorageUsage storageUsage = new StorageUsage();
        storageUsage.setIdentifier(containerName);
        storageUsage.setFreeSpace(containerFree);
        storageUsage.setTotalSpace(containerCapacity);
        fileRepositoryUsage.put(containerName, storageUsage);
    }
    systemDiagnostics.setContentRepositoryStorageUsage(fileRepositoryUsage);
    // get provenance repository disk usage
    final Set<String> provContainerNames = provenanceRepository.getContainerNames();
    final Map<String, StorageUsage> provRepositoryUsage = new LinkedHashMap<>(provContainerNames.size());
    for (final String containerName : provContainerNames) {
        long containerCapacity = -1L;
        long containerFree = 0L;
        try {
            containerFree = provenanceRepository.getContainerUsableSpace(containerName);
            containerCapacity = provenanceRepository.getContainerCapacity(containerName);
        } catch (final IOException ioe) {
            logger.warn("Unable to determine Provenance Repository usage for container {} due to {}", containerName, ioe.toString());
            if (logger.isDebugEnabled()) {
                logger.warn("", ioe);
            }
        }
        final StorageUsage storageUsage = new StorageUsage();
        storageUsage.setIdentifier(containerName);
        storageUsage.setFreeSpace(containerFree);
        storageUsage.setTotalSpace(containerCapacity);
        provRepositoryUsage.put(containerName, storageUsage);
    }
    systemDiagnostics.setProvenanceRepositoryStorageUsage(provRepositoryUsage);
    // get the garbage collection statistics
    final Map<String, GarbageCollection> garbageCollection = new LinkedHashMap<>(garbageCollectors.size());
    for (final GarbageCollectorMXBean garbageCollector : garbageCollectors) {
        final GarbageCollection garbageCollectionEntry = new GarbageCollection();
        garbageCollectionEntry.setCollectionCount(garbageCollector.getCollectionCount());
        garbageCollectionEntry.setCollectionTime(garbageCollector.getCollectionTime());
        garbageCollection.put(garbageCollector.getName(), garbageCollectionEntry);
    }
    systemDiagnostics.setGarbageCollection(garbageCollection);
    // This information is available only for *nix systems.
    final OperatingSystemMXBean osStats = ManagementFactory.getOperatingSystemMXBean();
    try {
        final Class<?> unixOsMxBeanClass = Class.forName("com.sun.management.UnixOperatingSystemMXBean");
        if (unixOsMxBeanClass.isAssignableFrom(osStats.getClass())) {
            final Method totalPhysicalMemory = unixOsMxBeanClass.getMethod("getTotalPhysicalMemorySize");
            totalPhysicalMemory.setAccessible(true);
            final Long ramBytes = (Long) totalPhysicalMemory.invoke(osStats);
            systemDiagnostics.setTotalPhysicalMemory(ramBytes);
            final Method maxFileDescriptors = unixOsMxBeanClass.getMethod("getMaxFileDescriptorCount");
            maxFileDescriptors.setAccessible(true);
            final Long maxOpenFileDescriptors = (Long) maxFileDescriptors.invoke(osStats);
            systemDiagnostics.setMaxOpenFileHandles(maxOpenFileDescriptors);
            final Method openFileDescriptors = unixOsMxBeanClass.getMethod("getOpenFileDescriptorCount");
            openFileDescriptors.setAccessible(true);
            final Long openDescriptorCount = (Long) openFileDescriptors.invoke(osStats);
            systemDiagnostics.setOpenFileHandles(openDescriptorCount);
        }
    } catch (final Throwable t) {
    // Ignore. This will throw either ClassNotFound or NoClassDefFoundError if unavailable in this JVM.
    }
    // set the creation timestamp
    systemDiagnostics.setCreationTimestamp(new Date().getTime());
    return systemDiagnostics;
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) GarbageCollectorMXBean(java.lang.management.GarbageCollectorMXBean) RuntimeMXBean(java.lang.management.RuntimeMXBean) IOException(java.io.IOException) Method(java.lang.reflect.Method) MemoryUsage(java.lang.management.MemoryUsage) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) MemoryMXBean(java.lang.management.MemoryMXBean) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean)

Example 12 with OperatingSystemMXBean

use of java.lang.management.OperatingSystemMXBean in project traccar by tananaev.

the class Log method logSystemInfo.

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");
    }
}
Also used : MemoryMXBean(java.lang.management.MemoryMXBean) RuntimeMXBean(java.lang.management.RuntimeMXBean) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean) IOException(java.io.IOException)

Example 13 with OperatingSystemMXBean

use of java.lang.management.OperatingSystemMXBean in project Payara by payara.

the class MachineMemoryUsageHealthCheck method doCheck.

@Override
public HealthCheckResult doCheck() {
    HealthCheckResult result = new HealthCheckResult();
    long memAvailable = 0;
    long memFree = 0;
    long memTotal = 0;
    long memActiveFile = 0;
    long memInactiveFile = 0;
    long memReclaimable = 0;
    boolean memAvailableFound = false;
    if (isLinux()) {
        try {
            List<String> lines = Files.readAllLines(Paths.get("/proc/meminfo"), StandardCharsets.UTF_8);
            if (lines.isEmpty()) {
                return result;
            }
            for (String line : lines) {
                String[] parts = line.split("\\s+");
                if (parts.length > 1) {
                    String part = parts[0];
                    if (MEMAVAILABLE.equals(part)) {
                        memAvailable = parseMemInfo(parts);
                        memAvailableFound = true;
                    }
                    if (MEMFREE.equals(part)) {
                        memFree = parseMemInfo(parts);
                    }
                    if (MEMTOTAL.equals(part)) {
                        memTotal = parseMemInfo(parts);
                    }
                    if (ACTIVEFILE.equals(part)) {
                        memActiveFile = parseMemInfo(parts);
                    }
                    if (INACTIVEFILE.equals(part)) {
                        memInactiveFile = parseMemInfo(parts);
                    }
                    if (RECLAIMABLE.equals(part)) {
                        memReclaimable = parseMemInfo(parts);
                    }
                }
            }
            if (!memAvailableFound) {
                memAvailable = memFree + memActiveFile + memInactiveFile + memReclaimable;
            }
            double usedPercentage = ((double) memAvailable / memTotal) * 100;
            result.add(new HealthCheckResultEntry(decideOnStatusWithRatio(usedPercentage), "Physical Memory Used: " + prettyPrintBytes(memTotal - memAvailable) + " - " + "Total Physical Memory: " + prettyPrintBytes(memTotal) + " - " + "Memory Used%: " + new DecimalFormat("#.00").format(usedPercentage) + "%"));
        } catch (IOException exception) {
            result.add(new HealthCheckResultEntry(HealthCheckResultStatus.CHECK_ERROR, "Memory information cannot be read for retrieving physical memory usage values", exception));
        } catch (ArithmeticException exception) {
            result.add(new HealthCheckResultEntry(HealthCheckResultStatus.CHECK_ERROR, "Error occurred while calculating memory usage values. Total memory is " + memTotal, exception));
        }
    } else {
        try {
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            Long totalPhysicalMemSize = invokeMethodFor(osBean, "getTotalPhysicalMemorySize");
            Long freePhysicalMemSize = invokeMethodFor(osBean, "getFreePhysicalMemorySize");
            double usedPercentage = ((double) (totalPhysicalMemSize - freePhysicalMemSize) / totalPhysicalMemSize) * 100;
            result.add(new HealthCheckResultEntry(decideOnStatusWithRatio(usedPercentage), "Physical Memory Used: " + prettyPrintBytes((totalPhysicalMemSize - freePhysicalMemSize)) + " - " + "Total Physical Memory: " + prettyPrintBytes(totalPhysicalMemSize) + " - " + "Memory Used%: " + new DecimalFormat("#.00").format(usedPercentage) + "%"));
        } catch (Exception exception) {
            result.add(new HealthCheckResultEntry(HealthCheckResultStatus.CHECK_ERROR, "Operating system methods cannot be invoked for retrieving physical memory usage values", exception));
        }
    }
    return result;
}
Also used : DecimalFormat(java.text.DecimalFormat) HealthCheckResult(fish.payara.nucleus.healthcheck.HealthCheckResult) IOException(java.io.IOException) IOException(java.io.IOException) HealthCheckResultEntry(fish.payara.notification.healthcheck.HealthCheckResultEntry) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean)

Example 14 with OperatingSystemMXBean

use of java.lang.management.OperatingSystemMXBean in project Mycat_plus by coderczp.

the class EnvironmentInformation method getSizeOfFreeHeapMemory.

/**
 * 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();
}
Also used : Method(java.lang.reflect.Method) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean)

Example 15 with OperatingSystemMXBean

use of java.lang.management.OperatingSystemMXBean in project Mycat_plus by coderczp.

the class EnvironmentInformation method getMaxJvmHeapMemory.

/**
 * 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;
}
Also used : Method(java.lang.reflect.Method) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean)

Aggregations

OperatingSystemMXBean (java.lang.management.OperatingSystemMXBean)88 RuntimeMXBean (java.lang.management.RuntimeMXBean)26 Method (java.lang.reflect.Method)20 IOException (java.io.IOException)15 MemoryMXBean (java.lang.management.MemoryMXBean)11 MemoryUsage (java.lang.management.MemoryUsage)8 ThreadMXBean (java.lang.management.ThreadMXBean)8 HashMap (java.util.HashMap)8 UnixOperatingSystemMXBean (com.sun.management.UnixOperatingSystemMXBean)7 GarbageCollectorMXBean (java.lang.management.GarbageCollectorMXBean)6 Status (com.alibaba.dubbo.common.status.Status)5 File (java.io.File)5 LinkedHashMap (java.util.LinkedHashMap)5 Map (java.util.Map)5 Test (org.junit.Test)5 Test (org.testng.annotations.Test)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 UnknownHostException (java.net.UnknownHostException)4 Date (java.util.Date)4 ExtendedOperatingSystemMXBeanImpl (com.ibm.lang.management.internal.ExtendedOperatingSystemMXBeanImpl)3