Управление числом vCPU и ядер в виртуальной машине
10.02.2020
itpro
Hyper-V, KVM, VMware, Windows 10, Виртуализация
комментария 2
При создании виртуальных машин на различных гипервизорах (VMWare, KVM, Hyper-V и т.д.) вы можете обратить внимание, что иногда виртуальная машина может не видеть все выделенные ей виртуальные ядра (vCPU). В нашем случае виртуальной машине на KVM были выделены 8 vCPU, на нее установлена Windows 10. Однако Windows определяла эти ядра как отдельные процессоры, из которых можно использовать только 2 vCPU.
Виртуальная машина Windows 10 не видит все ядра
Если открыть диспетчер устройств Windows, можно убедится, что все выделенные ядра видны в качестве 8 отдельных виртуальных процессоров типа QEMU Virtual CPU version 2,5.
При этом в свойствах Windows 10 (Computer -> Properties) и в Task Manage видно, что на компьютере доступны только 2 процессора QEMU Virtual CPU.
То есть сколько бы вы не добавили виртуальных ядер, Windows 10 все равно сможет использовать только два. При этом соседний виртуальный сервер с Window Server 2016 на этом же гипервизоре видит все 16 выделенных ему vCPU.
Количество поддерживаемых процессоров в Windows 10
Проблема заключается в том, что в десктопных редакциях Windows (Windows 10/8.1/7) есть ограничение на максимальное количество физических процессоров (сокетов), которое компьютер может использовать:
- Windows 10 Home – 1 CPU
- Windows 10 Professional – 2 CPU
- Windows 10 Workstation – до 4 CPU
- Windows Server 2016 – до 64 CPU
Однако это ограничение не распространяется на ядра. Т.е. для повышения производительности вы можете использовать процессор с большим количеством ядер. Большинство гипервизоров умеют предоставлять vCPU в виде процессоров, процессорных ядер или даже потоков. Т.е. вместо 8 виртуальных CPU вы можете предоставить vCPU в виде 2 сокетов по 4 ядра в каждом. Рассмотрим, как в различных системах виртуализации выделить виртуальные процессоры в виде ядер и как это связать с архитектурой NUMA, использующейся в современных процессорах.
Управление виртуальными ядрами и vCPU в KVM
В моей виртуальной машине KVM c Windows 10, все назначенные виртуальные ядра считаются отдельными процессорами.
Чтобы использовать все ресурсы CPU, выделенные виртуальной машине нужно, чтобы виртуальная машина видела не 8 процессоров, а один 8-ядерный процессор, 2 процессора по 4 ядра или 1 процессор с 4 ядрами по 2 потока. Попробуем изменить способ назначения виртуальных ядер для ВМ на KVM.
Выключите виртуальную машину:
# virsh shutdown server.vpn.ru – где server.vpn.ru это имя виртуальной машины.
Выведите текущую XML конфигурацию виртуальной машины KVM:
# virsh dumpxml server.vpn.ru
Нам интересен блок с описанием процессоров:
Как видим, у нас указано просто 8 vCPU. Изменим конфигурацию:
# virsh edit server.vpn.ru
И после </features> добавим:
- host-passthrough — режим эмуляции при котором на виртуальной машине будет показан физический процессор узла кластера (ноды).
- sockets=’1′ — указываем что процессор 1
- cores=’4′ — указываем, что процессор имеет 4 ядра
- threads=’2′ — указываем, что ядра у нас по 2 потока
Сохраните конфигурационный файл и запустите ВМ. Авторизуйтесь в гостевой ВМ с Windows 10 и в Task Manager или Resource Monitor проверьте, что ОС видит все выделенные виртуальные ядра.
Также в свойства системы теперь стал отображаться физический процессор хоста Intel(R) Xeon(R) Silver 4114 CPU, а не виртуальный.
Так нам удалось решить проблему с нагрузкой на ВМ, так как двух ядер не хватало для полноценной работы приложений.
Настройка виртуальных процессоров и количества ядер в VMWare
Вы можете изменить способ презентации vCPU для виртуальной машины VMWare из интерфейса vSphere Client.
- Выключите ВМ и откройте ее настройки;
- Разверните секцию CPU;
- Изменим конфигурацию ВМ так, чтобы гостевая ОС видела 2 процессора по 4 ядра. Измените значение Cores per Socket на 4. Это означает, что гостевая ОС будет видеть два четырех –ядерных процессора (2 сокета по 4 ядра);
- Сохраните изменения и запустите ВМ.
Архитектура NUMA и виртуальные vCPU
Есть еще несколько аспектов назначения vCPU и ядер виртуальным машинам, которые нужно понимать.
При назначении ядер на сокете учитывайте наличие NUMA архитектуры (используется в большинстве современных CPU). Не рекомендуется назначать вашей ВМ количество ядер на сокет (и общее количество vCPU) больше, чем доступно ядер на вашем физическом сокете/процессоре (ноде NUMA). При размещении на одной физической ноде NUMA, виртуальная машина сможет использовать быструю локальную RAM, доступную на конкретной ноде NUMA. Иначе для выполнения операции процессам придется ждать ответа от другой ноды NUMA (что несколько более долго).
Если вы назначаете для ВМ два отдельных виртуальных сокета, то гипервизор может их запускать на разных нодах NUMA. Что не лучшим образом скажется на производительности ВМ.
Если количество требуемых vCPU превышает количество ядер на 1 физическом сокете (ноде NUMA), нужно создать несколько виртуальных сокетов (процессоров) с необходимым количество ядер. Также не желательно использовать нечетное количество процессоров (лучше добавить 1 vCPU)
Это позволит сохранить производительность виртуальной машины.
Например, для 2 процессорного хоста с 10 ядрами (суммарно доступно 40 vCPU с учетом Hyper—Threading), при настройке vCPU для ВМ оптимально использовать такие конфигурации:
Требуемое количество vCPU | Количество виртуальных сокетов в настройках ВМ | Количество ядер на виртуальном процессоре в настройках ВМ |
1 | 1 | 1 |
…… | ||
10 | 1 | 10 |
11 | Не оптимально | |
12 | 2 | 6 |
…… | ||
20 | 2 | 10 |
Например, ВМ с Microsoft SQL Server 2016 Enterprise Edition 16 vCPU в конфигурации 8 сокетов по 2 ядра будет работать хуже, чем в конфигурации 2 сокета по 8 ядер.
Также не забывайте, что некоторые приложения лицензируются по физическим сокетам (так было в старых версиях SQL Server). Иногда вам просто выгоднее лицензировать один многоядерный процессор, чем несколько процессоров с меньшим количеством ядер.
NUMA | vNUMA | Should we consider “Cores per socket” VM configuration in vSphere?
There’s lot of information on NUMA implementation from processors manufacturers and software vendors, which can sometimes become a challenge and you end up re-visiting multiple blogs and VMware PDF files — This blog is a consolidation (one reference point) to understand NUMA, vNUMA, “why it is important in the world of hypervisors?”, changes in vNUMA from vSphere v6.5 onwards, configuration overrides, Rule of thumb, recommendations on “Cores per Socket” configuration for vSphere v6.7 and v7.0.
What is NUMA ?
Let’s begin with “UMA” (Uniform Memory Architecture) architecture, which is described as all processors accessing memory through a shared bus (or another type of interconnect). NUMA (Non-Uniform Memory Access), is also a shared memory architecture but it describes the placement of main memory modules with respect to processors in a multiprocessor system i.e. each processor has its own local memory module that it can access directly with a distinctive performance advantage. At the same time, it can also access any memory module belonging to another processor using a shared bus.
Why is it important in the world of hypervisor’s?
In general, NUMA awareness is important whenever you are using a server that supports two or more physical processor sockets. For example, in a two-socket server (image above), processor 1 accessing the memory that is directly attached to processor 0 will be slower than processor 1 accessing the memory directly attached to it because processor 1 will have to cross an inter-processor bus. This access is “non-uniform” in the sense that processor 0 will access this memory faster than processor 1 does, due to the longer access distance.
A NUMA Node is referred to as a processor with direct attached memory. Under some (but not all) conditions, accessing memory or devices across NUMA boundaries will result in decreased performance.
This becomes evident for VMs to utilize directly attached memory to the processor its running on, else (in some cases) the VM running will take some form of performance hit.
NUMA on vSphere:
For ESXi, to determine a system behaves like NUMA is done by a setting in BIOS, called “node interleaving” (also known as interleaved memory). If the node interleaving is disabled, ESXi detects the system as NUMA and applies NUMA optimizations. If node interleaving is enabled, ESXi does not detect the system as NUMA. For more information, refer to your server’s documentation.
With vSphere 4.1 the ability to present an option to define vCPU Cores and Socket was first introduced. In vSphere 5, the configuration determined the vNUMA topology exposed to the Operating System.
The intelligent, adaptive NUMA scheduling and memory placement policies in ESXi can manage all virtual machines transparently, so that administrators don’t need to deal with the complexity of balancing virtual machines between nodes by hand.
By default, ESXi NUMA scheduling and related optimizations are enabled only on systems with a total of at least four CPU cores and with at least two CPU cores per NUMA node.
NUMA Override / Advance configuration:
- Manual controls are available to override this default behavior, however, and advanced administrators might prefer to manually set NUMA placement by adding the setting in the VM configuration file:
The value 0 and 1 constrains the VM resourcing scheduling to NUMA nodes 0 and 1.
- On hyper-threaded systems, virtual machines with a number of vCPUs greater than the number of cores in a NUMA node but lower than the number of logical processors in each physical NUMA node might benefit from using logical processors with local memory instead of full cores with remote memory. This behavior can be configured for a specific virtual machine or for all VMs running on the physical host by using the following settings:
– For specific VM ,add the following configuration in the .vmx file (of from the GUI using advance configuration)
– For all VMs to use hyper-threading with NUMA, add the following configuration on the ESXi Host Advance settings:
These are advanced settings designed to help workloads that are cache-intensive, but not CPU intensive.
vNUMA on vSphere
Virtual NUMA (vNUMA) exposes NUMA topology to the guest operating system, allowing NUMA-aware guest operating systems and applications to make the most efficient use of the underlying hardware’s NUMA architecture.
Virtual NUMA, requires virtual hardware version 8 or later, can in some cases provide significant performance benefits for wide virtual machines (that is, virtual machines with more vCPUs than the number of cores in each physical NUMA node), though the benefits depend heavily on the level of NUMA optimization in the guest operating system and applications.
OS and applications potentially encounter remote memory access latencies while expecting local memory latencies after optimizing thread placements. It’s recommended to configure the VM’s “Cores per Socket” config to align with the physical boundaries of the CPU package.
vNUMA with vSphere 6.5 and later:
From vSphere v6.5 and later, vNUMA handling improved – which automatically determines the proper vNUMA topology to present to the guest OS based on the underlying ESXi host. The “Cores per Socket” no longer influences vNUMA or the configuration of the vNUMA topology. The configuration “Cores per Socket” now only affects the presentation of the virtual processors to the guest OS, something potentially relevant for software licensing.
For example: prior to vSphere v6.5, on a dual-socket physical ESXi host with 16 core per socket (for a total of 32 physical cores) – if you create a four-vSocket virtual machine and set cores per socket to four (for a total of 16 vCPUs), vNUMA would have created four vNUMA nodes based on the corespersocket setting. In vSphere 6.5 and later, the guest OS will still see four sockets and four cores per socket, but vNUMA will now create just one 16-core vNUMA node for the entire virtual machine because that virtual machine can be placed in a single physical NUMA node – but wait, see the “The Caveat” later in the blog below.
This new decoupling of the corespersocket setting from vNUMA allows vSphere to automatically determine the best vNUMA topology, unless the VMs Advance Virtual NUMA Attributes.
Considerations:
- “CPU Hot Add” or “CPU Hot Plug” is a feature that allows the addition of vCPUs to a running virtual machine. Enabling this feature, disables vNUMA for the respective virtual machine, resulting in the guest OS seeing a single vNUMA node. This in turn could result in the guest OS making sub-optimal scheduling decisions, leading to reduced performance for applications running in large virtual machines. Therefore, consider the use of this option only if you will need it.
- By default, vNUMA is enabled only for virtual machines with more than eight vCPUs. This feature can be enabled for smaller virtual machines, however, while still allowing ESXi to automatically manage the vNUMA topology. This can be useful for wide virtual machines (that is, virtual machines with more vCPUs than the number of cores in each physical NUMA node) with eight or fewer vCPUs.
vNUMA Overrides/Advance Configuration:
- To enable vNUMA for virtual machines with eight or fewer vCPUs the following configuration value can be added in the .vmx file:
Note: X is the number of vCPUs in the virtual machine.
- To revert the automatic vNUMA topology to old behaviour and directly control vNUMA node sizing being tied to cpuid.coresPerSocket, the following configuration value can be added in the .vmx file:
The Caveat:
The automatic vNUMA node determination from vSphere v6.5 and later is great optimization for handling VM’s CPU and Memory to align with pNUMA however the number virtual sockets does not consider the “cache address space” i.e. L3 cache. Therefore, it is recommended to take caution while configuring “Cores per Socket” and it should be aligned considering the boundaries of the physical CPUs for optimal performance. For more information and deep dive, see Frank Denneman’s blog here.
Rules of Thumb (by “Mark Achtemichuk”), still applies to Sphere v6.7 and 7.0:
- While there are many advanced vNUMA settings, only in rare cases do they need to be changed from defaults.
- Always configure the virtual machine vCPU count to be reflected as Cores per Socket, until you exceed the physical core count of a single physical NUMA node OR until you exceed the total memory available on a single physical NUMA node.
- When you need to configure more vCPUs than there are physical cores in the NUMA node, OR if you assign more memory than a NUMA node contains, evenly divide the vCPU count across the minimum number of NUMA nodes.
- Don’t assign an odd number of vCPUs when the size of your virtual machine, measured by vCPU count or configured memory, exceeds a physical NUMA node.
- Don’t enable vCPU Hot Add unless you’re okay with vNUMA being disabled.
- Don’t create a VM larger than the total number of physical cores of your host.
The table below outlines how a virtual machine should be configured, if the VM’s memory configuration is less than or equal to the pNUMA node memory, to ensure an optimal vNUMA topology and performance regardless of vSphere version:
The table below outlines how a virtual machine should be configured, if the VM’s memory configuration is more then the pNUMA node memory, to ensure an optimal vNUMA topology and performance regardless of vSphere version:
Моя первая виртуальная машина: как не накосячить
Итак, вот перед вами свеженькая организация в vCloud Director, и вам только предстоит создать свою первую виртуальную машину. Сегодня расскажу, какие настройки выбирать при создании виртуальной машины, чтобы она работала и не просила есть. Поехали!
Источник: drive2.ru
Операционная система. Выбирайте современные дистрибутивы. Если берете Windows 2008 R2 и более старую или Linux до ядра 4.19.x, ждите проблем. Каких? Ну, например, вендор уже перестал поддерживать актуальное состояние Windows 2008 R2 аж в 2013 году (EOL). Это означает, что он больше не разрабатывает драйвера под вышедшее с тех пор железо, не модифицирует ОС под новое что угодно. С древними операционками вы точно не сможете использовать все возможности, которые предоставляет современный гипервизор. А уже в эти новогодние праздники остро встанет проблема с безопасностью, так как 14 января 2020 года заканчивается расширенная поддержка Windows Server 2008 R2 и перестанут выходить Security Update.
Cores per socket. Оставляйте 1 ядро на сокет, ставьте столько сокетов, сколько вам нужно виртуальных процессоров. Да, логично наоборот, но правильно так. Если у вас нет специализированных лицензионных требований. Например, вы платите за сокет, а больше сокетов означает больше лицензий. Не ставьте 2/2, чтобы получить 4. Сделайте 4/1. Такую машину гипервизор будет обслуживать оптимальным образом. Scheduler гипервизора будет меньше пенализировать такие ВМ.
Объясню на пальцах. Представьте, что проводник рассаживает пассажиров по вагону, вагон – как в Сапсане. В роли проводника scheduler, пассажиры – это ВМ. Пассажиров, которые едут в одиночку (однопроцессорные ВМ), ему распределить проще всего: их можно посадить на любое место. Семью из 4 человек (4-процессорные ВМ) уже сложнее. Им нужно найти 4 места в одном вагоне. А теперь представим, что все в семье хотят ехать только лицом друг другу, а таких групп мест – 4 вокруг стола – в вагоне только 2. С большой вероятностью такой семье придется пройти в следующий вагон (на следующий тик планирования). Это как раз та ситуация, как если бы вы выбрали 2 сокета по 2 ядра, чтобы получить 4. Скорее всего, придется подождать, чтобы нашлись подходящие места. Так же и с ВМ: ей придется ждать дольше, чем менее “прихотливым” ВМ с 1 сокетом и кучкой процессоров.
Хотя эта история актуальнее для старых версий ESXi. Начиная с 6.5 (но не ранее!) механизм vNUMA отвязан от количества виртуальных сокетов, и старая рекомендация “не плодить сокеты” не так категорична. Но все еще зависит от приложения внутри гостевой ОС.
Hot Add для CPU и Memory. Это опция добавления памяти CPU для работающей виртуальной машины. Казалось бы, прекрасная функция: не нужно гасить машину, чтобы докинуть ей ресурсов. Так вот, не все так просто, и не зря они по дефолту отключены. Лучше и не включать, если вы не знаете, что такое NUMA-топология. Допустим, под капотом облака у нас двухсокетный сервер. На каждом сокете 4 ядра. Работает это именно как 4+4, а не 8 ядер. Такая же тема с памятью: если на каждом сокете 128 ГБ, это не дает в сумме 256 ГБ. Каждый процессорный сокет имеет прямой доступ только к определенным слотам памяти. Каждый сокет вместе с причитающейся ему процессором и памятью – это физическая NUMA-нода.
Если виртуальная машина влезает в размер физической NUMA-ноды, то она исполняется внутри этой ноды. Если виртуалка не умещается в NUMA-ноду, например по памяти, то она будет использовать память из соседней NUMA-ноды. Путь к удаленной памяти будет извилист – через межпроцессорную шину. Работать это будет не так быстро, как если бы виртуалка использовала ресурсы одной ноды.
Когда вы включаете добавления виртуальных процессоров и памяти на горячую, все это идет только в нулевую NUMA-ноду. Например, добавилось еще 4 процессора, и на NUMA-ноде 0 стало 6, а на NUMA-ноде 1 – 2 процессора. Машину немного перекосило, и работает она также косо. Это связано с тем, что при включении vCPU Hot-Plug перестает работать vNUMA, через которую vSphere старается оптимизировать топологию NUMA для ВМ. Поэтому, принимая решение о включении CPU Hot-Add, учитывайте физическую топологию NUMA для обеспечения производительности ВМ. Это очень критично, если по каким-либо причинам в ВМ имеется несколько виртуальных сокетов. В этом случае несоответствие физической топологии вызовет сильное падение производительности: CPU Scheduler сойдет с ума, пытаясь предоставить процессорное время такой ВМ, что вызовет рост CPU Ready и Co-Stop.
Все добавленные виртуальные процессоры (5-8) и память попали на NUMA-ноду 0.
Отдельная история в том, что будет происходить внутри ОС и приложения после таких “добавок”. Поэтому если уж решили пользоваться этой опцией, то проверьте, поддерживает ли ваша ОС такое. Non-NUMA-Aware приложения могут сильно просесть по производительности при расположении на нескольких NUMA-нодах.
Если вы все-таки добавили процессоры или память на горячую, сразу планируйте перезагрузку ВМ (не только ОС) на ближайший запланированный даунтайм.
Галочки не ставим.
Дисковый контроллер (Bus type). Для дисков выбирайте дисковый контроллер Paravirtual. Этот тип контроллера требует установки драйверов в ОС VMware Tools. Paravirtual – это специальное виртуальное устройство, которое создавалось для работы в виртуализации и не эмулирует работу какого-то другого аппаратного устройства. Любая эмуляция аппаратного устройства всегда работает медленнее.
Если вы не хотите использовать Paravirtual (но почему?), выбирайте LSI Logic SAS. Если ОС не поддерживает и его — LSI Logic Parallel. Никогда не используйте SATA и IDE. ВМ будет медленно работать, в итоге вы не получите производительности, за которой идут в облако.
При инсталляции ОС даже свежая версия Windows может не найти драйвер для Paravirtual адаптера. В этом случае примонтируйте к ВМ два ISO файла — ваш загрузочный образ Windows и диск с VMware tools. На последнем есть необходимый драйвер.
Сетевой адаптер. Правильный выбор – VMXNet3. VMXNet3, как и дисковый адаптер Paravirtual, это паравиртуальное устройство. Оно также требует драйверов, которые входят в VMware Tools.
Если вдруг VMXNet3 не подходит (проявляется какая-то несовместимость), то на крайний случай используйте E1000E. Но не ожидайте от адаптера E1000E производительности больше, чем 1 Гбит.
В общем, E1000E без прямых указаний вендоров не используйте. Казалось бы, оно новее, но сделано для обеспечения еще большей совместимости c legacy.
Вот не надо E1000E.
VMware Tools. Следите, чтобы они были установлены в ОС, запущены и актуальны. В VMware Tools входят драйвера устройств и разные другие компоненты, которые позволяют общаться ОС виртуальной машины с гипервизором, и наоборот. Через них происходит синхронизация времени ОС с хостом виртуализации (отключаемо), ходят heartbeat’ы, которые показывают гипервизору, что виртуалка жива, и прочее. Для работы ОС на виртуальной машине нужны как минимум драйверы сетевой карточки, дискового адаптера. Свежие версии всего вот этого входят в VMware Tools.
По умолчанию актуальные версии Windows и Linux имеют драйвера для работы с виртуальными устройствами VMware, но если у вас будут VMware Tools, то эти драйвера будут всегда свежими. Для Linux рекомендуется использовать open-vm-tools. Это не просто лучшая интеграция с ОС, но и обновление драйверов вместе с системой.
Отдельные диски для данных. Используйте разные виртуальные диски под данные и операционную систему. Да и на физических серверах стоит так делать. Вы сможете отдельно бекапить эти диски (с разным расписанием, например), сможете переключить диск с данными или его клон на другую ВМ и прочее.
Кроме того, новый виртуальный диск также получит дополнительную квоту на дисковую производительность.
Кастомизация. При первом включении ВМ нужно кастомизировать, чтобы все настройки из облака (например выданный облаком IP-адрес) применились к ОС. После уберите эту галку от греха подальше, чтобы нечаянно не сбросить настройки ОС: SID, пароль администратора и т. п.
Конечно, все вышесказанное – упрощенная картина, слова “капитана О” и, вообще, “все же это знают”. Но, как показывает практика, более 70% ВМ в облаке содержат одну или сразу несколько описанных ошибок.
Selecting the number of vCPUs and Cores for a Virtual Machine
Today, let us focus on setting the number of cores per CPU in a virtual machine.
What is a vCPU
A vCPU is the abbreviation for a virtual centralized processing unit. As for a definition, a vCPU represents a portion or share of the underlying, physical CPU that is assigned to a particular virtual machine (VM).
Here are a few terms our Support Engineers suggest to be aware of.
Hypervisor
We can consider a hypervisor as a controller. It sometimes refers to as a virtual machine monitor (VMM). Simply put, a hypervisor is a software to create and run virtual machines (VMs).
It allows one host computer to support multiple guest VMs by virtually sharing its resources such as memory and processing. Hypervisors are smart enough to allocate resources whether a single vCPU or numerous vCPUs.
Socket
We can consider a socket as hardware. It is an array of pins that hold a processor in place and connect the motherboard to the available processing power. The number of sockets is determined by the capacity of the motherboard.
There are differences in sockets depending on which generation CPU it supports.
Thread
A thread is a path of execution within a process. A process contains one or more threads. A thread is also known as a lightweight process. The concept of parallelism is to divide a process into multiple threads.
For instance, having multiple tabs open in a browser represents different threads. For word processing, there can be multiple threads such as one for formatting text and another thread for processing inputs.
Physical Core
A physical core, refers to as processing units, within the CPU. A single physical core may correspond to one or more logical cores.
Logical Core
A logical core makes it possible for a single physical core to perform two or more actions simultaneously. Logical cores made the concept of hyper-threading (HTT) possible.
Newer cores are more like full-fledged CPUs so they are capable of working on multiple tasks simultaneously. However, they are not true CPUs as the physical cores are.
How to Calculate vCPU
The hypervisor controls virtual servers and their resource allocation
It uses a portion of the physical CPU computing resources and allocates it to a vCPU which assigns to a specific VM.
System administrators can use hypervisors to setup different resource allocations with specific VMs configuration and with specific vCPU capabilities.
In the past, there was a rule of thumb that there were eight vCPUs per core. Today, mostly the manufacturer determines the vCPU count.
We calculate it by taking the number of processing threads that a chipset offers per core and multiplying the number of occupied sockets.
Here is how it looks:
Example Calculation of vCPU & Cores
Here, our Support Engineers demonstrate how to calculate vCPU and cores through an example.
First, we need to select a virtual server and CPU. Here, we select Intel Xeon E-2288G as the underlying CPU. Key stats for the Intel Xeon E-2288G include 8 cores/16 threads with a 3.7GHz base clock and a 5.0GHz turbo boost. There is 16MB of onboard cache.
Determine Your Workload & Utilization
First, we need to know the workload and application profiles. By knowing the requirements, we can make an informed decision on the underlying hardware.
Theoretically, if we have small VMs that barely use any CPU time, we can easily get 20-30 VMs from an 8-core server. However, if we have larger workloads such as a database server, we will have far fewer VMs from that same 8 core server.
It is all about resource utilization and allocation.
Next, let us look at some different configuration options. We are doing this just as an example.
Each vCPU allocation to each VM will depend on its specific workload.
CPU Exhaustion & Poor Performance
There is such a thing as CPU exhaustion which can cause poor performance for our virtual machines. The number of virtual cores assigned to a VM is limited.
For example, Windows Server 2008 R2 limits the number of vCPUs as 4 per VM which is extended to 64 in Windows server 2012.
When creating virtual machines in different hypervisors, we may see that sometimes a virtual machine may not see all virtual processor sockets (vCPU) assigned to it.
In our case, 8 vCPUs were assigned to a KVM virtual machine and Windows 10 was installed on it as a guest OS. However, Windows detected this vCPUs as separate processors (not cores) and it could use only 2 of them.
[[Is the calculation heavy? We’d be happy to assist]
Selecting the number of vCPUs and Cores for a Virtual Machine
Moving ahead, we will see the process of Selecting the number of vCPUs and Cores for a Virtual Machine.
Windows 10 Virtual Machine
If we open Windows Device Manager, we can make sure that all allocated cores are visible as 8 separate virtual processors QEMU Virtual CPU version 2.5+.
At the same time, Windows 10 properties (Computer -> Properties) and Task Manager show that only 2 QEMU Virtual processors are available.
It means that Windows 10 is able to use only 2 cores no matter how many of them you will add.
At the same time, a virtual server running Windows Server 2016 on the same hypervisor can see all 16 vCPUs allocated to it.
Number of Processors Supported in Windows
The problem is that desktop Windows versions have a restriction on the maximum number of physical processors a computer can use:
However, this restriction is not related to the number of cores.
In order to improve the performance of the virtual machine, we can use a processor with more cores. Most hypervisors can provide vCPUs as processors, processor cores, or even threads. It means that instead of 8 vCPUs, we can add 2 vCPUs with 4 per socket.
Let us see how to assign virtual processors as cores in different hypervisors and how to bind them to the NUMA architecture used in modern processors.
Managing Virtual Core & vCPU in KVM
In our KVM virtual machine running Windows 10, all assigned virtual cores are considered as separate processors.
To use all CPU resources allocated to a virtual machine, it must see one 8 core processor, 2 vCPUs with 4 cores each, or 1 vCPU with 4 cores in two threads instead of 8 vCPUs.
Now we try to change the allocation of virtual cores for the KVM virtual machine.
Initially, shut down your virtual machine:
Here are the aspects of a KVM virtual machine management from the console using virsh .
Display the current XML configuration of the KVM virtual machine:
We need a block describing the VM CPU settings:
As you can see, 8 vCPUs are set here. Let us change the configuration:
Then, we add the following block after :
Where:
Save the configuration file and start the virtual machine.
Then log in to the Windows 10 guest VM, run Task Manager or Resource Monitor, and make sure that the Windows sees all allocated virtual cores.
A physical processor of the host, Intel(R) Xeon(R) Silver 4114 CPU, now display instead of a virtual one in the system properties.
Here is how we manage to solve the heavy load issue for the VM since two cores have not been enough for the apps to work properly.
[Stuck somewhere in the process? We are here for you]
Setting the number of vCPUs and Cores for a VMWare VM
We can change the way of vCPU presentation for a VMWare virtual machine in the vSphere Client interface.
- Shut the VM down and open its settings
- Then expand the CPU section
- Change the VM configuration so that the guest OS can see 2 processors with 4 cores each. Change the value Cores per Socket to 4. It means that the guest OS will see two 4-core CPUs (2 sockets with 4 cores per socket)
- Finally, save the changes and run the VM.
[Couldn’t set the number? We can help you!]
Virtual Machine vCPU and NUMA Architecture
There are some more aspects of assigning vCPUs and cores to virtual machines.
When assigning the number of cores per socket, we make sure to have NUMA architecture. It is not recommended to assign more cores per socket to a VM than the number of cores available on the physical socket (NUMA node).
When we place it on a single physical NUMA node, a virtual machine will be able to use fast local RAM available on the specific NUMA node. Otherwise, processes will have to wait for the response from another NUMA node.
Generally, if we assign two separate virtual sockets to a VM, the hypervisor can run them on different NUMA nodes. It will affect VM performance.
If the number of vCPUs needed is more than the number of cores on 1 physical socket, we create several virtual sockets with the necessary number of cores.
Also, it is not recommended to use an odd number of processors (it is better to add 1 vCPU). It allows to maintain the virtual machine performance.
For example, it is recommended to use the following configuration for a 2-processor host with 10 cores per socket (40 vCPUs are available in total including Hyper-Threading) when we configure vCPUs for a VM:
vCPU Number Needed Number of Virtual Sockets in the VM Settings Number of Cores per a Virtual Processor in the VM Settings
1 1 1
……
10 1 10
11 Not optimal
12 2 6
……
20 2 10
In a free ESXi version, we cannot create a VM with more than 8 vCPUs.
For example, a VM running Microsoft SQL Server 2016 Enterprise Edition with 16 vCPU will have poorer performance than a VM with 2 Sockets x 8 Cores per Socket.
Also, remember that some applications license depends on the number of physical sockets. Sometimes it is more profitable to license one multicore processor than multiple processors with a less number of cores.
[Looking for an easy fix? Contact us now!]
Conclusion
To conclude, selecting the number of vCPUs and Cores for a Virtual Machine depends on the operating system used and some other factors. Today we saw how our Support Techs go about with this query.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.