kvm: Use lscpu to get cpu max speed (#5506)

* kvm: Use lscpu to get cpu max speed

* Fix str conversion

* Reorder

* Refactor

* Apply suggestions from code review

Co-authored-by: Daniel Augusto Veronezi Salvador <38945620+GutoVeronezi@users.noreply.github.com>

* Updated the calling method name getCpuSpeedFromCommandLscpu

* Make it more readable

Co-authored-by: Daniel Augusto Veronezi Salvador <38945620+GutoVeronezi@users.noreply.github.com>
Co-authored-by: sureshanaparti <12028987+sureshanaparti@users.noreply.github.com>
This commit is contained in:
davidjumani 2022-02-04 16:07:14 +05:30 committed by GitHub
parent f458964e52
commit 26e4e18218
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 36 additions and 2 deletions

View File

@ -18,6 +18,8 @@ package org.apache.cloudstack.utils.linux;
import com.cloud.hypervisor.kvm.resource.LibvirtCapXMLParser;
import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
import com.cloud.utils.script.Script;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.libvirt.Connect;
@ -80,13 +82,45 @@ public class KVMHostInfo {
}
protected static long getCpuSpeed(final NodeInfo nodeInfo) {
long speed = 0L;
speed = getCpuSpeedFromCommandLscpu();
if(speed > 0L) {
return speed;
}
speed = getCpuSpeedFromFile();
if(speed > 0L) {
return speed;
}
LOGGER.info(String.format("Using the value [%s] provided by Libvirt.", nodeInfo.mhz));
speed = nodeInfo.mhz;
return speed;
}
private static long getCpuSpeedFromCommandLscpu() {
try {
LOGGER.info("Fetching CPU speed from command \"lscpu\".");
String command = "lscpu | grep -i 'Model name' | head -n 1 | egrep -o '[[:digit:]].[[:digit:]]+GHz' | sed 's/GHz//g'";
String result = Script.runSimpleBashScript(command);
long speed = (long) (Float.parseFloat(result) * 1000);
LOGGER.info(String.format("Command [%s] resulted in the value [%s] for CPU speed.", command, speed));
return speed;
} catch (NullPointerException | NumberFormatException e) {
LOGGER.error(String.format("Unable to retrieve the CPU speed from lscpu."), e);
return 0L;
}
}
private static long getCpuSpeedFromFile() {
LOGGER.info(String.format("Fetching CPU speed from file [%s].", cpuInfoMaxFreqFileName));
try (Reader reader = new FileReader(cpuInfoMaxFreqFileName)) {
Long cpuInfoMaxFreq = Long.parseLong(IOUtils.toString(reader).trim());
LOGGER.info(String.format("Retrieved value [%s] from file [%s]. This corresponds to a CPU speed of [%s] MHz.", cpuInfoMaxFreq, cpuInfoMaxFreqFileName, cpuInfoMaxFreq / 1000));
return cpuInfoMaxFreq / 1000;
} catch (IOException | NumberFormatException e) {
LOGGER.error(String.format("Unable to retrieve the CPU speed from file [%s]. Using the value [%s] provided by the Libvirt.", cpuInfoMaxFreqFileName, nodeInfo.mhz), e);
return nodeInfo.mhz;
LOGGER.error(String.format("Unable to retrieve the CPU speed from file [%s]", cpuInfoMaxFreqFileName), e);
return 0L;
}
}