diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/KVMHostNumaTopologyReader.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/KVMHostNumaTopologyReader.java new file mode 100644 index 000000000000..b0c78018b07d --- /dev/null +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/KVMHostNumaTopologyReader.java @@ -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 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 directories = Files.newDirectoryStream(nodeRoot, "node*")) { + List 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 isolated) throws IOException { + List cpus = CpuList.parse(readFirstLine(directory.resolve("cpulist"))); + cpus.removeAll(isolated); + Map 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 readIsolatedCpus() throws IOException { + Path isolated = systemDevices.resolve("cpu").resolve("isolated"); + if (!Files.isReadable(isolated)) { + return new ArrayList<>(); + } + return CpuList.parse(readFirstLine(isolated)); + } + + private Map readMeminfo(Path meminfo) throws IOException { + Map 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 lines = Files.readAllLines(file, StandardCharsets.UTF_8); + return lines.isEmpty() ? "" : lines.get(0); + } +} diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index cadb70a0d4e5..259a7f331a71 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -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; @@ -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; @@ -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; @@ -3209,15 +3215,31 @@ private void configureVM(VirtualMachineTO vmTO, LibvirtVMDef vm, Map= 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); @@ -3236,6 +3258,101 @@ private void configureVM(VirtualMachineTO vmTO, LibvirtVMDef vm, Map 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 + * <cpu> 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 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; @@ -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()); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 954a86664611..d554758fc13c 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -26,7 +26,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; import java.util.regex.Pattern; +import java.util.stream.Collectors; import com.cloud.cpu.CPU; import com.cloud.offering.DiskOffering; @@ -458,12 +461,37 @@ public static class GuestResourceDef { private int vcpu = -1; private int maxVcpu = -1; private boolean memoryBalloning = false; + private boolean writeNumaCell = true; private int memoryBalloonStatsPeriod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MEMBALLOON_STATS_PERIOD); public void setMaxMemory(long mem) { this.maxMemory = mem; } + public long getMaxMemory() { + return maxMemory; + } + + public long getCurrentMem() { + return currentMemory; + } + + /** + * @return true when memory can be hot-added, which libvirt only allows for a guest with a NUMA cell + */ + public boolean isMemoryHotPluggable() { + return maxMemory > currentMemory; + } + + /** + * Tells this definition whether to write the NUMA cell that memory hot-add needs. + * Set it to false when the {@link CpuModeDef} of the VM writes the guest's NUMA cells, + * so that the domain XML has a single <cpu> element. + */ + public void setWriteNumaCell(boolean writeNumaCell) { + this.writeNumaCell = writeNumaCell; + } + public void setCurrentMem(long currMem) { this.currentMemory = currMem; } @@ -494,9 +522,11 @@ public String toString() { response.append(String.format("%s\n", this.currentMemory)); response.append(String.format("%s\n", this.currentMemory)); - if (this.maxMemory > this.currentMemory) { + if (isMemoryHotPluggable()) { response.append(String.format("%s\n", this.maxMemory)); - response.append(String.format(" \n", this.maxVcpu - 1, this.currentMemory)); + if (writeNumaCell) { + response.append(String.format(" \n", this.maxVcpu - 1, this.currentMemory)); + } } MemBalloonDef memBalloonDef = new MemBalloonDef(); @@ -2018,6 +2048,7 @@ public static class CpuTuneDef { static final int MIN_QUOTA = 1000; static final int MAX_PERIOD = 1000000; public static final long MAX_CPU_QUOTA = 17592186044415L; + private final Map vcpuPins = new TreeMap<>(); public void setShares(int shares) { _shares = shares; @@ -2043,10 +2074,26 @@ public void setPeriod(int period) { this.period = period; } + /** + * Pins a vCPU to a set of host CPUs. + * + * @param cpuset the host CPUs as a libvirt CPU list, such as "0-9,20-29" + */ + public void addVcpuPin(int vcpu, String cpuset) { + vcpuPins.put(vcpu, cpuset); + } + + public Map getVcpuPins() { + return vcpuPins; + } + @Override public String toString() { StringBuilder cpuTuneBuilder = new StringBuilder(); cpuTuneBuilder.append("\n"); + for (Map.Entry vcpuPin : vcpuPins.entrySet()) { + cpuTuneBuilder.append("\n"); + } if (_shares > 0) { cpuTuneBuilder.append("" + _shares + "\n"); } @@ -2074,6 +2121,7 @@ public static class CpuModeDef { private int _coresPerSocket = -1; private int _threadsPerCore = -1; private int _sockets = -1; + private final List numaCells = new ArrayList<>(); public static boolean isValidModelName(String model) { return model != null && CPU_MODEL_NAME.matcher(model).matches(); @@ -2106,6 +2154,19 @@ public void setTopology(int coresPerSocket, int threadsPerCore, int sockets) { _sockets = sockets; } + /** + * Adds a guest NUMA cell. + * + * @param vcpus the vCPUs of the cell as a libvirt CPU list, such as "0-7" + */ + public void addNumaCell(int id, String vcpus, long memoryKib) { + numaCells.add(String.format("", id, vcpus, memoryKib)); + } + + public int getNumaCellCount() { + return numaCells.size(); + } + @Override public String toString() { StringBuilder modeBuilder = new StringBuilder(); @@ -2136,6 +2197,12 @@ public String toString() { modeBuilder.append(""); } + if (!numaCells.isEmpty()) { + modeBuilder.append(""); + numaCells.forEach(modeBuilder::append); + modeBuilder.append(""); + } + // close cpu def modeBuilder.append(""); return modeBuilder.toString(); @@ -2148,6 +2215,41 @@ public int getCoresPerSocket() { public int getSockets() { return _sockets; } } + /** + * Binds the memory of each guest NUMA cell to a host NUMA node. + */ + public static class NumaTuneDef { + private final String mode; + private final Map hostNodeOfCell = new TreeMap<>(); + + /** + * @param mode the libvirt memory mode: strict or preferred + */ + public NumaTuneDef(String mode) { + this.mode = mode; + } + + public void addMemNode(int cellId, int hostNode) { + hostNodeOfCell.put(cellId, hostNode); + } + + @Override + public String toString() { + if (hostNodeOfCell.isEmpty()) { + return ""; + } + String hostNodes = new TreeSet<>(hostNodeOfCell.values()).stream().map(String::valueOf).collect(Collectors.joining(",")); + StringBuilder numaTuneBuilder = new StringBuilder(); + numaTuneBuilder.append("\n"); + numaTuneBuilder.append("\n"); + for (Map.Entry memNode : hostNodeOfCell.entrySet()) { + numaTuneBuilder.append("\n"); + } + numaTuneBuilder.append("\n"); + return numaTuneBuilder.toString(); + } + } + public static class SerialDef { private final String _type; private final String _source; diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java index fd771add7bea..27e20aa44c57 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java @@ -30,6 +30,7 @@ import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.utils.FileUtil; import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.cloudstack.utils.numa.NumaPlacementException; import org.apache.commons.collections4.CollectionUtils; import org.libvirt.Connect; import org.libvirt.DomainInfo.DomainState; @@ -172,6 +173,9 @@ public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource.handleVmStartFailure(conn, vmName, vm); } return new StartAnswer(command, e.getMessage()); + } catch (final NumaPlacementException e) { + logger.warn("Unable to start the NUMA-aware VM [{}] on this host: {}", vmName, e.getMessage()); + return new StartAnswer(command, String.format("Unable to start the NUMA-aware VM on this host: %s", e.getMessage())); } finally { if (state != DomainState.VIR_DOMAIN_RUNNING) { storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec); diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/KVMHostNumaTopologyReaderTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/KVMHostNumaTopologyReaderTest.java new file mode 100644 index 000000000000..1bbec7d77390 --- /dev/null +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/KVMHostNumaTopologyReaderTest.java @@ -0,0 +1,129 @@ +// 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.Files; +import java.nio.file.Path; +import java.util.Arrays; + +import org.apache.cloudstack.utils.numa.CpuList; +import org.apache.cloudstack.utils.numa.HostNumaNode; +import org.apache.cloudstack.utils.numa.HostNumaTopology; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class KVMHostNumaTopologyReaderTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private Path systemDevices; + + @Before + public void setUp() throws IOException { + systemDevices = temporaryFolder.newFolder("system").toPath(); + } + + private void writeNode(int id, String cpulist, long totalKb, long freeKb, long activeFileKb, long inactiveFileKb, long reclaimableSlabKb) throws IOException { + Path node = Files.createDirectories(systemDevices.resolve("node").resolve("node" + id)); + Files.write(node.resolve("cpulist"), (cpulist + "\n").getBytes(StandardCharsets.UTF_8)); + Files.write(node.resolve("meminfo"), Arrays.asList( + String.format("Node %d MemTotal: %d kB", id, totalKb), + String.format("Node %d MemFree: %d kB", id, freeKb), + String.format("Node %d MemUsed: %d kB", id, totalKb - freeKb), + String.format("Node %d Active(file): %d kB", id, activeFileKb), + String.format("Node %d Inactive(file): %d kB", id, inactiveFileKb), + String.format("Node %d SReclaimable: %d kB", id, reclaimableSlabKb), + String.format("Node %d HugePages_Total: 0", id)), StandardCharsets.UTF_8); + } + + private void writeIsolatedCpus(String cpulist) throws IOException { + Path cpu = Files.createDirectories(systemDevices.resolve("cpu")); + Files.write(cpu.resolve("isolated"), (cpulist + "\n").getBytes(StandardCharsets.UTF_8)); + } + + @Test + public void readFindsTheNodesInIdOrder() throws IOException { + writeNode(1, "10-19,30-39", 99000000L, 50000000L, 1000000L, 2000000L, 300000L); + writeNode(0, "0-9,20-29", 98000000L, 40000000L, 0L, 0L, 0L); + writeIsolatedCpus(""); + + HostNumaTopology topology = new KVMHostNumaTopologyReader(systemDevices).read(); + + Assert.assertEquals(2, topology.getNodes().size()); + HostNumaNode node0 = topology.getNodes().get(0); + Assert.assertEquals(0, node0.getId()); + Assert.assertEquals(CpuList.parse("0-9,20-29"), node0.getCpus()); + Assert.assertEquals(98000000L, node0.getMemoryKib()); + Assert.assertEquals(40000000L, node0.getAvailableKib()); + HostNumaNode node1 = topology.getNodes().get(1); + Assert.assertEquals(1, node1.getId()); + Assert.assertEquals(CpuList.parse("10-19,30-39"), node1.getCpus()); + Assert.assertEquals(99000000L, node1.getMemoryKib()); + Assert.assertEquals(53300000L, node1.getAvailableKib()); + } + + @Test + public void readLeavesOutIsolatedCpus() throws IOException { + writeNode(0, "0-9", 98000000L, 40000000L, 0L, 0L, 0L); + writeNode(1, "10-19", 98000000L, 40000000L, 0L, 0L, 0L); + writeIsolatedCpus("8-11"); + + HostNumaTopology topology = new KVMHostNumaTopologyReader(systemDevices).read(); + + Assert.assertEquals(CpuList.parse("0-7"), topology.getNodes().get(0).getCpus()); + Assert.assertEquals(CpuList.parse("12-19"), topology.getNodes().get(1).getCpus()); + } + + @Test + public void readLeavesOutNodesWithoutCpusOrMemory() throws IOException { + writeNode(0, "0-9", 98000000L, 40000000L, 0L, 0L, 0L); + writeNode(1, "", 98000000L, 40000000L, 0L, 0L, 0L); + writeNode(2, "10-19", 0L, 0L, 0L, 0L, 0L); + + HostNumaTopology topology = new KVMHostNumaTopologyReader(systemDevices).read(); + + Assert.assertEquals(1, topology.getNodes().size()); + Assert.assertEquals(0, topology.getNodes().get(0).getId()); + } + + @Test + public void readWorksWithoutAnIsolatedCpusFile() throws IOException { + writeNode(0, "0-3", 16000000L, 8000000L, 0L, 0L, 0L); + + HostNumaTopology topology = new KVMHostNumaTopologyReader(systemDevices).read(); + + Assert.assertEquals(CpuList.parse("0-3"), topology.getNodes().get(0).getCpus()); + } + + @Test + public void readReturnsNoNodesWhenTheHostHasNoNumaInformation() { + Assert.assertTrue(new KVMHostNumaTopologyReader(systemDevices).read().getNodes().isEmpty()); + } + + @Test + public void readReturnsNoNodesWhenTheLayoutCannotBeRead() throws IOException { + writeNode(0, "not-a-cpu-list", 16000000L, 8000000L, 0L, 0L, 0L); + + Assert.assertTrue(new KVMHostNumaTopologyReader(systemDevices).read().getNodes().isEmpty()); + } +} diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceNumaTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceNumaTest.java new file mode 100644 index 000000000000..2494cd2c991f --- /dev/null +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceNumaTest.java @@ -0,0 +1,254 @@ +// 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.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.cloudstack.utils.numa.CpuList; +import org.apache.cloudstack.utils.numa.GuestNumaPlan; +import org.apache.cloudstack.utils.numa.HostNumaNode; +import org.apache.cloudstack.utils.numa.HostNumaTopology; +import org.apache.cloudstack.utils.numa.NumaPlacementException; +import org.apache.cloudstack.utils.numa.NumaSettings; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.hypervisor.kvm.dpdk.DpdkHelper; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuModeDef; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestResourceDef; +import com.cloud.template.VirtualMachineTemplate.BootloaderType; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VmDetailConstants; + +@RunWith(MockitoJUnitRunner.class) +public class LibvirtComputingResourceNumaTest { + + private static final long GIB = 1024L * 1024L * 1024L; + private static final long GIB_IN_KIB = 1024L * 1024L; + + @Mock + private KVMHostNumaTopologyReader hostNumaTopologyReaderMock; + + private LibvirtComputingResource libvirtComputingResource; + + @Before + public void setUp() { + libvirtComputingResource = new LibvirtComputingResource(); + libvirtComputingResource.hostNumaTopologyReader = hostNumaTopologyReaderMock; + Mockito.lenient().when(hostNumaTopologyReaderMock.read()).thenReturn(new HostNumaTopology(Arrays.asList( + new HostNumaNode(0, CpuList.parse("0-9,20-29"), 96 * GIB_IN_KIB, 90 * GIB_IN_KIB), + new HostNumaNode(1, CpuList.parse("10-19,30-39"), 96 * GIB_IN_KIB, 80 * GIB_IN_KIB)))); + } + + private VirtualMachineTO createVm(VirtualMachine.Type type, int cpus, long ramGib, String policy) { + VirtualMachineTO to = new VirtualMachineTO(1L, "i-2-3-VM", type, cpus, 1000, 2000, ramGib * GIB / 2, ramGib * GIB, BootloaderType.HVM, "Other", false, false, "password"); + to.setRam(ramGib * GIB / 2, ramGib * GIB, ramGib * GIB); + Map details = new HashMap<>(); + if (policy != null) { + details.put(NumaSettings.POLICY, policy); + } + to.setDetails(details); + return to; + } + + @Test + public void createGuestNumaPlanReturnsNullForAVmThatIsNotNumaAware() { + Assert.assertNull(libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 8, 32, null), new HashMap<>())); + Assert.assertNull(libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 8, 32, "none"), new HashMap<>())); + + Mockito.verify(hostNumaTopologyReaderMock, Mockito.never()).read(); + } + + @Test + public void createGuestNumaPlanReturnsNullForASystemVm() { + Assert.assertNull(libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.DomainRouter, 8, 32, "strict"), new HashMap<>())); + } + + @Test + public void createGuestNumaPlanLeavesAVmWithDpdkNumaExtraConfigAlone() { + Map extraConfig = Collections.singletonMap(DpdkHelper.DPDK_NUMA, ""); + + Assert.assertNull(libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 8, 32, "strict"), extraConfig)); + } + + @Test + public void createGuestNumaPlanUsesTheMemoryTheOfferingGives() { + GuestNumaPlan plan = libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 8, 32, "strict"), new HashMap<>()); + + Assert.assertEquals(1, plan.getCells().size()); + Assert.assertEquals(32 * GIB_IN_KIB, plan.getCells().get(0).getMemoryKib()); + Assert.assertEquals(0, plan.getCells().get(0).getHostNode().getId()); + } + + @Test + public void createGuestNumaPlanFallsBackToMaxRamWhenRequestedRamIsNotSent() { + VirtualMachineTO to = createVm(VirtualMachine.Type.User, 8, 32, "strict"); + to.setRam(16 * GIB, 32 * GIB, 0); + + GuestNumaPlan plan = libvirtComputingResource.createGuestNumaPlan(to, new HashMap<>()); + + Assert.assertEquals(32 * GIB_IN_KIB, plan.getCells().get(0).getMemoryKib()); + } + + @Test + public void createGuestNumaPlanRefusesInvalidSettings() { + VirtualMachineTO to = createVm(VirtualMachine.Type.User, 8, 32, "sometimes"); + + NumaPlacementException e = Assert.assertThrows(NumaPlacementException.class, () -> libvirtComputingResource.createGuestNumaPlan(to, new HashMap<>())); + + Assert.assertTrue(e.getMessage(), e.getMessage().contains(NumaSettings.POLICY)); + } + + @Test + public void createGuestNumaPlanRefusesAVmThatDoesNotFitTheHost() { + VirtualMachineTO to = createVm(VirtualMachine.Type.User, 64, 32, "strict"); + + Assert.assertThrows(NumaPlacementException.class, () -> libvirtComputingResource.createGuestNumaPlan(to, new HashMap<>())); + } + + @Test + public void giveNumaAwareVmItsResourcesUpFrontRemovesHotAdd() { + VirtualMachineTO to = createVm(VirtualMachine.Type.User, 8, 32, "strict"); + to.setVcpuMaxLimit(16); + GuestResourceDef guestResource = new GuestResourceDef(); + guestResource.setCurrentMem(16 * GIB_IN_KIB); + guestResource.setMaxMemory(64 * GIB_IN_KIB); + guestResource.setVcpuNum(8); + guestResource.setMaxVcpuNum(16); + + libvirtComputingResource.giveNumaAwareVmItsResourcesUpFront(to, guestResource); + + Assert.assertEquals(32 * GIB_IN_KIB, guestResource.getCurrentMem()); + Assert.assertEquals(32 * GIB_IN_KIB, guestResource.getMaxMemory()); + Assert.assertFalse(guestResource.isMemoryHotPluggable()); + Assert.assertEquals(8, guestResource.getMaxVcpu()); + } + + @Test + public void addNumaCellsGivesANumaAwareVmOneSocketPerCell() { + GuestNumaPlan plan = libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 32, 128, "strict"), new HashMap<>()); + CpuModeDef cpuMode = new CpuModeDef(); + cpuMode.setTopology(4, 1, 8); + GuestResourceDef guestResource = new GuestResourceDef(); + + libvirtComputingResource.addNumaCells(cpuMode, guestResource, plan, Collections.singletonMap(VmDetailConstants.CPU_CORE_PER_SOCKET, "4")); + + Assert.assertEquals(2, cpuMode.getSockets()); + Assert.assertEquals(16, cpuMode.getCoresPerSocket()); + Assert.assertEquals(1, cpuMode.getThreadsPerCore()); + String xml = cpuMode.toString(); + Assert.assertTrue(xml, xml.contains("")); + } + + @Test + public void addNumaCellsKeepsTheThreadsPerCoreThatDivideACell() { + GuestNumaPlan plan = libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 32, 128, "strict"), new HashMap<>()); + CpuModeDef cpuMode = new CpuModeDef(); + + libvirtComputingResource.addNumaCells(cpuMode, new GuestResourceDef(), plan, Collections.singletonMap(VmDetailConstants.CPU_THREAD_PER_CORE, "2")); + + Assert.assertEquals(2, cpuMode.getSockets()); + Assert.assertEquals(8, cpuMode.getCoresPerSocket()); + Assert.assertEquals(2, cpuMode.getThreadsPerCore()); + + cpuMode = new CpuModeDef(); + libvirtComputingResource.addNumaCells(cpuMode, new GuestResourceDef(), plan, Collections.singletonMap(VmDetailConstants.CPU_THREAD_PER_CORE, "3")); + + Assert.assertEquals(16, cpuMode.getCoresPerSocket()); + Assert.assertEquals(1, cpuMode.getThreadsPerCore()); + } + + @Test + public void addNumaCellsMovesTheHotAddCellIntoTheCpuDefinition() { + CpuModeDef cpuMode = new CpuModeDef(); + cpuMode.setTopology(4, 1, 2); + GuestResourceDef guestResource = new GuestResourceDef(); + guestResource.setCurrentMem(4 * GIB_IN_KIB); + guestResource.setMaxMemory(8 * GIB_IN_KIB); + guestResource.setVcpuNum(4); + guestResource.setMaxVcpuNum(8); + + libvirtComputingResource.addNumaCells(cpuMode, guestResource, null, null); + + Assert.assertEquals(1, cpuMode.getNumaCellCount()); + Assert.assertTrue(cpuMode.toString(), cpuMode.toString().contains("")); + Assert.assertEquals(2, cpuMode.getSockets()); + Assert.assertFalse(guestResource.toString().contains("")); + Assert.assertTrue(guestResource.toString().contains("()); + CpuTuneDef cpuTune = new CpuTuneDef(); + + libvirtComputingResource.pinVcpusToHostNodes(cpuTune, plan); + + Assert.assertEquals(32, cpuTune.getVcpuPins().size()); + Assert.assertEquals("0-9,20-29", cpuTune.getVcpuPins().get(0)); + Assert.assertEquals("0-9,20-29", cpuTune.getVcpuPins().get(15)); + Assert.assertEquals("10-19,30-39", cpuTune.getVcpuPins().get(16)); + Assert.assertEquals("10-19,30-39", cpuTune.getVcpuPins().get(31)); + } + + @Test + public void pinVcpusToHostNodesDoesNothingWithoutAPlanOrWithPinningOff() { + CpuTuneDef cpuTune = new CpuTuneDef(); + libvirtComputingResource.pinVcpusToHostNodes(cpuTune, null); + Assert.assertTrue(cpuTune.getVcpuPins().isEmpty()); + + VirtualMachineTO to = createVm(VirtualMachine.Type.User, 8, 32, "strict"); + to.getDetails().put(NumaSettings.PIN, "none"); + libvirtComputingResource.pinVcpusToHostNodes(cpuTune, libvirtComputingResource.createGuestNumaPlan(to, new HashMap<>())); + Assert.assertTrue(cpuTune.getVcpuPins().isEmpty()); + } + + @Test + public void createNumaTuneDefUsesThePolicyAsTheMemoryMode() { + GuestNumaPlan strict = libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 32, 128, "strict"), new HashMap<>()); + GuestNumaPlan preferred = libvirtComputingResource.createGuestNumaPlan(createVm(VirtualMachine.Type.User, 8, 32, "preferred"), new HashMap<>()); + + Assert.assertEquals("\n\n\n\n\n", + libvirtComputingResource.createNumaTuneDef(strict).toString()); + Assert.assertEquals("\n\n\n\n", + libvirtComputingResource.createNumaTuneDef(preferred).toString()); + } +} diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java index f5fec8ad096e..4a24f7e36c34 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java @@ -276,6 +276,77 @@ public void testCpuModeDef() { } + @Test + public void testCpuModeDefWritesNumaCellsAfterTheTopology() { + LibvirtVMDef.CpuModeDef cpuModeDef = new LibvirtVMDef.CpuModeDef(); + cpuModeDef.setMode("host-passthrough"); + cpuModeDef.setTopology(8, 1, 2); + cpuModeDef.addNumaCell(0, "0-7", 33554432L); + cpuModeDef.addNumaCell(1, "8-15", 33554432L); + + String expected = "" + + ""; + + assertEquals(expected, cpuModeDef.toString()); + assertEquals(2, cpuModeDef.getNumaCellCount()); + } + + @Test + public void testCpuModeDefWithoutNumaCellsWritesNoNumaElement() { + LibvirtVMDef.CpuModeDef cpuModeDef = new LibvirtVMDef.CpuModeDef(); + cpuModeDef.setMode("host-model"); + + assertFalse(cpuModeDef.toString().contains("")); + } + + @Test + public void testCpuTuneDefWritesVcpuPinsInVcpuOrder() { + LibvirtVMDef.CpuTuneDef cpuTuneDef = new LibvirtVMDef.CpuTuneDef(); + cpuTuneDef.setShares(2000); + cpuTuneDef.addVcpuPin(1, "10-19,30-39"); + cpuTuneDef.addVcpuPin(0, "0-9,20-29"); + + String expected = "\n\n\n2000\n\n"; + + assertEquals(expected, cpuTuneDef.toString()); + } + + @Test + public void testNumaTuneDefBindsEachCellToItsHostNode() { + LibvirtVMDef.NumaTuneDef numaTuneDef = new LibvirtVMDef.NumaTuneDef("strict"); + numaTuneDef.addMemNode(1, 3); + numaTuneDef.addMemNode(0, 2); + + String expected = "\n\n\n" + + "\n\n"; + + assertEquals(expected, numaTuneDef.toString()); + assertEquals("", new LibvirtVMDef.NumaTuneDef("strict").toString()); + } + + @Test + public void testGuestResourceDefWritesItsNumaCellOnlyWhenAsked() { + LibvirtVMDef.GuestResourceDef guestResourceDef = new LibvirtVMDef.GuestResourceDef(); + guestResourceDef.setCurrentMem(1048576L); + guestResourceDef.setMaxMemory(2097152L); + guestResourceDef.setVcpuNum(2); + guestResourceDef.setMaxVcpuNum(4); + + assertTrue(guestResourceDef.isMemoryHotPluggable()); + String withCell = guestResourceDef.toString(); + assertTrue(withCell.contains("2097152")); + assertTrue(withCell.contains(" ")); + + guestResourceDef.setWriteNumaCell(false); + String withoutCell = guestResourceDef.toString(); + assertTrue(withoutCell.contains("2097152")); + assertFalse(withoutCell.contains("")); + + guestResourceDef.setMaxMemory(1048576L); + assertFalse(guestResourceDef.isMemoryHotPluggable()); + assertFalse(guestResourceDef.toString().contains(" allocateTo(VirtualMachineProfile vmProfile, DeploymentPlan protected List checkHostsCompatibilities(ServiceOffering offering, VirtualMachineProfile vmProfile, ExcludeList avoid, List hosts, int returnUpTo, boolean considerReservedCapacity) { List suitableHosts = new ArrayList<>(); logger.debug("Checking compatibility for the following hosts {}.", suitableHosts); + NumaSettings numaSettings = getNumaSettings(offering); for (Host host : hosts) { if (suitableHosts.size() == returnUpTo) { @@ -250,6 +256,10 @@ protected List checkHostsCompatibilities(ServiceOffering offering, Virtual continue; } + if (offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(numaSettings, offering, avoid, host)) { + continue; + } + if (hostHasCpuCapabilityAndCapacity(considerReservedCapacity, offering, host)) { suitableHosts.add(host); continue; @@ -270,6 +280,39 @@ protected boolean offeringRequestedVGpuAndHostDoesNotHaveIt(ServiceOffering offe return true; } + /** + * @return the NUMA settings of the compute offering; settings with the policy none when it has none or they are not valid + */ + protected NumaSettings getNumaSettings(ServiceOffering offering) { + try { + return NumaSettings.fromDetails(_serviceOfferingDetailsDao.listDetailsKeyPairs(offering.getId(), NumaSettings.KEYS)); + } catch (IllegalArgumentException e) { + logger.warn("Ignoring the NUMA settings of compute offering [{}]: {}", offering, e.getMessage()); + return NumaSettings.fromDetails(null); + } + } + + /** + * A NUMA-aware instance only goes to a KVM host that has reported its NUMA layout and whose NUMA nodes can each + * take an even share of the instance's vCPUs and memory. This looks at the size of the host's nodes, not at what + * other instances already use on them. + */ + protected boolean offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(NumaSettings numaSettings, ServiceOffering offering, ExcludeList avoid, Host host) { + if (!numaSettings.isEnabled() || host.getHypervisorType() != HypervisorType.KVM || offering.getCpu() == null || offering.getRamSize() == null) { + return false; + } + + try { + HostNumaTopology topology = HostNumaTopology.fromDetails(_hostDetailsDao.findDetails(host.getId())); + GuestNumaPlanner.plan(numaSettings, offering.getCpu(), offering.getRamSize() * 1024L, topology); + return false; + } catch (NumaPlacementException e) { + logger.debug("Adding host [{}] to the avoid set, because it cannot take a NUMA-aware instance of compute offering [{}]: {}", host, offering, e.getMessage()); + avoid.addHost(host.getId()); + return true; + } + } + /** * Reorder hosts in the decreasing order of free capacity. */ diff --git a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java index d3b536b32a86..ec4d29f9cc00 100644 --- a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java @@ -146,6 +146,7 @@ import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.userdata.UserDataManager; import org.apache.cloudstack.utils.jsinterpreter.GenericRuleHelper; +import org.apache.cloudstack.utils.numa.NumaSettings; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.cloudstack.vm.UnmanagedVMsManager; import org.apache.cloudstack.vm.lease.VMLeaseManager; @@ -3636,6 +3637,7 @@ protected ServiceOfferingVO createServiceOffering(final long userId, final boole if ((entry1 || entry2) && !(entry1 && entry2)) { throw new InvalidParameterValueException("Please specify the pciDevice and vgpuType correctly."); } + validateNumaSettingsInServiceOfferingDetails(details, dynamicScalingEnabled); for (final Entry detailEntry : details.entrySet()) { String detailEntryValue = detailEntry.getValue(); if (detailEntry.getKey().equals(GPU.Keys.pciDevice.toString())) { @@ -3756,6 +3758,23 @@ public static VMLeaseManager.ExpiryAction validateAndGetLeaseExpiryAction(Intege return cmdExpiryAction; } + /** + * Checks the NUMA settings of a compute offering. A NUMA-aware instance gets all of its vCPUs and memory at + * start, so the offering cannot have dynamic scaling enabled. + */ + protected void validateNumaSettingsInServiceOfferingDetails(Map details, boolean dynamicScalingEnabled) { + NumaSettings numaSettings; + try { + numaSettings = NumaSettings.fromDetails(details); + } catch (IllegalArgumentException e) { + throw new InvalidParameterValueException(e.getMessage()); + } + if (numaSettings.isEnabled() && dynamicScalingEnabled) { + throw new InvalidParameterValueException(String.format("A compute offering with %s=%s cannot have dynamic scaling enabled. Set %s to false.", + NumaSettings.POLICY, numaSettings.getPolicy(), ApiConstants.DYNAMIC_SCALING_ENABLED)); + } + } + @Override public void validateExtraConfigInServiceOfferingDetail(String detailName) { if (!detailName.equals(DpdkHelper.DPDK_NUMA) && !detailName.equals(DpdkHelper.DPDK_HUGE_PAGES) diff --git a/server/src/main/java/com/cloud/hypervisor/KVMGuru.java b/server/src/main/java/com/cloud/hypervisor/KVMGuru.java index 5e3beed769a6..52052740981b 100644 --- a/server/src/main/java/com/cloud/hypervisor/KVMGuru.java +++ b/server/src/main/java/com/cloud/hypervisor/KVMGuru.java @@ -50,12 +50,14 @@ import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; +import org.apache.cloudstack.utils.numa.NumaSettings; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.commons.collections.MapUtils; import javax.inject.Inject; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -183,6 +185,7 @@ public Double getCpuQuotaPercentage(double vmSpeeed, double hostSpeed) { public VirtualMachineTO implement(VirtualMachineProfile vm) { VirtualMachineTO to = toVirtualMachineTO(vm); setVmQuotaPercentage(to, vm); + applyNumaSettingsOfServiceOffering(to, vm); enableDpdkIfNeeded(vm, to); @@ -200,6 +203,25 @@ public VirtualMachineTO implement(VirtualMachineProfile vm) { return to; } + /** + * Passes the NUMA settings of the compute offering to the KVM agent with the VM details. + * Only the compute offering can make a VM NUMA-aware, so the same keys set as VM details are left out. + */ + protected void applyNumaSettingsOfServiceOffering(VirtualMachineTO virtualMachineTo, VirtualMachineProfile virtualMachineProfile) { + Map details = virtualMachineTo.getDetails() == null ? new HashMap<>() : new HashMap<>(virtualMachineTo.getDetails()); + boolean changed = details.keySet().removeAll(NumaSettings.KEYS); + + Map offeringDetails = _serviceOfferingDetailsDao.listDetailsKeyPairs(virtualMachineProfile.getServiceOfferingId(), NumaSettings.KEYS); + if (MapUtils.isNotEmpty(offeringDetails)) { + details.putAll(offeringDetails); + changed = true; + } + + if (changed) { + virtualMachineTo.setDetails(details); + } + } + protected void configureVmOsDescription(VirtualMachine virtualMachine, VirtualMachineTO virtualMachineTo, HostVO hostVo) { GuestOSVO guestOS = _guestOsDao.findByIdIncludingRemoved(virtualMachine.getGuestOSId()); String guestOsDisplayName = guestOS.getDisplayName(); diff --git a/server/src/test/java/com/cloud/agent/manager/allocator/impl/FirstFitAllocatorNumaTest.java b/server/src/test/java/com/cloud/agent/manager/allocator/impl/FirstFitAllocatorNumaTest.java new file mode 100644 index 000000000000..caf08a314bf1 --- /dev/null +++ b/server/src/test/java/com/cloud/agent/manager/allocator/impl/FirstFitAllocatorNumaTest.java @@ -0,0 +1,162 @@ +// 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.agent.manager.allocator.impl; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.cloudstack.utils.numa.HostNumaTopology; +import org.apache.cloudstack.utils.numa.NumaSettings; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.deploy.DeploymentPlanner.ExcludeList; +import com.cloud.host.Host; +import com.cloud.host.dao.HostDetailsDao; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.offering.ServiceOffering; +import com.cloud.service.dao.ServiceOfferingDetailsDao; + +@RunWith(MockitoJUnitRunner.class) +public class FirstFitAllocatorNumaTest { + + private static final long HOST_ID = 7L; + private static final long OFFERING_ID = 11L; + private static final long NODE_MEMORY_KIB = 96L * 1024L * 1024L; + + @Mock + private HostDetailsDao hostDetailsDaoMock; + @Mock + private ServiceOfferingDetailsDao serviceOfferingDetailsDaoMock; + @Mock + private Host hostMock; + @Mock + private ServiceOffering offeringMock; + + @InjectMocks + private FirstFitAllocator firstFitAllocator = new FirstFitAllocator(); + + private final NumaSettings strict = new NumaSettings(NumaSettings.Policy.STRICT, 0, NumaSettings.Pin.NODE); + private ExcludeList avoid; + + @Before + public void setUp() { + avoid = new ExcludeList(); + Mockito.lenient().when(hostMock.getId()).thenReturn(HOST_ID); + Mockito.lenient().when(hostMock.getHypervisorType()).thenReturn(HypervisorType.KVM); + Mockito.lenient().when(offeringMock.getId()).thenReturn(OFFERING_ID); + Mockito.lenient().when(offeringMock.getCpu()).thenReturn(8); + Mockito.lenient().when(offeringMock.getRamSize()).thenReturn(32 * 1024); + } + + private Map twoNodeHostDetails() { + Map details = new HashMap<>(); + details.put("host.cpu.max.speed.mhz", "3000"); + details.put(HostNumaTopology.HOST_NUMA_NODES, "0,1"); + details.put(HostNumaTopology.HOST_NUMA_NODE_PREFIX + "0", "20;" + NODE_MEMORY_KIB); + details.put(HostNumaTopology.HOST_NUMA_NODE_PREFIX + "1", "20;" + NODE_MEMORY_KIB); + return details; + } + + @Test + public void getNumaSettingsReadsTheOfferingDetails() { + Mockito.when(serviceOfferingDetailsDaoMock.listDetailsKeyPairs(OFFERING_ID, NumaSettings.KEYS)).thenReturn(Collections.singletonMap(NumaSettings.POLICY, "strict")); + + NumaSettings settings = firstFitAllocator.getNumaSettings(offeringMock); + + Assert.assertTrue(settings.isEnabled()); + Assert.assertTrue(settings.isStrict()); + } + + @Test + public void getNumaSettingsTreatsMissingOrInvalidSettingsAsNotNumaAware() { + Mockito.when(serviceOfferingDetailsDaoMock.listDetailsKeyPairs(OFFERING_ID, NumaSettings.KEYS)).thenReturn(null); + Assert.assertFalse(firstFitAllocator.getNumaSettings(offeringMock).isEnabled()); + + Mockito.when(serviceOfferingDetailsDaoMock.listDetailsKeyPairs(OFFERING_ID, NumaSettings.KEYS)).thenReturn(Collections.singletonMap(NumaSettings.POLICY, "sometimes")); + Assert.assertFalse(firstFitAllocator.getNumaSettings(offeringMock).isEnabled()); + } + + @Test + public void anOfferingThatIsNotNumaAwareIsNotChecked() { + boolean result = firstFitAllocator.offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(NumaSettings.fromDetails(null), offeringMock, avoid, hostMock); + + Assert.assertFalse(result); + Mockito.verifyNoInteractions(hostDetailsDaoMock); + Assert.assertFalse(avoid.shouldAvoid(hostMock)); + } + + @Test + public void aHostThatIsNotKvmIsNotChecked() { + Mockito.when(hostMock.getHypervisorType()).thenReturn(HypervisorType.VMware); + + boolean result = firstFitAllocator.offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(strict, offeringMock, avoid, hostMock); + + Assert.assertFalse(result); + Mockito.verifyNoInteractions(hostDetailsDaoMock); + } + + @Test + public void aHostWhoseNodesCanTakeTheInstanceIsKept() { + Mockito.when(hostDetailsDaoMock.findDetails(HOST_ID)).thenReturn(twoNodeHostDetails()); + + boolean result = firstFitAllocator.offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(strict, offeringMock, avoid, hostMock); + + Assert.assertFalse(result); + Assert.assertFalse(avoid.shouldAvoid(hostMock)); + } + + @Test + public void aHostThatReportedNoNumaLayoutIsAvoided() { + Mockito.when(hostDetailsDaoMock.findDetails(HOST_ID)).thenReturn(Collections.singletonMap("host.cpu.max.speed.mhz", "3000")); + + boolean result = firstFitAllocator.offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(strict, offeringMock, avoid, hostMock); + + Assert.assertTrue(result); + Assert.assertTrue(avoid.shouldAvoid(hostMock)); + } + + @Test + public void aHostWhoseNodesAreTooSmallIsAvoided() { + Mockito.when(hostDetailsDaoMock.findDetails(HOST_ID)).thenReturn(twoNodeHostDetails()); + Mockito.when(offeringMock.getCpu()).thenReturn(64); + + boolean result = firstFitAllocator.offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(strict, offeringMock, avoid, hostMock); + + Assert.assertTrue(result); + Assert.assertTrue(avoid.shouldAvoid(hostMock)); + } + + @Test + public void anInstanceThatCannotBeSplitEvenlyOverTheRequestedNodesIsAvoided() { + Mockito.when(hostDetailsDaoMock.findDetails(HOST_ID)).thenReturn(twoNodeHostDetails()); + Mockito.when(offeringMock.getCpu()).thenReturn(7); + NumaSettings twoNodes = new NumaSettings(NumaSettings.Policy.STRICT, 2, NumaSettings.Pin.NODE); + + boolean result = firstFitAllocator.offeringIsNumaAwareAndHostNumaNodesCannotTakeIt(twoNodes, offeringMock, avoid, hostMock); + + Assert.assertTrue(result); + Assert.assertTrue(avoid.shouldAvoid(hostMock)); + } +} diff --git a/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplNumaTest.java b/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplNumaTest.java new file mode 100644 index 000000000000..40c593336cda --- /dev/null +++ b/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplNumaTest.java @@ -0,0 +1,69 @@ +// 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.configuration; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.cloudstack.utils.numa.NumaSettings; +import org.junit.Assert; +import org.junit.Test; + +import com.cloud.exception.InvalidParameterValueException; + +public class ConfigurationManagerImplNumaTest { + + private final ConfigurationManagerImpl configurationManager = new ConfigurationManagerImpl(); + + @Test + public void offeringDetailsWithoutNumaSettingsAreAccepted() { + configurationManager.validateNumaSettingsInServiceOfferingDetails(new HashMap<>(), true); + configurationManager.validateNumaSettingsInServiceOfferingDetails(Collections.singletonMap(NumaSettings.POLICY, "none"), true); + } + + @Test + public void aNumaAwareOfferingWithoutDynamicScalingIsAccepted() { + Map details = new HashMap<>(); + details.put(NumaSettings.POLICY, "strict"); + details.put(NumaSettings.NODES, "auto"); + details.put(NumaSettings.PIN, "node"); + + configurationManager.validateNumaSettingsInServiceOfferingDetails(details, false); + } + + @Test + public void aNumaAwareOfferingWithDynamicScalingIsRefused() { + Map details = Collections.singletonMap(NumaSettings.POLICY, "preferred"); + + InvalidParameterValueException e = Assert.assertThrows(InvalidParameterValueException.class, + () -> configurationManager.validateNumaSettingsInServiceOfferingDetails(details, true)); + + Assert.assertTrue(e.getMessage(), e.getMessage().contains("dynamic scaling")); + } + + @Test + public void invalidNumaSettingsAreRefused() { + Map badPolicy = Collections.singletonMap(NumaSettings.POLICY, "always"); + Map badNodes = new HashMap<>(); + badNodes.put(NumaSettings.POLICY, "strict"); + badNodes.put(NumaSettings.NODES, "0"); + + Assert.assertThrows(InvalidParameterValueException.class, () -> configurationManager.validateNumaSettingsInServiceOfferingDetails(badPolicy, false)); + Assert.assertThrows(InvalidParameterValueException.class, () -> configurationManager.validateNumaSettingsInServiceOfferingDetails(badNodes, false)); + } +} diff --git a/server/src/test/java/com/cloud/hypervisor/KVMGuruNumaTest.java b/server/src/test/java/com/cloud/hypervisor/KVMGuruNumaTest.java new file mode 100644 index 000000000000..f343f588e80d --- /dev/null +++ b/server/src/test/java/com/cloud/hypervisor/KVMGuruNumaTest.java @@ -0,0 +1,129 @@ +// 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; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.cloudstack.utils.numa.NumaSettings; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.service.dao.ServiceOfferingDetailsDao; +import com.cloud.template.VirtualMachineTemplate.BootloaderType; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@RunWith(MockitoJUnitRunner.class) +public class KVMGuruNumaTest { + + private static final long OFFERING_ID = 11L; + + @Mock + private ServiceOfferingDetailsDao serviceOfferingDetailsDaoMock; + @Mock + private VirtualMachineProfile vmProfileMock; + + @InjectMocks + private KVMGuru guru = new KVMGuru(); + + private VirtualMachineTO to; + + @Before + public void setUp() { + to = new VirtualMachineTO(1L, "i-2-3-VM", VirtualMachine.Type.User, 8, 1000, 2000, 1024L, 2048L, BootloaderType.HVM, "Other", false, false, "password"); + Mockito.when(vmProfileMock.getServiceOfferingId()).thenReturn(OFFERING_ID); + } + + private void offeringHas(Map details) { + Mockito.when(serviceOfferingDetailsDaoMock.listDetailsKeyPairs(OFFERING_ID, NumaSettings.KEYS)).thenReturn(details); + } + + @Test + public void theNumaSettingsOfTheOfferingReachTheVmDetails() { + Map offeringDetails = new HashMap<>(); + offeringDetails.put(NumaSettings.POLICY, "strict"); + offeringDetails.put(NumaSettings.NODES, "2"); + offeringHas(offeringDetails); + to.setDetails(Collections.singletonMap("rootDiskController", "scsi")); + + guru.applyNumaSettingsOfServiceOffering(to, vmProfileMock); + + Assert.assertEquals("strict", to.getDetails().get(NumaSettings.POLICY)); + Assert.assertEquals("2", to.getDetails().get(NumaSettings.NODES)); + Assert.assertFalse(to.getDetails().containsKey(NumaSettings.PIN)); + Assert.assertEquals("scsi", to.getDetails().get("rootDiskController")); + } + + @Test + public void theNumaSettingsOfTheOfferingReachAVmWithoutDetails() { + offeringHas(Collections.singletonMap(NumaSettings.POLICY, "preferred")); + + guru.applyNumaSettingsOfServiceOffering(to, vmProfileMock); + + Assert.assertEquals("preferred", to.getDetails().get(NumaSettings.POLICY)); + } + + @Test + public void numaSettingsSetAsVmDetailsAreLeftOut() { + offeringHas(new HashMap<>()); + Map vmDetails = new HashMap<>(); + vmDetails.put(NumaSettings.POLICY, "strict"); + vmDetails.put(NumaSettings.PIN, "node"); + vmDetails.put("rootDiskController", "scsi"); + to.setDetails(vmDetails); + + guru.applyNumaSettingsOfServiceOffering(to, vmProfileMock); + + Assert.assertFalse(to.getDetails().containsKey(NumaSettings.POLICY)); + Assert.assertFalse(to.getDetails().containsKey(NumaSettings.PIN)); + Assert.assertEquals("scsi", to.getDetails().get("rootDiskController")); + } + + @Test + public void theOfferingWinsOverTheSameKeysInTheVmDetails() { + offeringHas(Collections.singletonMap(NumaSettings.POLICY, "preferred")); + Map vmDetails = new HashMap<>(); + vmDetails.put(NumaSettings.POLICY, "strict"); + vmDetails.put(NumaSettings.NODES, "4"); + to.setDetails(vmDetails); + + guru.applyNumaSettingsOfServiceOffering(to, vmProfileMock); + + Assert.assertEquals("preferred", to.getDetails().get(NumaSettings.POLICY)); + Assert.assertFalse(to.getDetails().containsKey(NumaSettings.NODES)); + } + + @Test + public void aVmWithoutNumaSettingsKeepsItsDetailsUntouched() { + offeringHas(null); + Map vmDetails = Collections.singletonMap("rootDiskController", "scsi"); + to.setDetails(vmDetails); + + guru.applyNumaSettingsOfServiceOffering(to, vmProfileMock); + + Assert.assertSame(vmDetails, to.getDetails()); + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/CpuList.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/CpuList.java new file mode 100644 index 000000000000..5f6ff3d7e2bf --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/CpuList.java @@ -0,0 +1,93 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.TreeSet; + +import org.apache.commons.lang3.StringUtils; + +/** + * Reads and writes CPU lists in the form the Linux kernel and libvirt use, such as "0-3,8,10-11". + */ +public final class CpuList { + + private CpuList() { + } + + /** + * @return the CPUs in ascending order, without duplicates; empty for a blank list + * @throws IllegalArgumentException when the list is not a valid CPU list + */ + public static List parse(String list) { + TreeSet cpus = new TreeSet<>(); + if (StringUtils.isBlank(list)) { + return new ArrayList<>(cpus); + } + for (String part : list.trim().split(",")) { + String range = part.trim(); + try { + int dash = range.indexOf('-'); + int first = Integer.parseInt(dash < 0 ? range : range.substring(0, dash).trim()); + int last = dash < 0 ? first : Integer.parseInt(range.substring(dash + 1).trim()); + if (first < 0 || last < first) { + throw new IllegalArgumentException(String.format("Invalid CPU list '%s'", list)); + } + for (int cpu = first; cpu <= last; cpu++) { + cpus.add(cpu); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(String.format("Invalid CPU list '%s'", list), e); + } + } + return new ArrayList<>(cpus); + } + + /** + * @return the CPUs as a compact list such as "0-3,8"; an empty string for no CPUs + */ + public static String format(Collection cpus) { + StringBuilder list = new StringBuilder(); + Integer first = null; + Integer previous = null; + for (Integer cpu : new TreeSet<>(cpus)) { + if (first == null) { + first = cpu; + } else if (cpu != previous + 1) { + appendRange(list, first, previous); + first = cpu; + } + previous = cpu; + } + if (first != null) { + appendRange(list, first, previous); + } + return list.toString(); + } + + private static void appendRange(StringBuilder list, int first, int last) { + if (list.length() > 0) { + list.append(','); + } + list.append(first); + if (last > first) { + list.append('-').append(last); + } + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/GuestNumaPlan.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/GuestNumaPlan.java new file mode 100644 index 000000000000..bf86e85055f9 --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/GuestNumaPlan.java @@ -0,0 +1,97 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.Collections; +import java.util.List; + +/** + * How an instance is laid out over the NUMA nodes of a host: its guest NUMA cells and the host node behind each one. + */ +public class GuestNumaPlan { + + public static class Cell { + private final int id; + private final int firstVcpu; + private final int lastVcpu; + private final long memoryKib; + private final HostNumaNode hostNode; + + public Cell(int id, int firstVcpu, int lastVcpu, long memoryKib, HostNumaNode hostNode) { + this.id = id; + this.firstVcpu = firstVcpu; + this.lastVcpu = lastVcpu; + this.memoryKib = memoryKib; + this.hostNode = hostNode; + } + + public int getId() { + return id; + } + + public int getFirstVcpu() { + return firstVcpu; + } + + public int getLastVcpu() { + return lastVcpu; + } + + public long getMemoryKib() { + return memoryKib; + } + + public HostNumaNode getHostNode() { + return hostNode; + } + + /** + * @return the vCPUs of this cell as libvirt writes them, such as "0-7" + */ + public String getVcpus() { + return firstVcpu == lastVcpu ? String.valueOf(firstVcpu) : firstVcpu + "-" + lastVcpu; + } + + /** + * @return the CPUs of the host node behind this cell, such as "0-9,20-29" + */ + public String getHostCpus() { + return CpuList.format(hostNode.getCpus()); + } + } + + private final NumaSettings settings; + private final List cells; + + public GuestNumaPlan(NumaSettings settings, List cells) { + this.settings = settings; + this.cells = Collections.unmodifiableList(cells); + } + + public NumaSettings getSettings() { + return settings; + } + + public List getCells() { + return cells; + } + + public int getVcpusPerCell() { + Cell first = cells.get(0); + return first.getLastVcpu() - first.getFirstVcpu() + 1; + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/GuestNumaPlanner.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/GuestNumaPlanner.java new file mode 100644 index 000000000000..606b03c43c9e --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/GuestNumaPlanner.java @@ -0,0 +1,123 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Lays a NUMA-aware instance out over the NUMA nodes of a host. The management server uses it to tell whether a + * host can take the instance, and the KVM agent uses it to build the instance's domain XML. + */ +public final class GuestNumaPlanner { + + private GuestNumaPlanner() { + } + + /** + * Splits the instance evenly over guest NUMA cells and picks a host node for each cell. + * With an automatic node count, the instance gets the fewest cells it fits in. + * + * @param vcpus the vCPUs of the instance + * @param memoryKib the memory of the instance + * @param topology the NUMA layout of the host + * @return the plan, never null + * @throws NumaPlacementException when the instance cannot be laid out on the host + */ + public static GuestNumaPlan plan(NumaSettings settings, int vcpus, long memoryKib, HostNumaTopology topology) { + if (!settings.isEnabled()) { + throw new NumaPlacementException("The instance is not NUMA-aware."); + } + if (topology == null || topology.getNodes().isEmpty()) { + throw new NumaPlacementException("The host has not reported a NUMA layout."); + } + + if (settings.getNodes() > 0) { + String problem = checkEvenSplit(settings.getNodes(), vcpus, memoryKib); + if (problem != null) { + throw new NumaPlacementException(problem); + } + List hostNodes = chooseHostNodes(settings, settings.getNodes(), vcpus, memoryKib, topology); + if (hostNodes == null) { + throw new NumaPlacementException(String.format("The host does not have %d NUMA node(s) with %d CPU(s) and %d KiB of %s memory each.", + settings.getNodes(), vcpus / settings.getNodes(), memoryKib / settings.getNodes(), settings.isStrict() ? "available" : "total")); + } + return buildPlan(settings, vcpus, memoryKib, hostNodes); + } + + for (int cells = 1; cells <= topology.getNodes().size(); cells++) { + if (checkEvenSplit(cells, vcpus, memoryKib) != null) { + continue; + } + List hostNodes = chooseHostNodes(settings, cells, vcpus, memoryKib, topology); + if (hostNodes != null) { + return buildPlan(settings, vcpus, memoryKib, hostNodes); + } + } + throw new NumaPlacementException(String.format("The instance (%d vCPU(s), %d KiB) cannot be split evenly over the host's NUMA node(s) with enough CPUs and %s memory on each.", + vcpus, memoryKib, settings.isStrict() ? "available" : "total")); + } + + /** + * @return null when the instance splits evenly over that many cells, otherwise the reason it does not + */ + protected static String checkEvenSplit(int cells, int vcpus, long memoryKib) { + if (vcpus % cells != 0) { + return String.format("%d vCPU(s) cannot be split evenly over %d NUMA node(s).", vcpus, cells); + } + if (memoryKib % cells != 0) { + return String.format("%d KiB of memory cannot be split evenly over %d NUMA node(s).", memoryKib, cells); + } + return null; + } + + /** + * Picks the host nodes with the most memory to offer among those that can hold one cell. + * A strict instance needs the memory to be available now, when the host says how much is. + * + * @return the chosen host nodes in id order, or null when too few can hold a cell + */ + protected static List chooseHostNodes(NumaSettings settings, int cells, int vcpus, long memoryKib, HostNumaTopology topology) { + int cellVcpus = vcpus / cells; + long cellMemoryKib = memoryKib / cells; + List candidates = new ArrayList<>(); + for (HostNumaNode node : topology.getNodes()) { + long memory = settings.isStrict() ? node.getRankingMemoryKib() : node.getMemoryKib(); + if (node.getCpuCount() >= cellVcpus && memory >= cellMemoryKib) { + candidates.add(node); + } + } + if (candidates.size() < cells) { + return null; + } + candidates.sort(Comparator.comparingLong(HostNumaNode::getRankingMemoryKib).reversed().thenComparingInt(HostNumaNode::getId)); + List chosen = new ArrayList<>(candidates.subList(0, cells)); + chosen.sort(Comparator.comparingInt(HostNumaNode::getId)); + return chosen; + } + + private static GuestNumaPlan buildPlan(NumaSettings settings, int vcpus, long memoryKib, List hostNodes) { + int cellVcpus = vcpus / hostNodes.size(); + long cellMemoryKib = memoryKib / hostNodes.size(); + List cells = new ArrayList<>(); + for (int id = 0; id < hostNodes.size(); id++) { + cells.add(new GuestNumaPlan.Cell(id, id * cellVcpus, (id + 1) * cellVcpus - 1, cellMemoryKib, hostNodes.get(id))); + } + return new GuestNumaPlan(settings, cells); + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/HostNumaNode.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/HostNumaNode.java new file mode 100644 index 000000000000..7894881d2e2b --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/HostNumaNode.java @@ -0,0 +1,98 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; + +/** + * One NUMA node of a hypervisor host: the CPUs guests may use and its memory. + */ +public class HostNumaNode { + + public static final long UNKNOWN = -1; + + private final int id; + private final List cpus; + private final int cpuCount; + private final long memoryKib; + private final long availableKib; + + public HostNumaNode(int id, Collection cpus, long memoryKib) { + this(id, cpus, memoryKib, UNKNOWN); + } + + /** + * @param availableKib memory that can be given to a guest now, or {@link #UNKNOWN} + */ + public HostNumaNode(int id, Collection cpus, long memoryKib, long availableKib) { + this.id = id; + this.cpus = Collections.unmodifiableList(new ArrayList<>(new TreeSet<>(cpus))); + this.cpuCount = this.cpus.size(); + this.memoryKib = memoryKib; + this.availableKib = availableKib; + } + + /** + * A node known only by its size, which is how the management server reads it from the host details. + */ + public HostNumaNode(int id, int cpuCount, long memoryKib) { + this.id = id; + this.cpus = Collections.emptyList(); + this.cpuCount = cpuCount; + this.memoryKib = memoryKib; + this.availableKib = UNKNOWN; + } + + public int getId() { + return id; + } + + /** + * @return the CPUs guests may use; empty when only their number is known + */ + public List getCpus() { + return cpus; + } + + public int getCpuCount() { + return cpuCount; + } + + public long getMemoryKib() { + return memoryKib; + } + + public long getAvailableKib() { + return availableKib; + } + + /** + * @return the memory to rank this node by: what is available now when known, otherwise its total + */ + public long getRankingMemoryKib() { + return availableKib == UNKNOWN ? memoryKib : availableKib; + } + + @Override + public String toString() { + return String.format("HostNumaNode{id=%d, cpus=%d, memoryKib=%d, availableKib=%d}", id, cpuCount, memoryKib, availableKib); + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/HostNumaTopology.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/HostNumaTopology.java new file mode 100644 index 000000000000..2379cd2efbe7 --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/HostNumaTopology.java @@ -0,0 +1,109 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; + +/** + * The NUMA layout of a hypervisor host. The KVM agent reports it as host details and the management server reads it + * back from them. + */ +public class HostNumaTopology { + + /** Host detail listing the ids of the host's NUMA nodes, such as "0,1". */ + public static final String HOST_NUMA_NODES = "host.numa.nodes"; + /** Prefix of the host detail of one NUMA node. Its value is the number of CPUs guests may use on the node and its memory in KiB, such as "20;65536000". */ + public static final String HOST_NUMA_NODE_PREFIX = "host.numa.node."; + + protected static final int MAX_DETAIL_LENGTH = 255; + + private final List nodes; + + public HostNumaTopology(List nodes) { + List sorted = new ArrayList<>(nodes); + sorted.sort(Comparator.comparingInt(HostNumaNode::getId)); + this.nodes = Collections.unmodifiableList(sorted); + } + + public List getNodes() { + return nodes; + } + + /** + * @return the host details describing this layout; empty when there is nothing to report or a value would not fit + */ + public Map toDetails() { + Map details = new LinkedHashMap<>(); + if (nodes.isEmpty()) { + return details; + } + details.put(HOST_NUMA_NODES, nodes.stream().map(node -> String.valueOf(node.getId())).collect(Collectors.joining(","))); + for (HostNumaNode node : nodes) { + details.put(HOST_NUMA_NODE_PREFIX + node.getId(), node.getCpuCount() + ";" + node.getMemoryKib()); + } + for (String value : details.values()) { + if (value.length() > MAX_DETAIL_LENGTH) { + return new LinkedHashMap<>(); + } + } + return details; + } + + /** + * @return the layout the host reported, or null when the host details hold none or it cannot be read + */ + public static HostNumaTopology fromDetails(Map details) { + if (details == null || StringUtils.isBlank(details.get(HOST_NUMA_NODES))) { + return null; + } + List nodes = new ArrayList<>(); + try { + for (String id : details.get(HOST_NUMA_NODES).split(",")) { + int nodeId = Integer.parseInt(id.trim()); + String value = details.get(HOST_NUMA_NODE_PREFIX + nodeId); + if (value == null) { + return null; + } + String[] parts = value.split(";", -1); + if (parts.length != 2) { + return null; + } + int cpuCount = Integer.parseInt(parts[0].trim()); + if (cpuCount < 0) { + return null; + } + nodes.add(new HostNumaNode(nodeId, cpuCount, Long.parseLong(parts[1].trim()))); + } + } catch (IllegalArgumentException e) { + return null; + } + return new HostNumaTopology(nodes); + } + + @Override + public String toString() { + return "HostNumaTopology" + nodes; + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/NumaPlacementException.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/NumaPlacementException.java new file mode 100644 index 000000000000..0eba84650496 --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/NumaPlacementException.java @@ -0,0 +1,29 @@ +// 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 org.apache.cloudstack.utils.numa; + +/** + * A NUMA-aware instance cannot be laid out on a host. The message says why. + */ +public class NumaPlacementException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public NumaPlacementException(String message) { + super(message); + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/numa/NumaSettings.java b/utils/src/main/java/org/apache/cloudstack/utils/numa/NumaSettings.java new file mode 100644 index 000000000000..33ed59c9ed2f --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/numa/NumaSettings.java @@ -0,0 +1,149 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +/** + * The NUMA settings of a compute offering, as the management server and the KVM agent read them. + */ +public class NumaSettings { + + /** Whether to build guest NUMA nodes and bind their memory: none, preferred or strict. */ + public static final String POLICY = "numa.policy"; + /** Number of guest NUMA nodes: auto, or a number from 1 up. */ + public static final String NODES = "numa.nodes"; + /** Whether the vCPUs of a guest node are pinned to the CPUs of its host node: node or none. */ + public static final String PIN = "numa.pin"; + + public static final String AUTO = "auto"; + public static final List KEYS = Arrays.asList(POLICY, NODES, PIN); + + public enum Policy { + NONE, PREFERRED, STRICT; + + public static Policy fromString(String value) { + if (StringUtils.isBlank(value)) { + return NONE; + } + for (Policy policy : values()) { + if (policy.name().equalsIgnoreCase(value.trim())) { + return policy; + } + } + throw new IllegalArgumentException(String.format("Invalid value '%s' for %s. Use none, preferred or strict.", value, POLICY)); + } + + @Override + public String toString() { + return name().toLowerCase(); + } + } + + public enum Pin { + NODE, NONE; + + public static Pin fromString(String value) { + if (StringUtils.isBlank(value)) { + return NODE; + } + for (Pin pin : values()) { + if (pin.name().equalsIgnoreCase(value.trim())) { + return pin; + } + } + throw new IllegalArgumentException(String.format("Invalid value '%s' for %s. Use node or none.", value, PIN)); + } + + @Override + public String toString() { + return name().toLowerCase(); + } + } + + private final Policy policy; + private final int nodes; + private final Pin pin; + + /** + * @param nodes the number of guest NUMA nodes, or 0 to let CloudStack choose + */ + public NumaSettings(Policy policy, int nodes, Pin pin) { + this.policy = policy; + this.nodes = nodes; + this.pin = pin; + } + + /** + * Reads the settings from a details map. + * + * @throws IllegalArgumentException when a value is not valid + */ + public static NumaSettings fromDetails(Map details) { + if (details == null) { + return new NumaSettings(Policy.NONE, 0, Pin.NODE); + } + return new NumaSettings(Policy.fromString(details.get(POLICY)), parseNodes(details.get(NODES)), Pin.fromString(details.get(PIN))); + } + + protected static int parseNodes(String value) { + if (StringUtils.isBlank(value) || AUTO.equalsIgnoreCase(value.trim())) { + return 0; + } + try { + int nodes = Integer.parseInt(value.trim()); + if (nodes >= 1) { + return nodes; + } + } catch (NumberFormatException e) { + // reported below + } + throw new IllegalArgumentException(String.format("Invalid value '%s' for %s. Use auto or a number from 1 up.", value, NODES)); + } + + public Policy getPolicy() { + return policy; + } + + /** + * @return the number of guest NUMA nodes, or 0 when CloudStack chooses + */ + public int getNodes() { + return nodes; + } + + public Pin getPin() { + return pin; + } + + public boolean isEnabled() { + return policy != Policy.NONE; + } + + public boolean isStrict() { + return policy == Policy.STRICT; + } + + @Override + public String toString() { + return String.format("NumaSettings{policy=%s, nodes=%s, pin=%s}", policy, nodes == 0 ? AUTO : String.valueOf(nodes), pin); + } +} diff --git a/utils/src/test/java/org/apache/cloudstack/utils/numa/GuestNumaPlannerTest.java b/utils/src/test/java/org/apache/cloudstack/utils/numa/GuestNumaPlannerTest.java new file mode 100644 index 000000000000..68bd2fc9cf6d --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/numa/GuestNumaPlannerTest.java @@ -0,0 +1,182 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; + +public class GuestNumaPlannerTest { + + private static final long GIB_IN_KIB = 1024L * 1024L; + + private static final NumaSettings STRICT_AUTO = new NumaSettings(NumaSettings.Policy.STRICT, 0, NumaSettings.Pin.NODE); + private static final NumaSettings PREFERRED_AUTO = new NumaSettings(NumaSettings.Policy.PREFERRED, 0, NumaSettings.Pin.NODE); + + private HostNumaTopology twoNodeHost(long availableOnNode0Kib, long availableOnNode1Kib) { + return new HostNumaTopology(Arrays.asList( + new HostNumaNode(0, CpuList.parse("0-9,20-29"), 96 * GIB_IN_KIB, availableOnNode0Kib), + new HostNumaNode(1, CpuList.parse("10-19,30-39"), 96 * GIB_IN_KIB, availableOnNode1Kib))); + } + + private HostNumaTopology twoNodeHost() { + return twoNodeHost(HostNumaNode.UNKNOWN, HostNumaNode.UNKNOWN); + } + + @Test + public void planPutsASmallInstanceOnOneNode() { + GuestNumaPlan plan = GuestNumaPlanner.plan(STRICT_AUTO, 8, 32 * GIB_IN_KIB, twoNodeHost()); + + Assert.assertEquals(1, plan.getCells().size()); + GuestNumaPlan.Cell cell = plan.getCells().get(0); + Assert.assertEquals(0, cell.getId()); + Assert.assertEquals("0-7", cell.getVcpus()); + Assert.assertEquals(32 * GIB_IN_KIB, cell.getMemoryKib()); + Assert.assertEquals(0, cell.getHostNode().getId()); + Assert.assertEquals("0-9,20-29", cell.getHostCpus()); + Assert.assertEquals(8, plan.getVcpusPerCell()); + } + + @Test + public void planPrefersTheNodeWithTheMostAvailableMemory() { + GuestNumaPlan plan = GuestNumaPlanner.plan(STRICT_AUTO, 8, 32 * GIB_IN_KIB, twoNodeHost(40 * GIB_IN_KIB, 80 * GIB_IN_KIB)); + + Assert.assertEquals(1, plan.getCells().size()); + Assert.assertEquals(1, plan.getCells().get(0).getHostNode().getId()); + } + + @Test + public void planSplitsAnInstanceThatDoesNotFitOneNode() { + GuestNumaPlan plan = GuestNumaPlanner.plan(STRICT_AUTO, 32, 128 * GIB_IN_KIB, twoNodeHost()); + + Assert.assertEquals(2, plan.getCells().size()); + Assert.assertEquals("0-15", plan.getCells().get(0).getVcpus()); + Assert.assertEquals("16-31", plan.getCells().get(1).getVcpus()); + Assert.assertEquals(64 * GIB_IN_KIB, plan.getCells().get(0).getMemoryKib()); + Assert.assertEquals(64 * GIB_IN_KIB, plan.getCells().get(1).getMemoryKib()); + Assert.assertEquals(0, plan.getCells().get(0).getHostNode().getId()); + Assert.assertEquals(1, plan.getCells().get(1).getHostNode().getId()); + } + + @Test + public void planUsesTheRequestedNumberOfNodes() { + NumaSettings twoNodes = new NumaSettings(NumaSettings.Policy.STRICT, 2, NumaSettings.Pin.NODE); + + GuestNumaPlan plan = GuestNumaPlanner.plan(twoNodes, 8, 32 * GIB_IN_KIB, twoNodeHost()); + + Assert.assertEquals(2, plan.getCells().size()); + Assert.assertEquals("0-3", plan.getCells().get(0).getVcpus()); + Assert.assertEquals("4-7", plan.getCells().get(1).getVcpus()); + } + + @Test + public void planGivesASingleVcpuCellAPlainVcpuNumber() { + NumaSettings twoNodes = new NumaSettings(NumaSettings.Policy.STRICT, 2, NumaSettings.Pin.NODE); + + GuestNumaPlan plan = GuestNumaPlanner.plan(twoNodes, 2, 4 * GIB_IN_KIB, twoNodeHost()); + + Assert.assertEquals("0", plan.getCells().get(0).getVcpus()); + Assert.assertEquals("1", plan.getCells().get(1).getVcpus()); + } + + @Test + public void planRefusesAnUnevenVcpuSplit() { + NumaSettings twoNodes = new NumaSettings(NumaSettings.Policy.STRICT, 2, NumaSettings.Pin.NODE); + + NumaPlacementException e = Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(twoNodes, 7, 32 * GIB_IN_KIB, twoNodeHost())); + + Assert.assertTrue(e.getMessage(), e.getMessage().contains("7 vCPU(s) cannot be split evenly over 2 NUMA node(s)")); + } + + @Test + public void planRefusesAnUnevenMemorySplit() { + NumaSettings twoNodes = new NumaSettings(NumaSettings.Policy.STRICT, 2, NumaSettings.Pin.NODE); + + NumaPlacementException e = Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(twoNodes, 8, 1025, twoNodeHost())); + + Assert.assertTrue(e.getMessage(), e.getMessage().contains("1025 KiB of memory cannot be split evenly over 2 NUMA node(s)")); + } + + @Test + public void planRefusesMoreNodesThanTheHostHas() { + NumaSettings fourNodes = new NumaSettings(NumaSettings.Policy.STRICT, 4, NumaSettings.Pin.NODE); + + NumaPlacementException e = Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(fourNodes, 8, 32 * GIB_IN_KIB, twoNodeHost())); + + Assert.assertTrue(e.getMessage(), e.getMessage().contains("does not have 4 NUMA node(s)")); + } + + @Test + public void planRefusesAnInstanceLargerThanTheHostNodes() { + Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(STRICT_AUTO, 64, 128 * GIB_IN_KIB, twoNodeHost())); + Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(STRICT_AUTO, 32, 256 * GIB_IN_KIB, twoNodeHost())); + } + + @Test + public void strictPlanNeedsTheMemoryToBeAvailableNow() { + HostNumaTopology busyHost = twoNodeHost(16 * GIB_IN_KIB, 16 * GIB_IN_KIB); + + Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(STRICT_AUTO, 8, 64 * GIB_IN_KIB, busyHost)); + } + + @Test + public void strictPlanSplitsWhenNoSingleNodeHasTheMemoryAvailable() { + HostNumaTopology busyHost = twoNodeHost(40 * GIB_IN_KIB, 40 * GIB_IN_KIB); + + GuestNumaPlan plan = GuestNumaPlanner.plan(STRICT_AUTO, 8, 64 * GIB_IN_KIB, busyHost); + + Assert.assertEquals(2, plan.getCells().size()); + } + + @Test + public void preferredPlanOnlyNeedsTheNodeToBeLargeEnough() { + HostNumaTopology busyHost = twoNodeHost(16 * GIB_IN_KIB, 24 * GIB_IN_KIB); + + GuestNumaPlan plan = GuestNumaPlanner.plan(PREFERRED_AUTO, 8, 64 * GIB_IN_KIB, busyHost); + + Assert.assertEquals(1, plan.getCells().size()); + Assert.assertEquals(1, plan.getCells().get(0).getHostNode().getId()); + } + + @Test + public void planRefusesAHostWithoutANumaLayout() { + Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(STRICT_AUTO, 8, 32 * GIB_IN_KIB, null)); + Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(STRICT_AUTO, 8, 32 * GIB_IN_KIB, new HostNumaTopology(Collections.emptyList()))); + } + + @Test + public void planRefusesAnInstanceThatIsNotNumaAware() { + NumaSettings none = NumaSettings.fromDetails(null); + + Assert.assertThrows(NumaPlacementException.class, () -> GuestNumaPlanner.plan(none, 8, 32 * GIB_IN_KIB, twoNodeHost())); + } + + @Test + public void planLeavesOutNodesWithTooFewCpus() { + List nodes = Arrays.asList( + new HostNumaNode(0, CpuList.parse("0-3"), 96 * GIB_IN_KIB), + new HostNumaNode(1, CpuList.parse("4-19"), 96 * GIB_IN_KIB)); + + GuestNumaPlan plan = GuestNumaPlanner.plan(STRICT_AUTO, 8, 32 * GIB_IN_KIB, new HostNumaTopology(nodes)); + + Assert.assertEquals(1, plan.getCells().size()); + Assert.assertEquals(1, plan.getCells().get(0).getHostNode().getId()); + } +} diff --git a/utils/src/test/java/org/apache/cloudstack/utils/numa/HostNumaTopologyTest.java b/utils/src/test/java/org/apache/cloudstack/utils/numa/HostNumaTopologyTest.java new file mode 100644 index 000000000000..c79fe3ec9563 --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/numa/HostNumaTopologyTest.java @@ -0,0 +1,123 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class HostNumaTopologyTest { + + @Test + public void cpuListParsesAndFormatsRanges() { + Assert.assertEquals(Arrays.asList(0, 1, 2, 3, 8, 10, 11), CpuList.parse(" 0-3, 8,10-11 ")); + Assert.assertEquals(Arrays.asList(1, 2, 3), CpuList.parse("3,1-2,2")); + Assert.assertTrue(CpuList.parse("").isEmpty()); + Assert.assertTrue(CpuList.parse(null).isEmpty()); + + Assert.assertEquals("0-3,8,10-11", CpuList.format(Arrays.asList(11, 10, 8, 3, 2, 1, 0))); + Assert.assertEquals("5", CpuList.format(Collections.singletonList(5))); + Assert.assertEquals("", CpuList.format(Collections.emptyList())); + } + + @Test + public void cpuListRefusesInvalidLists() { + for (String list : Arrays.asList("a", "3-1", "0-", "-1", "0,,1")) { + Assert.assertThrows(list, IllegalArgumentException.class, () -> CpuList.parse(list)); + } + } + + @Test + public void detailsRoundTrip() { + HostNumaTopology topology = new HostNumaTopology(Arrays.asList( + new HostNumaNode(1, CpuList.parse("10-19,30-39"), 98765432L), + new HostNumaNode(0, CpuList.parse("0-9,20-29"), 98765000L))); + + Map details = topology.toDetails(); + + Assert.assertEquals(3, details.size()); + Assert.assertEquals("0,1", details.get(HostNumaTopology.HOST_NUMA_NODES)); + Assert.assertEquals("20;98765000", details.get(HostNumaTopology.HOST_NUMA_NODE_PREFIX + "0")); + Assert.assertEquals("20;98765432", details.get(HostNumaTopology.HOST_NUMA_NODE_PREFIX + "1")); + + HostNumaTopology read = HostNumaTopology.fromDetails(details); + + Assert.assertEquals(2, read.getNodes().size()); + Assert.assertEquals(0, read.getNodes().get(0).getId()); + Assert.assertEquals(20, read.getNodes().get(0).getCpuCount()); + Assert.assertTrue(read.getNodes().get(0).getCpus().isEmpty()); + Assert.assertEquals(98765000L, read.getNodes().get(0).getMemoryKib()); + Assert.assertEquals(HostNumaNode.UNKNOWN, read.getNodes().get(0).getAvailableKib()); + Assert.assertEquals(98765000L, read.getNodes().get(0).getRankingMemoryKib()); + Assert.assertEquals(1, read.getNodes().get(1).getId()); + } + + @Test + public void toDetailsReportsNothingForAHostWithoutNodes() { + Assert.assertTrue(new HostNumaTopology(Collections.emptyList()).toDetails().isEmpty()); + } + + @Test + public void toDetailsReportsNothingWhenAValueWouldNotFit() { + List manyNodes = new ArrayList<>(); + for (int id = 0; id < 100; id++) { + manyNodes.add(new HostNumaNode(id, 4, 1024L)); + } + HostNumaTopology topology = new HostNumaTopology(manyNodes); + + Assert.assertTrue(topology.toDetails().isEmpty()); + } + + @Test + public void fromDetailsReturnsNullWhenTheHostReportedNoLayout() { + Assert.assertNull(HostNumaTopology.fromDetails(null)); + Assert.assertNull(HostNumaTopology.fromDetails(new HashMap<>())); + } + + @Test + public void fromDetailsReturnsNullForALayoutItCannotRead() { + Map missingNode = new HashMap<>(); + missingNode.put(HostNumaTopology.HOST_NUMA_NODES, "0,1"); + missingNode.put(HostNumaTopology.HOST_NUMA_NODE_PREFIX + "0", "20;1024"); + Assert.assertNull(HostNumaTopology.fromDetails(missingNode)); + + for (String value : Arrays.asList("20", "20;", "20;abc", "x;1024", "0-9;1024", "-1;1024", "20;1024;1")) { + Map details = new HashMap<>(); + details.put(HostNumaTopology.HOST_NUMA_NODES, "0"); + details.put(HostNumaTopology.HOST_NUMA_NODE_PREFIX + "0", value); + Assert.assertNull(value, HostNumaTopology.fromDetails(details)); + } + + Map badIds = new HashMap<>(); + badIds.put(HostNumaTopology.HOST_NUMA_NODES, "zero"); + Assert.assertNull(HostNumaTopology.fromDetails(badIds)); + } + + @Test + public void availableMemoryRanksANodeWhenKnown() { + HostNumaNode node = new HostNumaNode(0, CpuList.parse("0-3"), 1000L, 400L); + + Assert.assertEquals(400L, node.getRankingMemoryKib()); + Assert.assertEquals(1000L, node.getMemoryKib()); + } +} diff --git a/utils/src/test/java/org/apache/cloudstack/utils/numa/NumaSettingsTest.java b/utils/src/test/java/org/apache/cloudstack/utils/numa/NumaSettingsTest.java new file mode 100644 index 000000000000..3e5d8ad9cb31 --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/numa/NumaSettingsTest.java @@ -0,0 +1,88 @@ +// 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 org.apache.cloudstack.utils.numa; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class NumaSettingsTest { + + private Map details(String policy, String nodes, String pin) { + Map details = new HashMap<>(); + details.put(NumaSettings.POLICY, policy); + details.put(NumaSettings.NODES, nodes); + details.put(NumaSettings.PIN, pin); + return details; + } + + @Test + public void fromDetailsDefaultsToNotNumaAware() { + for (Map details : Arrays.asList(null, Collections.emptyMap(), details(null, null, null), details(" ", "", ""))) { + NumaSettings settings = NumaSettings.fromDetails(details); + + Assert.assertFalse(settings.isEnabled()); + Assert.assertEquals(NumaSettings.Policy.NONE, settings.getPolicy()); + Assert.assertEquals(0, settings.getNodes()); + Assert.assertEquals(NumaSettings.Pin.NODE, settings.getPin()); + } + } + + @Test + public void fromDetailsReadsEachSetting() { + NumaSettings settings = NumaSettings.fromDetails(details("Strict", " 2 ", "none")); + + Assert.assertTrue(settings.isEnabled()); + Assert.assertTrue(settings.isStrict()); + Assert.assertEquals(2, settings.getNodes()); + Assert.assertEquals(NumaSettings.Pin.NONE, settings.getPin()); + + settings = NumaSettings.fromDetails(details("preferred", "AUTO", "node")); + + Assert.assertTrue(settings.isEnabled()); + Assert.assertFalse(settings.isStrict()); + Assert.assertEquals(0, settings.getNodes()); + Assert.assertEquals(NumaSettings.Pin.NODE, settings.getPin()); + } + + @Test + public void fromDetailsRefusesInvalidValues() { + Map> invalid = new LinkedHashMap<>(); + invalid.put(NumaSettings.POLICY, details("always", null, null)); + invalid.put(NumaSettings.NODES, details("strict", "0", null)); + invalid.put(NumaSettings.NODES + " ", details("strict", "-1", null)); + invalid.put(NumaSettings.NODES + " ", details("strict", "two", null)); + invalid.put(NumaSettings.PIN, details("strict", null, "core")); + + for (Map.Entry> entry : invalid.entrySet()) { + IllegalArgumentException e = Assert.assertThrows(IllegalArgumentException.class, () -> NumaSettings.fromDetails(entry.getValue())); + Assert.assertTrue(e.getMessage(), e.getMessage().contains(entry.getKey().trim())); + } + } + + @Test + public void policyAndPinPrintInLowerCase() { + Assert.assertEquals("strict", NumaSettings.Policy.STRICT.toString()); + Assert.assertEquals("preferred", NumaSettings.Policy.PREFERRED.toString()); + Assert.assertEquals("node", NumaSettings.Pin.NODE.toString()); + } +}