io.axoniq.console.framework.application.CpuMetricsProvider.kt Maven / Gradle / Ivy
/*
* Copyright (c) 2024. AxonIQ B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.console.framework.application
import java.lang.management.ManagementFactory
/**
* Provides CPU metrics for the system and the process.
* Inspired by micrometer code, but adjusted to work well for us
*/
class CpuMetricsProvider {
private val osBean = ManagementFactory.getOperatingSystemMXBean()
private val osBeanClass = listOf(
"com.ibm.lang.management.OperatingSystemMXBean", "com.sun.management.OperatingSystemMXBean"
).firstExistingClass()
private val cpuLoadMethod = osBeanClass?.detectMethod(osBean, "getCpuLoad") ?: osBeanClass?.detectMethod(osBean, "getSystemCpuLoad")
private val processCpuUsageMethod = osBeanClass?.detectMethod(osBean, "getProcessCpuLoad")
fun getSystemCpuUsage(): Double {
return cpuLoadMethod?.invoke(osBean) as Double? ?: -1.0
}
fun getProcessCpuUsage(): Double {
return processCpuUsageMethod?.invoke(osBean) as Double? ?: -1.0
}
}