Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 com.cloud.hypervisor.kvm.resource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.cloudstack.utils.numa.CpuList;
import org.apache.cloudstack.utils.numa.HostNumaNode;
import org.apache.cloudstack.utils.numa.HostNumaTopology;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
* Reads the NUMA layout of a KVM host from sysfs: the CPUs and memory of each node, leaving out isolated CPUs.
*/
public class KVMHostNumaTopologyReader {

private static final Logger LOGGER = LogManager.getLogger(KVMHostNumaTopologyReader.class);

private static final Pattern NODE_DIRECTORY = Pattern.compile("^node(\\d+)$");
private static final Pattern MEMINFO_LINE = Pattern.compile("^Node\\s+\\d+\\s+(\\S+):\\s+(\\d+)\\s*kB\\s*$");
private static final String[] RECLAIMABLE = {"MemFree", "Active(file)", "Inactive(file)", "SReclaimable"};

private final Path systemDevices;

public KVMHostNumaTopologyReader() {
this(Paths.get("/sys/devices/system"));
}

protected KVMHostNumaTopologyReader(Path systemDevices) {
this.systemDevices = systemDevices;
}

/**
* @return the NUMA nodes of this host that have CPUs and memory; with no nodes when the layout cannot be read
*/
public HostNumaTopology read() {
List<HostNumaNode> nodes = new ArrayList<>();
Path nodeRoot = systemDevices.resolve("node");
if (!Files.isDirectory(nodeRoot)) {
LOGGER.debug("No NUMA information at [{}].", nodeRoot);
return new HostNumaTopology(nodes);
}
try (DirectoryStream<Path> directories = Files.newDirectoryStream(nodeRoot, "node*")) {
List<Integer> isolated = readIsolatedCpus();
for (Path directory : directories) {
Matcher matcher = NODE_DIRECTORY.matcher(directory.getFileName().toString());
if (!matcher.matches()) {
continue;
}
HostNumaNode node = readNode(Integer.parseInt(matcher.group(1)), directory, isolated);
if (node != null) {
nodes.add(node);
}
}
} catch (IOException | IllegalArgumentException e) {
LOGGER.warn("Unable to read the NUMA layout of this host from [{}]: {}", nodeRoot, e.getMessage());
return new HostNumaTopology(new ArrayList<>());
}
return new HostNumaTopology(nodes);
}

private HostNumaNode readNode(int id, Path directory, List<Integer> isolated) throws IOException {
List<Integer> cpus = CpuList.parse(readFirstLine(directory.resolve("cpulist")));
cpus.removeAll(isolated);
Map<String, Long> meminfo = readMeminfo(directory.resolve("meminfo"));
Long total = meminfo.get("MemTotal");
if (cpus.isEmpty() || total == null || total == 0) {
LOGGER.debug("Leaving NUMA node [{}] out: it has no usable CPUs or no memory.", id);
return null;
}
long available = HostNumaNode.UNKNOWN;
if (meminfo.containsKey("MemFree")) {
available = 0;
for (String key : RECLAIMABLE) {
available += meminfo.getOrDefault(key, 0L);
}
}
return new HostNumaNode(id, cpus, total, available);
}

private List<Integer> readIsolatedCpus() throws IOException {
Path isolated = systemDevices.resolve("cpu").resolve("isolated");
if (!Files.isReadable(isolated)) {
return new ArrayList<>();
}
return CpuList.parse(readFirstLine(isolated));
}

private Map<String, Long> readMeminfo(Path meminfo) throws IOException {
Map<String, Long> values = new HashMap<>();
for (String line : Files.readAllLines(meminfo, StandardCharsets.UTF_8)) {
Matcher matcher = MEMINFO_LINE.matcher(line);
if (matcher.matches()) {
values.put(matcher.group(1), Long.parseLong(matcher.group(2)));
}
}
return values;
}

private String readFirstLine(Path file) throws IOException {
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
return lines.isEmpty() ? "" : lines.get(0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@
import org.apache.cloudstack.utils.linux.CPUStat;
import org.apache.cloudstack.utils.linux.KVMHostInfo;
import org.apache.cloudstack.utils.linux.MemStat;
import org.apache.cloudstack.utils.numa.GuestNumaPlan;
import org.apache.cloudstack.utils.numa.GuestNumaPlanner;
import org.apache.cloudstack.utils.numa.NumaPlacementException;
import org.apache.cloudstack.utils.numa.NumaSettings;
import org.apache.cloudstack.utils.qemu.QemuImg;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.apache.cloudstack.utils.qemu.QemuImgException;
Expand Down Expand Up @@ -231,6 +235,7 @@
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogAction;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogModel;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.MetadataDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.NumaTuneDef;
import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceAgentExecutor;
import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceExecutor;
import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceServiceExecutor;
Expand Down Expand Up @@ -624,6 +629,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
protected int stopTimeout;
protected CPUStat cpuStat = new CPUStat();
protected MemStat memStat = new MemStat(dom0MinMem, dom0OvercommitMem);
protected KVMHostNumaTopologyReader hostNumaTopologyReader = new KVMHostNumaTopologyReader();
private final LibvirtUtilitiesHelper libvirtUtilitiesHelper = new LibvirtUtilitiesHelper();
private LibvirtDomainListener libvirtDomainListener;

Expand Down Expand Up @@ -3209,15 +3215,31 @@ private void configureVM(VirtualMachineTO vmTO, LibvirtVMDef vm, Map<String, Str
}

vm.addComp(guest);
vm.addComp(createGuestResourceDef(vmTO));

int vcpus = vmTO.getCpus();
GuestNumaPlan numaPlan = createGuestNumaPlan(vmTO, extraConfig);
GuestResourceDef guestResource = createGuestResourceDef(vmTO);
if (numaPlan != null) {
giveNumaAwareVmItsResourcesUpFront(vmTO, guestResource);
}
vm.addComp(guestResource);

if (!extraConfig.containsKey(DpdkHelper.DPDK_NUMA)) {
vm.addComp(createCpuModeDef(vmTO, vcpus));
CpuModeDef cpuMode = createCpuModeDef(vmTO, vcpus);
addNumaCells(cpuMode, guestResource, numaPlan, vmTO.getDetails());
vm.addComp(cpuMode);
}

if (hypervisorLibvirtVersion >= MIN_LIBVIRT_VERSION_FOR_GUEST_CPU_TUNE) {
vm.addComp(createCpuTuneDef(vmTO));
CpuTuneDef cpuTune = createCpuTuneDef(vmTO);
pinVcpusToHostNodes(cpuTune, numaPlan);
vm.addComp(cpuTune);
} else if (numaPlan != null && numaPlan.getSettings().getPin() == NumaSettings.Pin.NODE) {
throw new NumaPlacementException(String.format("The libvirt version of this host is too old to pin the vCPUs of the NUMA-aware VM [%s].", vmTO.getName()));
}

if (numaPlan != null) {
vm.addComp(createNumaTuneDef(numaPlan));
}

FeaturesDef features = createFeaturesDef(customParams, isUefiEnabled, isSecureBoot);
Expand All @@ -3236,6 +3258,101 @@ private void configureVM(VirtualMachineTO vmTO, LibvirtVMDef vm, Map<String, Str
addExtraConfigsToVM(vmTO, vm, extraConfig);
}

/**
* Lays a NUMA-aware user VM out over the NUMA nodes of this host.
*
* @return the plan, or null when the VM is not NUMA-aware
* @throws NumaPlacementException when the VM is NUMA-aware and does not fit this host
*/
protected GuestNumaPlan createGuestNumaPlan(VirtualMachineTO vmTO, Map<String, String> extraConfig) {
if (!VirtualMachine.Type.User.equals(vmTO.getType())) {
return null;
}
NumaSettings settings;
try {
settings = NumaSettings.fromDetails(vmTO.getDetails());
} catch (IllegalArgumentException e) {
throw new NumaPlacementException(e.getMessage());
}
if (!settings.isEnabled()) {
return null;
}
if (MapUtils.isNotEmpty(extraConfig) && extraConfig.containsKey(DpdkHelper.DPDK_NUMA)) {
LOGGER.info("VM [{}] has a DPDK NUMA extra configuration, so its NUMA settings {} are not applied.", vmTO.getName(), settings);
return null;
}
long memoryKib = getNumaAwareVmMemoryKib(vmTO);
GuestNumaPlan plan = GuestNumaPlanner.plan(settings, vmTO.getCpus(), memoryKib, hostNumaTopologyReader.read());
LOGGER.debug("VM [{}] with {} gets {} guest NUMA node(s).", vmTO.getName(), settings, plan.getCells().size());
return plan;
}

/**
* @return the memory the offering gives the VM, which is what a NUMA-aware VM gets at start
*/
protected long getNumaAwareVmMemoryKib(VirtualMachineTO vmTO) {
long memory = vmTO.getRequestedRam() > 0 ? vmTO.getRequestedRam() : vmTO.getMaxRam();
return ByteScaleUtils.bytesToKibibytes(memory);
}

/**
* A NUMA-aware VM gets all of its memory and vCPUs at start. Its guest NUMA cells are sized from them,
* so neither is hot-added later.
*/
protected void giveNumaAwareVmItsResourcesUpFront(VirtualMachineTO vmTO, GuestResourceDef guestResource) {
long memoryKib = getNumaAwareVmMemoryKib(vmTO);
guestResource.setCurrentMem(memoryKib);
guestResource.setMaxMemory(memoryKib);
guestResource.setMaxVcpuNum(vmTO.getCpus());
}

/**
* Writes the guest NUMA cells into the VM's CPU definition, so that the domain XML has a single
* <code>&lt;cpu&gt;</code> element. A NUMA-aware VM gets one cell and one socket per guest node.
* Any other VM whose memory can be hot-added gets the single cell libvirt needs for that.
*/
protected void addNumaCells(CpuModeDef cpuMode, GuestResourceDef guestResource, GuestNumaPlan numaPlan, Map<String, String> details) {
guestResource.setWriteNumaCell(false);
if (numaPlan == null) {
if (guestResource.isMemoryHotPluggable()) {
cpuMode.addNumaCell(0, "0-" + (guestResource.getMaxVcpu() - 1), guestResource.getCurrentMem());
}
return;
}

int vcpusPerCell = numaPlan.getVcpusPerCell();
int threadsPerCore = details == null ? 1 : NumbersUtil.parseInt(details.get(VmDetailConstants.CPU_THREAD_PER_CORE), 1);
if (threadsPerCore < 1 || vcpusPerCell % threadsPerCore != 0) {
threadsPerCore = 1;
}
cpuMode.setTopology(vcpusPerCell / threadsPerCore, threadsPerCore, numaPlan.getCells().size());
for (GuestNumaPlan.Cell cell : numaPlan.getCells()) {
cpuMode.addNumaCell(cell.getId(), cell.getVcpus(), cell.getMemoryKib());
}
}

/**
* Pins the vCPUs of each guest NUMA cell to the CPUs of the host node behind it.
*/
protected void pinVcpusToHostNodes(CpuTuneDef cpuTune, GuestNumaPlan numaPlan) {
if (numaPlan == null || numaPlan.getSettings().getPin() != NumaSettings.Pin.NODE) {
return;
}
for (GuestNumaPlan.Cell cell : numaPlan.getCells()) {
for (int vcpu = cell.getFirstVcpu(); vcpu <= cell.getLastVcpu(); vcpu++) {
cpuTune.addVcpuPin(vcpu, cell.getHostCpus());
}
}
}

protected NumaTuneDef createNumaTuneDef(GuestNumaPlan numaPlan) {
NumaTuneDef numaTune = new NumaTuneDef(numaPlan.getSettings().getPolicy().toString());
for (GuestNumaPlan.Cell cell : numaPlan.getCells()) {
numaTune.addMemNode(cell.getId(), cell.getHostNode().getId());
}
return numaTune;
}

protected MetadataDef createMetadataDef(VirtualMachineTO vmTO) {
VirtualMachineMetadataTO metadata = vmTO.getMetadata();
return (metadata != null) ? new MetadataDef(metadata) : null;
Expand Down Expand Up @@ -4494,6 +4611,7 @@ public StartupCommand[] initialize() {
if (info.getCpuMaxSpeed() > 0) {
cmd.getHostDetails().put(HOST_CPU_MAX_SPEED_MHZ, String.valueOf(info.getCpuMaxSpeed()));
}
cmd.getHostDetails().putAll(hostNumaTopologyReader.read().toDetails());
fillNetworkInformation(cmd);
privateIp = cmd.getPrivateIpAddress();
cmd.getHostDetails().putAll(getVersionStrings());
Expand Down
Loading