Гипервизоры VirtualBox/WorkStation/Fusion/ESXI/Hyper-V/XEN; KVM/QEMU (oVirt/Proxmox VE)

  • (Security, Virtualization) Все что надо знать о безопасности гипервизоров:
    Гипервизор Xen разрешил гостевым системам взламывать хосты
    
    Разработчики гипервизора Xen выкатили пачку экстренных обновлений, закрывающих сразу двадцать уязвимостей. И если восемь из них просто приводят к отказу в обслуживании или утечке памяти, то оставшиеся двенадцать полностью умножают на ноль саму концепцию виртуализации.
    
    Эти дыры позволяют гостевой системе вырваться из своей песочницы и выполнить любой код на стороне физического хоста. 
    
    Главной звездой этого парада уязвимостей стал загрузчик pygrub и библиотека libfsimage. Хакеру достаточно просто скормить системе специально оформленный образ диска в древнем формате iso9660, чтобы вызвать классическое переполнение буфера. После этого гостевая машина получает привилегии, которых с головой хватает для захвата контроля над всем физическим сервером.
    
    Вдобавок исследователи нашли целую россыпь состояний гонки при работе с очередями и таблицами грантов, что позволяет вырваться на свободу даже самому обычному непривилегированному пользователю внутри виртуальной машины.
    
    Под капотом популярного гипервизора творится настоящий хаос. Из-за отсутствия базовых проверок гостевые системы могут читать чужие данные из стека или возвращать себе страницы памяти, которые им вообще не принадлежат.
    
    Linux / Линукс 🥸
  • (Rfc 9411, virtualization) Советы бывалых при тестировании на производительность сетевых решений в виртуализации
    1. использовать numa/cpu core pinning
    2. использовать DirectPath I/O (PCI passthrough или SR-IOV) – подробнее о них смотри ниже
    3. отключить миграцию vmotion/live migration
    4. не забудьте: иногда проще и честнее взять физический DUT, чем бороться с виртуальными ресурсами виртуалки.
  • Пример настроек VM для работы NGFW, ничего нового, но «повторение – мать учения»: проброс сетевой карты pci passthrough, резервация cpu и memory как в esxi, так и в kvm (virsh).

    https://vkvideo.ru/video-208050206_456239039
    https://www.securitylab.ru/analytics/561426.php
    
    
    Screenshot

    Screenshot
  • sudo virsh edit «имя ВМ»
    - Секция <memtune> используется для настройки управления памятью виртуальной машины.
    - Параметр <min_guarantee> устанавливает минимальный объём памяти, который будет гарантированно выделен ВМ.
    - Секция <cputune> используется для управления распределением процессорных ресурсов.
    - <vcpu> указывает количество виртуальных процессоров (VCPU), выделенных для ВМ. <vcpupin> – этот параметры привязывают каждый виртуальный процессор (VCPU) к конкретному физическому ядру (CPU).
    
    
  •  
    
    
  • Виртуализировать приложение, которое задач виртуализации сопротивляется – занятие зачастую сложное и неблагодарное (с linkmeup telecom 98).
  • Open VM Tools (open-vm-tools) – аналог проприетарных дополнительных пакетов в VM типа VMware Tools, которые позволяют с ней лучше взаимодействовать гипервизору (например, гипернация/мягкое отключение) и пользователю (драйвера/разрешение экрана, копипаст, захват мыши). На каких то дистрибутивах установлены сразу, но не включены (sudo systemctl enable –now open-vm-tools), на каких то не установлены (sudo apt install open-vm-tools).
Open VM Tools (open-vm-tools) is the open source implementation of VMware Tools for Linux and FreeBSD guest operating systems.
The open-vm-tools suite is bundled with some Linux operating systems and is installed as a part of the OS, eliminating the need to separately install the suite on guest operating systems. All leading Linux vendors support the open-vm-tools suite on vSphere, Workstation, and Fusion, and bundle open-vm-tools with their product releases. 
List of operating systems with open-vm-tools
Red Hat Enterprise Linux 7.0 and later releases
SUSE Linux Enterprise 12 and later releases
Ubuntu 14.04 and later releases
CentOS 7 and later releases
FreeBSD 10.3, 10.4 & 11.1
Debian 7.x and later releases
Oracle Linux 7 and later
Fedora 19 and later releases
openSUSE 11.x and later releases
  • Для VM чаще всего лучше отключать режимы типо гипернации/отключение экрана и ЖД по времени – если это и работает, то зачастую плохо или просто мешает.
  • Файлы с образом виртуальной машины:
    • name.ova (или name.ovf + name.vmdk) – для в ESXi и остальных сред виртуализации
    • name.vhd (или name.vhdx) – для развертывания в среде Microsoft Hyper-V
    • name.raw – для развертывания в среде KVM
    • name.qcow2 – для развертывания в среде KVM

 

VirtualBox

В контексте виртуализации снимок машины это огонь  – как просто и эффективно решить задачу по бекапу данных – регулярному или разовому.

Мой первый гипервизор. Имеет существенные недостатки:

  • Совместимость – что не запускаетсч на VirtualBox, зачастую работает на VMware Workstation, Player, ESXi.
  • Судя по инфе с сайта eve-ng virtual box не использует аппаратное ускорение, в отличии от Workstation.
VIRTUAL BOX DOESN'T SUPPORT HW ACCELERATION !!! AVOID USING IT !!!!

Сеть

Доступ с host машины по SSH на guest в VirtualBox

Варианты:

  • сделать интерфейс bridged (описание ниже)
  • сделать интерфейс “Виртуальный адаптер хоста” (тоже ниже)
  • сделать проброс порта через NAT (может не работать с антивирусом)

Типы интерфейсов

В VirtualBox очень богатая настройка сетевых интерфейсов виртуальной машины. Самих сетевых интерфейсов можно на виртуалке поднять до четырех, а их настройки очень гибки (отключение, смена MAC, смена типа, проброс портов).

Есть четыре типа интерфейсов (полностью о настройках и типах сетевых подключений тут):

NAT Network Adress Translation – тип по умолчанию. VM находится за “NAT” интерфейса машины-хоста.

Сетевой мост (Bridged) – VM создает мост между своим сетевым интерфейсом и интерфейсом хост-машины. Таким образом VM попадает в один broadcast-домен с интерфейсом хоста и может получить независимый от хост-машины адрес. К примеру, для того чтобы зайти на VM с хостовой машины я использовал именно этот тип (бинд на Ethernet интерфейс), а не проброс порта т.к. он самый простой – VM получило независимый от хост-машины адрес, а я далее, для удобства, прописал его в static-dhcp. У виртуалки при режиме Bridge свой MAC-адрес на порту. По сути режим представляет из себя Secondary адрес на сетевой карте хост-машины для виртуалки.

        В Bridged схемы возможна проблема со связностью (судя по всему broadcast/multicast) между двумя VM, использующими bridged схему на одной хостовой машине. Решается использованием внутренней сети между VM (Internal Network, vmnet).

DGS-3620-28SC:admin#show fdb po 24
1    default   00-0F-FE-F1-D3-61 24    Dynamic Forward - 192.168.1.2     
1    default  08-00-27-31-A9-E7 24    Dynamic Forward - 192.168.1.100
Total Entries: 2

Виртуальный адаптер хоста (Host Only) – p2p связь между хост-машиной и гостевой, по сути это отдельная сетка между хостом и guest. Настроить интерфейс можно статикой (см. настройки в “Виртуальные сети хоста” или по DHCP.

Внутренняя сеть (Internal Network) – связь между хост-машиной и другими гостевыми.

 

Direct Path IO, SR-IOV (SR IOV)
  • DirectPath I/O менее гибкая технология – выделяется полностью сетевая карта, а не виртуальная сетевая карта (Virtual Function) как в случае с SR-IOV (которых может быть несколько).
SR-IOV offers performance benefits and tradeoffs similar to those of DirectPath I/O.

With DirectPath I/O you can map only one physical function to one virtual machine. SR-IOV lets you share a single physical device, allowing multiple virtual machines to connect directly to the physical function.

SR-IOV allow for a single physical device to be shared amongst multiple guests.

In the Number of virtual functions text box, type the number of virtual functions that you want to configure for the adapter.

A value of 0 means SR-IOV is not enabled for that physical function.

82599EB 10-Gigabit SFI/SFP+ Network Connection
82599EB 10-Gigabit SFI/SFP+ Network Connection
82599 Ethernet Controller Virtual Function
82599 Ethernet Controller Virtual Function

 

    • Обе технологии требуют при использовании (пробросе NIC) полный доступ к ОП для VM – т.е. не получится выделить 8GB на платформе с 8GB RAM, как если бы эти технологии не использовались.
    • Intel VT-d (или AMD-Vi для процессоров AMD) необходимо включать в BIOS для работы SR-IOV
    • При работе с SR-IOV можно столкнуться с проблемой работы сети VM связанной с включенным anti-spoofing, в таком случае может помочь отключение этой функции для NIC на уровне гипервизора
RAM
Reserve all memory
The VM will not power on until its memory reservation equals its memory size.

spoof checking
ESXI spoof checking
Так
esxcli intnet sriovnic vf set -n vmnic2 -v 0 -t true -s false
esxcli network sriovnic vf list -n vmnic2
Или
esxcli system module parameters set -m nmlx5_core -p "trust_state=1 max_vfs=5"
у адаптеров mellanox за доверенный режим отвечает параметр trust_state 
судя по документации есть два основных варианта настройки:
1. trust_state=1 - включает доверенный режим
2. trust_state=2 - включает доверенный режим с поддержкой DSCP (используется для QoS)

Linux spoof checking
To enable MAC anti-spoofing, run:
ip link set ens785f1 vf 0 spoofchk on
To disable MAC anti-spoofing, run:
ip link set ens785f1 vf 0 spoofchk off
  • Peripheral Component Interconnect (PCI) passthrough gives VNFs direct access to physical PCI devices that seem and behave as if they were physically connected to the VNF. PCI passthrough can be used to map a single pNIC to a single VNF, making the VNF appear to be directly connected to the pNIC.Using PCI passthrough provides performance advantages, such as:
      • One-to-One Mapping
      • Bypassed Hypervisor
      • Direct Access to I/O Resources
      • Increased I/O Throughput
      • Reduced CPU Utilization
      • Reduced System Latency
  • SR-IOV is a PCI passthrough feature that enables multiple VNFs to share the same pNIC. SR-IOV emulates multiple Peripheral Component Interconnect Express (PCIe) devices, such as pNICs, on a single PCIe device. The emulated PCIe device is referred to as Virtual Function (VF), and the physical PCIe device is referred to as Physical Function (PF). Physical Functions have full PCIe features. Virtual Functions have simple PCIe functions that process I/O only. Using PCI passthrough technology, the VNFs have direct access to the VFs.
  • CheckPoint proof: The virtual switch path, processed by the VSX kernel, doesn’t provide the same performance as the physical switch path.
    Feature Physical Interface Virtual Switch (wrp)
    SecureXL Fast Path :white_heavy_check_mark: Fully supported :cross_mark: Not applied
    Multi-Queue :white_heavy_check_mark: Supported :cross_mark: Not applicable
    CoreXL Scaling :white_heavy_check_mark: Multi-core :warning: Limited
    Throughput :white_heavy_check_mark: High :warning: Limited
  • Обе технологии (DirectPath I/O и SR-IOV)
    • увеличивают производительность за счет исключения из схемы обработки vSwitch.
    • имеют ограничения – использование vMotion, snapshots
Some virtual machine operations are unavailable when PCI/PCIe passthrough devices are present.
You cannot suspend, migrate with vMotion, or take or restore snapshots of such virtual machines. 

Like DirectPath I/O, SR-IOV is not compatible with certain core virtualization features, such as vMotion.

Разное

  • Для использования общей папки расшаренной с основной системы для гостевой в гостевой нужно обратится к общей папке. В Windows (можно просто зайти в раздел Сеть в “Мой компьютер”) и Linux используются разные команды для монтировки общей сетевой папки:
net use x: \\vboxsvr\1 - windows
mount -t vboxsf 1 mount_point - UNIX
  • VM машина Virtual Box с одного компа переносится легко на другой. Просто копируешь всю папку с VM, включая файл .vbox с параметрами машины и .vdi с образом и файлами машины. Далее заходишь в VirtualBox на новом ПК, выбираешь Машина -> Добавить и указываешь .vbox файл.
  • Между разными гипервизорами VM можно переносить используя расширение OVA/OVF
OVF (Open Virtualization Format) — открытый стандарт для хранения и распространения виртуальных машин. Стандарт описывает открытый, переносимый, расширяемый формат для распространения образов виртуальных машин. Стандарт OVF не привязан к какой-либо реализации гипервизора или аппаратной архитектуре.

Пакет OVF состоит из нескольких файлов, расположенных, как правило, в одном каталоге. Пакет всегда содержит ровно один файл описания с расширением .ovf. Это XML-файл, описывающий упакованную виртуальную машину и содержащий метаданные пакета, такие, как название, аппаратные требования, ссылки на другие файлы в пакете и описания. Кроме файла описания, пакет OVF обычно содержит один или несколько образов диска и может включать файлы сертификатов и другие файлы.

Весь каталог может быть распространен в виде пакета Open Virtual Appliance (OVA), который представляет собой файл архива TAR с внутренним каталогом OVF.

Поддерживается в:

VirtualBox от Oracle;
VMware ESX, VMware Workstation от VMWare.
  • VirtualBox по умолчанию выделяет одно ядро на виртуалку. Можно изменить (отключаешь виртуалку, перетягиваешь “ползунок”, включаешь).
  • Resize (увеличение/уменьшение) размера виртуального диска vdi в VirtualBox на Windows раньше возможен был только через консоль, теперь легко делается через GUI (менеджер -> инструменты) просто перетягиванием бегунка для нужного vdi. Если при попытке resize выдает VBOX_E_FILE_ERROR (0x80BB0004) – проверить что места достаточно, перезагрузить ПК.
  • Если выдает VERR_VD_IMAGE_READ_ONLY – сначала перезагрузить ПК, попробовать запустить VB от имени администратора, потом проверить отсутствие галки “только чтение” и только потом переустанавливать/шаманить с правами.

 

 

XCP-NG

  • Популярен
  • Основан на XEN
  • `Имеет коммерческую поддержку
  • Поддерживает в том числе “сетевые” (network function) VM – pfsense например

 

 

VMWARE
  • VMware – де-факто стандарт по виртуализации. У меня еще в 2015 была виртуалка, которая крутилась на корпоративном гипервизоре VMware vSphere в Билайне. Юзал так же VMware Workstation для работы с GNS3. В vSphere можно поднимать IOS-XE (Cisco Nexus 1000V).
    У VMware в разы лучше эмуляция. То, что не идет на виртуалке VirtualBox - пойдет 100% на VMware.
  • (python, vmware) Методы взаимодействия с VMware используя python через API: Pyvmomi (official, supported now), pysphere (not official, deprecated from 2013). Сравнение явно в пользу pyvmomi.
  • I Copied It / I Moved It. При переносе файлов одной VM между datastore разных ESXi правильнее выбрать “I Moved It“.
The virtual machine might have been moved or copied. In order to configure certain management and networking features ,VMware ESX needs to know if this virtual machine was moved or copied. If you don't know, answer "I copied it"

- I Moved It — ESXi сохраняет исходные UUID виртуальной машины (bios.uuid) и MAC-адреса её vNIC'ов. Сеть, vMotion, привязки по MAC в DHCP-резервациях, лицензии ПО, привязанного к UUID, — всё продолжает работать как раньше.
- I Copied It — ESXi генерирует новые UUID и MAC-адреса. Это нужно именно при копировании, чтобы два клона одной ВМ не конфликтовали в сети (одинаковые MAC приводили бы к коллизиям, ARP-путанице и странным сетевым проблемам).

Если случайно ответили «I Copied It» — не страшно: у ВМ просто сменятся MAC-адреса (статические настройки IP на интерфейсах придётся поправить) и UUID. При желании их можно вернуть вручную в настройках ВМ или через vim-cmd/PowerCLI, задав прежние значения.

(SSH, AAA, VMWARE)

Ошибки, которые лечатся указанием алгоритма обмена ключей/типа шифрования/MAC (могут быть на старом софте Cisco, VMware). Причем обычно добавление только одного недостаточно т.к. весь стек deprecated.

# EXAMPLE 1
$ ssh 192.168.1.254
Unable to negotiate with 192.168.1.254 port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
$ ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 192.168.1.254
Unable to negotiate with 192.168.1.254 port 22: no matching cipher found. Their offer: aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
# RESULT 1
$ ssh -c aes256-cbc -oKexAlgorithms=+diffie-hellman-group1-sha1 192.168.1.254


# EXAMPLE 2
no matching key exchange method found. Their offer: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha
no matching host key type found. Their offer: ssh-rsa
no matching MAC found. Their offer: hmac-sha1,hmac-sha1-96
# RESULT 2
ssh -oKexAlgorithms=+diffie-hellman-group14-sha1 -oHostKeyAlgorithms=+ssh-rsa -oMACs=+hmac-sha1 root@1.1.1.1
Workstation/Fusion

Пример Export’а машины в Workstation Player через командную утилиту OVFTool.

C:\Program Files (x86)\VMware\VMware Player\OVFTool>ovftool "D:\New VMs\Virtual Machines\dev.vmx" "D:\dev.ovf"

Для Workstation при импорте иногда (в случае ошибки на размер файла) требуется отключение проверки на размер vmdk (test-vm.vmx), открываем VMX файл, добавляем строку. Такое было при использовании сетевого диска для сохранения VM. В целом, лучше не использовать просто и вероятнее всего с такими проблемами не столкнешься.

\\network-path\test-vm\test-vm.vmx
diskLib.sparseMaxFileSizeCheck= "FALSE"
Vmware fusion

Аналог бесплатного VMware Workstation для MAC OS. Во многих случаях значительно производительнее VirtualBox т.к. поддерживает nested virtualization (например, нужно для GNS3/EVE-NG).

В Fusion/Workstation встроен impairment функционал для виртуалок.

В случае проблемы Could not open /dev/vmmon: Broken pipe” поможет разрешение на приложения VMware в политиках безопасности.

https://communities.vmware.com/thread/600496
VMWARE vSphere & ESXI

Из опыта с vSphere/ESXI:

  • VMware Compatibility Guide
  • ESXi бесплатной версии достаточен для многих HOME/SOHO задач, какие можно ждать особенности
    • при установке на старое/новое железо может потребоваться изменение установочного образа ESXi путем добавления в него необходимых драйверов, в моем случае это были драйвера Realtek rtl8111e для ESXi 6.7
    • В ESXi 6.7 autostart VM (непостоянно рабочий гипервизор) настраивается с пары кликов (manage -> system -> autostart), в том числе последовательность загрузки VM во время autostart
    • Graceful отключение настраивается в том же разделе что и автостарт – нужно выбрать Shut down action (OS shutdown) вместо Power Off (pulling the off cable). Так же требуется установка VMware Tools (Actions -> Guest OS -> Install VMware Tools). VMware Tools is not installed in this virtual machine. VMware Tools allows detailed guest information to be displayed as well as allowing you to perform operations on the guest OS, e.g. graceful shutdown, reboot, etc. You should install VMware Tools. 
    • исчетение evaluation периода (подробнее ниже)
    • если хочется запретить взаимодействие с внешней сетью интерфейса самого гипервизора (уязвимости/обновления и проч) – обнуляем default route и (дополнительно) настраиваем deny правило на домашнем роутере
    • можно и привязать ядра cpu через affinity к определенным VM и создать эти ядра как ядра на одном сокете (лучше для windows guest – см. ниже)
  • 3 и более vCPU в VM на базе Windows (сталкивался на Windows 7 PRO и ESXi 6.7) могут в системе не включится, если они на гипервизоре созданы как отдельные сокеты (1 сокет = 1 vCPU). При этом если создать такое же количество (напр. 8) используя 2 сокета и 4 ядра на сокет – все будет работать корректно (продублировал в гипервизоры и windows).
  • ESXi можно устанавливать на SSD, даже нужно. Так же на версиях до 7-ой можно было устанавливать даже на USB flash.
I would choose to use the SSD disks, as my experience tells me, that booting ESXi from a USB stick is terribly slow, which you don't want it to be when you are rebooting in the middle of the day during work hours.
US$ 1,164.15
  • ESXi 5.5.0 и 6.7.0 устанавливаются с использованием unetbootin 6.6.1. С Rufus могут быть проблемы из-за файла menu.c
  • ESXi 6.7.0 требует сложный пароль при установке вручную (при авто-развертывании не обязательно)
  • В свежих версиях vSphere по умолчанию есть ограничение на copy-paste из виртуальной машины и в нее – решается тюнингом настроек VM в vSphere и обновлением VMWare Tools в VM.
https://kb.vmware.com/s/article/57122
Name: Value:
isolation.tools.copy.disable FALSE
isolation.tools.paste.disable FALSE
isolation.tools.setGUIOptions.enable TRUE
  • – Отключение HyperThreading
    – Включение Intel® Turbo BoostTechnology 2.0
    – Настройка Scheduling Affinity – используем только ядра одного CPU
    – Настройка SR-IOV для создания 6 Virtual Function сетевых карт в сторону коммутатора HPE5900 JC772A
    The Palo Alto Networks Next Generation Firewall VM-700 was instantiated on the KVM hypervisor directly, using 16 CPU cores and 56 Gigabyte of RAM. Hyperthreading was disabled and Intel® Turbo BoostTechnology 2.0 was enabled in the compute node.The CPU cores from 1 to 16 on Non Uniform MemoryAccess (NUMA) node 0 were pinned for the VM-700.The remaining 6 cores on node 0 and all cores onnode 1 remained idle. Palo Alto Networks achieves itsmaximum scale with 16 dedicated cores. To fullyutilize HPE server configuration with a total of44 cores, multiple VM-700 would need to bedeployed. Since there was no virtualized loadbalancer available distributing the workload, testswere conducted with just one VM-700. Three SR-IOV virtual functions (VF) were created foreach physical port of the HPE 40GbE dual-port NIC;in total, 6 VFs were bound to Palo Alto Networks VM-700 as shown in Figure 3.
    The compute node and the traffic generator were connected through an HPE5900 Series JC772A switch.
  • Пример настроек вкладки Resources vSphere и Options и других для виртуальной машины и гипервизора в целях максимизиации/стабилизации результатов производительности. При этом если на гипервизоре работает всего одна VM, разницы производительности с изоляцией или без может по ряду опций не быть из-за эффективного распределения ресурсов гипервизором/отсутствия шумов.
    • (на хосте) PCI passthrough / SR – IOV
    • (на хосте) Power management policy -> High performance (do not use any power management features), в BIOS так же рекомендуют отключать
    • Options: Latency-Sensitivity Feature -> High, приводит к:
      • Gives Exclusive Access to Physical Resources (CPU, RAM)
      • Bypasses Virtualization Layers
      • Tunes Virtualization Layers
    • CPU (resource allocation): Normal -> High, 0 -> MAX, unlimited (default)
    • Memory (resource allocation):
      • BEST: Reserve all guest memory (All locked)
      • Normal -> High, 0 -> MAX, unlimited (default)
    • Disk (resource allocation): Normal -> High
    • Advanced Memory (NUMA Memory Affinity): Я указывал ту же NUMA ноу что и для Affinity ниже (вторая нода для CPU из affinity). При этом если vCPU и память помещаются в один узел (ВМ ≤ размера NUMA-узла) в целом можно и ничего не настраивать т.к. ESXi сам держит ВМ в одном узле.
    • Advanced CPU (Hyperthreading Core Sharing, Scheduling Affinity):
      • Hyperthreading Core Sharing: Any (Share CPU with HT) -> None/Internal (Not share CPU with HT) – Deprecated опция и может не работать на vSphere старше 5.0, актуальная замещающая опция находится в Options: Latency-Sensitivity Feature
      • Настройка Scheduling Affinity:может значительно влиять на performance устройства – при динамическом распределении средствами ESXi производительность Fortitester была нестабильной с крайними значениями меньше на 10-20% от максимальной производительности. После “жесткого” binding ядер одного из процессоров (в двух-процессорном сервере) к VM производительность стала стабильной и всегда максимальной (для максимума в Line-Rate, возможно нестабильность ушла “за line-rate”). При этом нужно настраивать аккуратно – к примеру включать минимум на одно физическое ядро больше, чем vCPU, причем практически для любого гипервизора, чтобы у служебных потоков гипервизора было физическое ядро, где они могут работать, не отбирая время у vCPU.
- В VMware ESXi— есть системные миры (memory reclamation, I/O, драйверы), которые тоже должны выполняться на тех же логических процессорах. Если affinity = ровно N логических процессоров под N vCPU, гипервизору негде разместить свою работу без вытеснения vCPU — растёт co-scheduling contention и CPU Ready. 
- В KVM/QEMU — есть emulator thread, IO threads (если включены), потоки VNC/SPICE, потоки обработки прерываний. Все они тоже попадают в affinity-маску. Если вы выделили ровно 4 ядра под 4 vCPU, эти служебные потоки будут конкурировать с vCPU за те же ядра. 
pve.proxmox.com +1
- В OpenStack/Nova — при dedicated CPU policy явно рекомендуется выносить emulator threads на отдельное ядро через emulator_thread_policy=isolate, чтобы они не мешали vCPU.
The Scheduling Affinity option gives you detailed control over how virtual machine CPUs are distributed across the host's physical cores. 
The option supports hyperthreading if hyperthreading is enabled. 
ESXi generally manages processor scheduling well, even when hyperthreading is enabled. 
These settings are useful only for fine-tuning critical virtual machines. Using CPU affinity, you can assign a virtual machine to a specific processor.
  • При заливки крупных файлов в ESXi 6.7 через WEB в datastore полезно отключить idle timeout, иначе можно получить фейлы upload из-за idle
settings -> application timeout -> off
  • Устранение дублирования символов в vSphere client (web/app) возможно через файл конфигурации для VM (задержка отклика клавиатуры keyboard.typematicMinDelay = “2000000”).
  • ESXi если в management после установки нет ethernet интерфейсов – возможно ESXI не имеет драйверов на них, может помочь апгрейд (помогало в случае 5.5 -> 6.7).
  • ESXi 5.5 (на базе flash) и 6.7 удобный WEB, vSphere клиент не нужен, да и он deprecated (Legacy C# Client)
  • Nested виртуализация (т. е. в VM гипервизора VMware ESXi запускаем еще один гипервизор типа VMware Workstation) требует включения “Expose hardware assisted virtualization to the guest OS” в гипервизоре, иначе возникает ошибка “This host does not support intel VT-x“

  • В ESXi можно поменять согласование линка на сетевой карте, но между двумя ESXi может не получится поднять 100 full:
      • линк будет падать при статичных настройках 100 full с двух стороны
      • линк не будет падать, но согласование с одной стороны будет 100 half при автосогласовании с одной стороны
        При этом статичная настройка корректно работает с коммутатором (видимо проблема связана с mdi).
  • Установка IOS
    • Получаем откуда то ISO или создаем ISO, например с помощью “ISO Creator” (freeisocreator.com),
    • далее в vSphere Client или WEB выбираем “connect to iso image on local disk”
    • или в ESXi легко пробросить CD/DVD привод – в CD-Rom выбираем файл ISO из datastore
    • Пути к файлам обязательны, иначе будет silent error.

  • Distributed Switch вместо обычного vSwitch может пригодится при организации связи между несколькими eSXI гипервизоров в рамках одного vSphere.
  • Работа с томами VMDK:
    • Используя vmdk + vmx легко развернуть ОС
    • *-flat.vmdk хорошо сжимаются 7zip и другими compression тулами (7zip LZMA2 “скоростной”):
      • 120GB -> 23GB
      • 100GB -> 20GB
    • Расширить том очень легко – добавляешь памяти на диск в ESXi, расширяешь в настройках Windows том. Проблемы могут быть если созданы snapshot – будет ошибка Failed – Invalid operation for device ‘3’. в GUI и ошибка ‘The called function cannot be performed on partial chains. Open the parent virtual disk.’ в VMRC. В таком случае достаточно удалить все snapshot.
    • Сжать том (shrink) можно было только в старых версиях ESXi/vSphere. Лучше это никогда не делать т.к. это опасно. Лучше создать небольшой том и перенести на него данные, далее дропнуть старый.
shrink vmdk
Gary D Williams This person is a Verified Professional
VMWARE EXPERT
Shrinking a VMDK is no longer supported and it never was a good idea. If you can, stand up another, smaller VMDK, move the data to it then delete the oversized one.
  • При импорте ova на ESXi 5.5 через vSphere Client 5.5 можно столкнуться с проблемой того, что vSphere Client 5.5 не поддерживает SHA256 hash в Manifest. Нужно конвертировать, используя ovftool ((или удалять файл с контрольной суммой – еще проще, подробнее ниже)). В теории можно так же WEB c VMware Client Integration Plug-in, но по факту сам плагин у меня не заработал в Chrome и использовал ovftool.
Error: ExtraConfig options exists in source (use --allowExtraConfig option to allow this). Warning: - ExtraConfig option 'MemTrimRate' is not allowed, will skip it.
Fix OVA file importing error on VMware: "The OVF package is invalid and cannot be deployed"
The following manifest file entry (line) is invalid: SHA256(filename-ovf)=sha256-hash-string
C:\Program Files\VMware\VMware OVF Tool> .\ovftool.exe --shaAlgorithm=SHA1 --allowExtraConfig D:\old-sha256.ova D:\new-sha1.ova

Opening OVA source: D:\old-sha256.ova
The manifest validates
Opening OVA target: D:\new-sha1.ova
Writing OVA package: D:\new-sha1.ova
Transfer Completed
Completed successfully
  • При импорте ova на ESXi 5.5 можно столкнуться с ошибкой отсутствия поддержки каких-либо интерфейсов (напр. Serial для Cisco FirePower). Решается простым удалением данного интерфейса (конечно, если по факту он действительно не критично в вашем деплое).
Failed to deploy OVF package: Incompatible device backing specified for device
https://kb.vmware.com/s/article/2128084
<Item>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:ElementName>Serial port 1</rasd:ElementName>
<rasd:InstanceID>18</rasd:InstanceID>
<rasd:ResourceSubType>vmware.serialport.device</rasd:ResourceSubType>
<rasd:ResourceType>21</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="yieldOnPoll" vmw:value="true"/>
</Item>
  • При импорте ova на ESXi 5.5 можно столкнуться с ошибкой отсутствия на текущей системе образа ОС, которая устанавливалась через CD-ROM. “Failed to deploy OVF package: File ds:///vmfs/volumes/36b401f-680d4bc0-1ff7-001517d3bf0c/_deviceImage-0.iso was not found”
    • лучше всего, если есть возможность, удалить из изначальной VM (которую пытаемся импортировать) CD-ROM  и сделать повторный экспорт
    • иначе требуется изменение OVF файла
      For this particular problem, locate the line 'vmware.cdrom.iso' and change this to 'vmware.cdrom.remotepassthrough'.
      https://communities.vmware.com/t5/Open-Virtualization-Format-Tool/Failed-to-deploy/m-p/1785416
  • При импорте ova можно столкнуться с ошибкой отсутствия поддержки нужного количества ядер в виде сокетов (напр. 32 или 64 сокета с одним ядром на каждое), в таком случае требуется поддержка
    • как со стороны гипервизора: virtualhw.version = “8”
    • так и со стороны ОС гостевой системы: Все 32-разрядные версии Windows 7 поддерживают до 32 ядер процессора, а 64‑разрядные версии — до 256 ядер
  • При импорте ova на ESXi 5.5 пришлось изменить ova:
    • Распаковываем ova с помощью 7-zip – извлекаем ovf, vmdk, mf файлы (поэтому best practice при импорте VM – сразу сохранять ее не в OVA, а в виде OVF + VMDK); извлекать нужно т.к. после сохранения измененных параметров ova через 7-zip он перестает распознаваться vSphere 5.5
    • Изменяем в ovf файле vmx-11 (в актуальных может быть уже и vmx-20 :)) на vmx-10
      "The following manifest file entry (line) is invalid: SHA256(filename-ovf)=sha256-hash-string"
      
      "Unsupported hardware family vmx-11"
    • Так же может потребоваться изменение типа VM на поддерживаемый при этом нужно учитывать, что даже если ID присутствует в базе/поддерживается нужно указывать и ID и корректный ему тип, иначе будет ошибка про некорректный ID.
   <OperatingSystemSection ovf:id="115" ovf:version="12" vmw:osType="otherLinux64Guest">
    • Удаляем файл *.mf с контрольными суммами, иначе
      • придется пересчитывать из sha256 в sha1 (напр. с помощью ovftool, описал выше)
      • придется пересчитывать после изменения vmx
  • (disk/dd, VMware) Подготовить ОС к созданию образа (OVA) – делаем тип диска Thin, а свободное пространство зануляем через dd
    dd if=/dev/zero of=/zero.fill bs=1M; sudo rm -f /zero.fill
  • Для экспорта VM в случае глюков gui интерфейсов (сталкивался на WEB 6.7)/необходимости автоматизации можно скачать vmdk прямо с datastore или использовать CLI OVFTool и Export-VApp.
OVFTool - Example of how to use OVFTool can be found here: https://www.michellelaverick.com/2018/04/using-ovftool/

Export-VApp - vSphere PowerCLI Cmdlets Reference https://www.vmware.com/support/developer/PowerCLI/PowerCLI51/html/Export-VApp.html
  • Установка ОС через образа ISO в виде виртуального CD на VM
    • connect to iso on local disk может быть серым из-за того, что VM отключена или это глюк клиента vSphere (помогает перезагрузка клиента)
    • после того, как заработало, попадаем в BIOS отправив ctrl+alt+del через консоль и нажав F2, выставляем загрузку с CD
  • Разворачивание VM с использованием vmdk + vmx – загружаем в datastore оба файла, ПКМ по VMX -> Register VM. Если VMX файла нет или в таком режиме разворачивается с ошибками и не хотим мучаться с конвертерами (vmkfstools)  – можно примонтировать диск при создании VM.
    https://serverfault.com/questions/579866/deploying-vm-from-vmdk-vmx-file
  • PCI passthrough
    • На моей практике PCI-E PassThroughput против vswitch (ESXI) или тем бодее virtio (KVM) увеличивает производительность в разы (vswitch) и десятки раз (virtio). Пример реальных дропов на vswitch при нагрузке (увеличение очереди и другие шаманства не помогли от них избавиться) – см. ниже в управлении через CLI.
    • ESXi может не прокидывать passthrough из-за некорректных настроек в BIOS в контексте виртуализации. Самое простое для начала – сбрасываем в default.
Task Update Passthru Config
Key haTask-ha-host-vim.host.PciPassthruSystem.updatePassthruConfig-882758993
Description Update PCI passthrough device configuration
State Failed - An error occurred during host configuration.
  •   Виртуализированные сетевые карты E1000 vs VMXNET3
    • VMXNET3 однозначно более производительные ((ниже таблица от Gemini ИИ)) и использовать их нужно всегда когда они доступны
Use E1000 only if the virtual machine does not support VMXNET3 drivers or when VMware tools cannot be installed.
Performance Comparison: VMXNET3 vs. E1000

Feature [1, 2, 3, 4, 5, 6, 7, 8, 9] VMXNET3 (Paravirtualized) E1000 (Emulated)
Max Throughput 10Gbps (up to 100Gbps in high-speed infra) Typically ~1 Gbps (up to ~2.5G under load)
CPU Usage Very Low (Optimized) High (due to emulation)
Latency Low High
Driver Required VMware Tools Native/Built-in
Usage Scenario All production VMs Legacy OS/No VM Tools
Features TSO, RSS, Multi-queue Basic Gigabit NIC
    • VMXNET3 могут отсутсвовать в настройке если выбрана некорректная ОС в типе ОС в VMWare (к примеру Other Linux (64-bit) -> Linux, Debian GNU/Linux 6 (64-bit))
The configured guest OS (Other Linux (64-bit)) for this virtual machine does not match the guest that is currently running (Other 4.x or later Linux (64-bit)). You should specify the correct guest OS to allow for guest-specific optimizations.
  • VM может не запускаться из-за кривых настроек (куча разных причин). Например:
    • Нужно memory reservations поправить в соответствии с размером памяти.
Failed - Invalid memory setting: memory reservation (sched.mem.min) should be equal to memsize(5192).
    • кривых настроек дисков – может помочь смена scsi на IDE
Failed - Unsupported or invalid disk type 2 for 'scsi0:0'. Ensure that the disk has been imported.

I solved the issue by changing the Virtual Device Node from SCSI controller 0 to IDE controller 0 at the hard disk settings of the virtual machine.
  • CTRL+ALT снять захват из Console (если забыть можно долго мучатся)
  • В vSphere очень просто сделать snapshot (backup) текущей системы, главное чтобы были права
  • Если install vmware tools не активно (серое) – отключаем CD/flopy
    Had the same issue. Like the answer posted before, I had to shutdown the machine and change both the floppy drive and cd drives to "Auto detect" and then power on the machine.
  • в vSphere можно посмотреть загрузку CPU/memory/сети за день/неделю/месяц/год/кастом
• количество пакетов среднее макс
• оперативная память среднее макс
• жесткий диск
• CPU среднее макс
• сеть среднее макс
  • периодически в vSphere появляются сообщения о миграции виртуальной машины (VM migration) из-за изменения потребления ресурсов (DRS – Distributed Resource Scheduler):
    13.12.2015 12:23:21 <Server_name> info Alarm 'Virtual machine total disk latency' changed from Gray to Green
    13.12.2015 12:23:21 <Server_name> info Alarm Alarm 'Virtual machine memory usage' changed from Gray to Green
    13.12.2015 12:23:21 <Server_name> info Alarm Alarm 'Virtual machine CPU usage' changed from Gray to Green
    13.12.2015 12:22:28 <Server_name> info Resource allocation changed Migrate virtual machine
  • “Unsuccessful EFI network VMware doesn’t boot Windows 10 Installer.” – выбираем вместо UEFI загрузку BIOS (VM options -> boot options).
Управление ESXi через CLI по SSH

Версия ESXi

~ # vmware -vl
VMware ESXi 5.5.0 build-3248547
VMware ESXi 5.5.0 Update 3

Изменение hostname ESXi

esxcli system hostname set –host=hostname
esxcli system hostname set –fqdn=fqdn
Список VM с именами VM и их ID.
> esxcli vm process list
Win10-experiments
World ID: 2099339
Process ID: 0
VMX Cartel ID: 2099337
UUID: 56 4d 1d ee 48 c7 9b 63-73 bd 9f e9 b2 29 dd 90
Display Name: Win10-experiments
Config File: /vmfs/volumes/643b0919-87228d82-6cb3-3085a9a10821/Win10-experiments/Win10-experiments.vmx
Список VM с номерами VM, используемыми носителями и VMX файлами.
> vim-cmd vmsvc/getallvms
Vmid Name File Guest OS Version Annotation
1 old-Win10-backups [Barracuda-150GB] Win10/Win10.vmx windows9_64Guest vmx-14
2 Win10-experiments [SSH-OCZ-Vertex3-100GB] Win10-experiments/Win10-experiments.vmx windows9_64Guest vmx-14
3 Win10-backups [WD-1.8TB] Win10/Win10.vmx windows9_64Guest vmx-14
Отключение процессов VM по World ID VM. Якобы “помогает от зависших и не отвечающих в vSphere Client ВМ”, но мне не помогло – задача автостарта не сбрасывалась 🙂 ((root cause – умерший SSD; для отмены задачи помогла только разрегистрация VM, но зависания в других задачах из-за root cause сохранились))
> esxcli vm process kill --type=[soft,hard,force] --world-id=WorldID 
> esxcli vm process kill --type=hard --world-id=2099529
Аналогия – отключение задач VM. По номеру VM получаем ее задачи, по названию задачи убиваем. У меня так же не сработало ((root cause – умерший SSD; для отмены задачи помогла только разрегистрация VM, но зависания в других задачах из-за root cause сохранились)).
> vim-cmd vmsvc/get.tasklist 3
(ManagedObjectReference) [
'vim.Task:haTask-3-vim.VirtualMachine.powerOn-47'
]
> vim-cmd vimsvc/task_cancel 'haTask-3-vim.VirtualMachine.powerOn-47'

Продление evaluation по ssh. После 60 дней отключаются advanced фичи и нужно запросить бесплатную лицензию (иначе отключенные vm не включить), но evaluation период при необходимости легко продливается даже после истечения, без каких-либо “кряков” ((но и такого полно – https://gist.github.com/arashkaffamanesh/43f9f18c9ef80f5f65a2d9c14446f707). Продление делается по SSH (включаем по консоли на hypervisor) через подмену старого файла шаблоном. Работает как на ESXi 5.5, так и на ESXi 6.7.

If 60 days have passed and no license was applied, then all advanced features are locked, running VMs continue to run but you cannot start powered off VMs. ESXi hosts connected to vCenter Server are disconnected in this case. You'll need to apply a license (free or paid) to make your ESXi server work again.

rm -r /etc/vmware/license.cfg cp /etc/vmware/.#license.cfg /etc/vmware/license.cfg /etc/init.d/vpxa restart
Пример реальных дропов на vswitch при нагрузке (увеличение очереди и другие шаманства не помогли от них избавиться).
~ # esxcli network vm list
World ID Name Num Ports Networks
-------- ---------------------- --------- ------------------------------------------
40713 Test-VA 4 VM Network, VM Network, VM Network, attack

~ # esxcli network vm port list -w 40713
Port ID: 33554440
vSwitch: vSwitch0
Portgroup: VM Network
DVPort ID:
MAC Address: 00:00:00:00:00:00
IP Address: 0.0.0.0
Team Uplink: vmnic1
Uplink Port ID: 33554434
Active Filters:

Port ID: 33554441
vSwitch: vSwitch0
Portgroup: VM Network
DVPort ID:
MAC Address: 00:00:00:00:00:00
IP Address: 0.0.0.0
Team Uplink: vmnic1
Uplink Port ID: 33554434
Active Filters:

Port ID: 33554442
vSwitch: vSwitch0
Portgroup: VM Network
DVPort ID:
MAC Address: 00:0c:29:26:7c:1a
IP Address: 0.0.0.0
Team Uplink: vmnic1
Uplink Port ID: 33554434
Active Filters:

Port ID: 50331653
vSwitch: vSwitch1
Portgroup: UPLINK
DVPort ID:
MAC Address: 00:0c:29:26:7c:24
IP Address: 0.0.0.0
Team Uplink: vmnic3
Uplink Port ID: 50331650
Active Filters:

~ # esxcli network port stats get -p 50331653
Packet statistics for port 50331653
Packets received: 1846312006
Packets sent: 210
Bytes received: 2795316313108
Bytes sent: 12600
Broadcast packets received: 0
Broadcast packets sent: 210
Multicast packets received: 0
Multicast packets sent: 0
Unicast packets received: 1846312006
Unicast packets sent: 0
Receive packets dropped: 261199086
Transmit packets dropped: 0

Увеличение размера RX-очереди и другие шаманства не помогают существенно:
~ # esxcfg-nics -s 10000 -d full vmnic3
~ # ethtool -A vmnic3 autoneg off rx off tx off
~ # ethtool -s vmnic3 autoneg off speed 10000 duplex full
~ # ethtool -G vmnic3 rx 4096 tx 4096

Изменение управляющего (management) IP возможно через SSH, помимо Console

https://kb.vmware.com/s/article/2084629
esxcli network ip interface ipv4 get # смотрим название интерфейса
esxcli network ip interface ipv4 set -i vmk0 -I 172.16.1.101 -N 255.255.255.0 -t static # изменяем IP

Просмотр всех носителей ssd/hdd/cd.

[root@192:~] esxcli storage core device list
t10.ATA_____OCZ2DVERTEX3_MI__________________________OCZ2DN900H83UOGFTNL8U
   Display Name: Local ATA Disk (t10.ATA_____OCZ2DVERTEX3_MI__________________________OCZ2DN900H83UOGFTNL8U)
   Has Settable Display Name: true
   Size: 114473
   Device Type: Direct-Access
   Multipath Plugin: NMP
   Devfs Path: /vmfs/devices/disks/t10.ATA_____OCZ2DVERTEX3_MI__________________________OCZ2DN900H83UOGFTNL8U
   Vendor: ATA
   Model: OCZ-VERTEX3 MI
   Revision: 2.25
   SCSI Level: 5
   Is Pseudo: false
   Status: on
   Is RDM Capable: false
   Is Local: true
   Is Removable: false
   Is SSD: true
   Is VVOL PE: false
   Is Offline: false
   Is Perennially Reserved: false
   Queue Full Sample Size: 0
   Queue Full Threshold: 0
   Thin Provisioning Status: yes
   Attached Filters:
   VAAI Status: unknown
   Other UIDs: vml.01000000004f435a2d4e393030483833554f4746544e4c38554f435a2d5645
   Is Shared Clusterwide: false
   Is SAS: false
   Is USB: false
   Is Boot Device: true
   Device Max Queue Depth: 31
   No of outstanding IOs with competing worlds: 31
   Drive Type: unknown
   RAID Level: unknown
   Number of Physical Drives: unknown
   Protection Enabled: false
   PI Activated: false
   PI Type: 0
   PI Protection Mask: NO PROTECTION
   Supported Guard Types: NO GUARD SUPPORT
   DIX Enabled: false
   DIX Guard Type: NO GUARD SUPPORT
   Emulated DIX/DIF Enabled: false

t10.ATA_____WDC_WD20EZBX2D00AYRA0_________________________WD2DWXK2AA2PX4PP
   Display Name: Local ATA Disk (t10.ATA_____WDC_WD20EZBX2D00AYRA0_________________________WD2DWXK2AA2PX4PP)
   Has Settable Display Name: true
   Size: 1907729
   Device Type: Direct-Access
   Multipath Plugin: NMP
   Devfs Path: /vmfs/devices/disks/t10.ATA_____WDC_WD20EZBX2D00AYRA0_________________________WD2DWXK2AA2PX4PP
   Vendor: ATA
   Model: WDC WD20EZBX-00A
   Revision: 1A01
   SCSI Level: 5
   Is Pseudo: false
   Status: on
   Is RDM Capable: false
   Is Local: true
   Is Removable: false
   Is SSD: false
   Is VVOL PE: false
   Is Offline: false
   Is Perennially Reserved: false
   Queue Full Sample Size: 0
   Queue Full Threshold: 0
   Thin Provisioning Status: yes
   Attached Filters:
   VAAI Status: unsupported
   Other UIDs: vml.0100000000202020202057442d57584b324141325058345050574443205744
   Is Shared Clusterwide: false
   Is SAS: false
   Is USB: false
   Is Boot Device: false
   Device Max Queue Depth: 31
   No of outstanding IOs with competing worlds: 31
   Drive Type: unknown
   RAID Level: unknown
   Number of Physical Drives: unknown
   Protection Enabled: false
   PI Activated: false
   PI Type: 0
   PI Protection Mask: NO PROTECTION
   Supported Guard Types: NO GUARD SUPPORT
   DIX Enabled: false
   DIX Guard Type: NO GUARD SUPPORT
   Emulated DIX/DIF Enabled: false

Просмотр smart/health информации по носителям ssd/hdd. В данном случае SSD оказался проблемным – через минут 5 после включения сервера переставал работать и в том числе выдавать smart информацию. Обращает на себя внимание процент износа диска (Media Wearout Indicator) – 95 при пороге 10!!!

[root@192:~] esxcli storage core device smart get -d=t10.ATA_____OCZ2DVERTEX3_MI__________________________OCZ2DN900H83UOGFTNL8U
Error getting Smart Parameters: Cannot open device

[root@192:~] esxcli storage core device smart get -d=t10.ATA_____OCZ2DVERTEX3_MI__________________________OCZ2DN900H83UOGFTNL8U
Parameter                     Value  Threshold  Worst
----------------------------  -----  ---------  -----
Health Status                 OK     N/A        N/A
Media Wearout Indicator       95     10         95
Write Error Count             0      0          0
Read Error Count              N/A    N/A        N/A
Power-on Hours                71     0          71
Power Cycle Count             97     0          97
Reallocated Sector Count      100    3          100
Raw Read Error Rate           120    50         120
Drive Temperature             30     0          30
Driver Rated Max Temperature  N/A    N/A        N/A
Write Sectors TOT Count       0      0          0
Read Sectors TOT Count        0      0          0
Initial Bad Block Count       N/A    N/A        N/A

Пример вывода по относительно новому HDD.

[root@192:~] esxcli storage core device smart get -d=t10.ATA_____WDC_WD20EZBX2D00AYRA0_________________________WD2DWXK2AA2PX4PP
Parameter                     Value  Threshold  Worst
----------------------------  -----  ---------  -----
Health Status                 OK     N/A        N/A
Media Wearout Indicator       N/A    N/A        N/A
Write Error Count             0      0          N/A
Read Error Count              0      51         N/A
Power-on Hours                125    0          N/A
Power Cycle Count             46     0          N/A
Reallocated Sector Count      0      140        N/A
Raw Read Error Rate           0      51         N/A
Drive Temperature             34     0          N/A
Driver Rated Max Temperature  N/A    N/A        N/A
Write Sectors TOT Count       N/A    N/A        N/A
Read Sectors TOT Count        N/A    N/A        N/A
Initial Bad Block Count       N/A    N/A        N/A

 

vSwitch
  • Пример настроек vswitch для работы virtual MAC NGFW , в целом могут быть разные проблемы от настроек vswitch при виртуальном кластере, с чем сталкивался и Ideco

Стоит отметить, что для корректной работы VMAC в некоторых средах виртуализации требуется соответствующая настройка гипервизора.
Рассмотрим ключевые шаги настройки Port Groups в VMware:

- Включить Promiscuous Mode. В этом режиме сетевой интерфейс принимает все пакеты, проходящие через сеть, независимо от их адресата. Обычно сетевой адаптер фильтрует трафик, пропуская только пакеты, адресованные собственному MAC-адресу, широковещательные или многоадресные пакеты. В режиме Promiscuous Mode устройство получает полный сетевой трафик, что необходимо для корректной работы VMAC, обеспечивая обработку пакетов, адресованных виртуальному MAC-адресу, используемому в кластере.

- Выключить «MAC Address Changes». Выключение этой опции предотвращает динамическое изменение MAC-адреса сетевого интерфейса. Это важно для стабильности сетевого взаимодействия, так как VMAC должен оставаться неизменным для корректного распознавания и маршрутизации трафика в кластере.

- Включить «Forget Transmits». Данная функция управляет кешем MAC-адресов, обеспечивая очистку информации о недавно переданных пакетах. Это помогает избежать повторной передачи или неправильной маршрутизации пакетов при переключениях или изменениях в сетевой топологии.
Подробнее: https://www.securitylab.ru/analytics/561426.php
  • Standard vSwitch и VLAN (VID)

    • Если на свиче указать TAG 4095 – в ESXi для standard vSwitch это рассматривается как special case фича Virtual Guest Tagging (VGT), она позволяет пробрасывать любые (напр. 754, 755, 854, 855, 1033, 4000) тегированные фреймы в VM не снимая VID метку при отдаче на VM (по сути trunk port с vSwitch в сторону VM).

    • Есть на свиче настроить конкретный TAG (от 1 до 4094) – он будет обрабатывать фреймы, полученные с этим фреймом с vSwitch uplink и отдавать нетегированными в VM (гостевые машины) и наоборот, получив от VM кадр будет отдавать его тегированным на uplink (по сути access port с vSwitch в сторону VM).

Virtual Guest Tagging (VGT) – With VGT, all VLAN tagging is done by the virtual machine. VLAN tags are preserved between the virtual machine networking stack and external switch when frames pass to and from virtual switches.
Host network adapters must be connected to trunk ports on the physical switch. For a standard switch, the VLAN ID of port groups with VGT must be set to 4095.
  • В vSwitch даже для организации базовой связности может пригодиться отключение Security параметров – Promiscuous, MAC address changes, Forged transmits.
ARP ответы от VM в nested VM (VMware ESXi -> VM Windows -> VMware Workstation -> Linux) по какой-то причине не фиксировались на проблемной VM, при том, что хост машина (VM Windows) была доступна с проблемной VM. Решилось модификацией security политик для трафика на vSwitch.
            Security
               Promiscuous mode Accept
               MAC address changes Accept
               Forged transmits Accept
  • CDP: На vswitch esxi можно настроить как прием, так и анонс CDP. Кроме того очень полезно, что в ESXi можно посмотреть какие MAC адреса VM выучил vSwitch (чтобы сопоставить например VM и VLAN TAG проброшенный TRUNK/VGT).
   csco#show cdp neighbors
   Capability Codes: R - Router, T - Trans Bridge, B - Source Route Bridge
                     S - Switch, H - Host, I - IGMP, r - Repeater, P - Phone,
                     D - Remote, C - CVTA, M - Two-port Mac Relay
   Device ID        Local Intrfce     Holdtme    Capability  Platform  Port ID
   localhost        Gig 1/0/30        178               S    VMware ES vmnic2
   localhost        Gig 1/0/29        178               S    VMware ES vmnic1
Разбор Deploying Extremely Latency-Sensitive Applications in VMware vSphere 5.5 Performance Study

(весь разбор в Vmware, NIC, latency; одно упоминание в Статистике)

Описание обхода проблем с задержками (и частично производительностью) в виртуализации и их решения на основе разбора White Paper «Deploying Extremely Latency-Sensitive Applications in VMware vSphere 5.5 Performance Study» https://communities.vmware.com/docs/DOC-30382 (https://disk.yandex.ru/i/Rnb12ReVjj1wrg). Виртуализация и производительность (скорость ответа в статье), включая проблемы latency (как величина среднего latency, так и его вариативность/jitter) – это по сути чистой виды “перетягивание каната”: чем больше виртуализации, тем больше проблем с производительностью и latency. 

  • В среднем того, как работает гипервизор vmware и его настроек по умолчанию vm для работы виртуализации обычно достаточно для качественной работы условно среднего приложения (web, bd и даже voice с ~миллисекундными требованиями к задержке) – это обеспечивается во многом за счет функционала гипервизора, который выделяет больше тех или иных ресурсов (cpu, memory, network) той vm, которая больше всего в них нуждается в конкретный момент времени. 
  • Однако, гипервизор «не всесилен» и имеет архитектурные ограничения:
      • Гипервизор реализует уровни разделяемых абстракций, через которые vm получает ресурсы, эти уровни накладывают издержки сами по себе, не говоря про разделяемость общего ресурса между разными vm и конкуренцию за него – к примеру виртуальные сетевые карты и виртуальные коммутаторы добавляют задержки, но без них взаимодействие между VM тяжелее организовать,
      • Гипервизор имеет scheduler, который определяет кому больше всего требуется разделяемый ресурс прямо сейчас и его перераспределяет 
        • особенно плохо он работает когда pcpu (physical CPU) ресурс то нужен, то не нужен – по сути постоянная задержка из-за переключения (pinning vcpu к pcpu) , а этот паттерн (ресурс то нужен, то не нужен) часто свойственен требовательным к сетевым задержкам приложениям; 
        • плюс ресурс может быть одновременно нужен нескольким VM,
        • scheduler гипервизора имеет скорость реакции в миллисекунды (написали как пример),
      • Гипервизор по умолчанию увеличивает задержки за счет объединения каких то операций (к примеру взаимодействие между vmm и vmkernel задействует VNIC coalescing и использование  Large Receive Offload (LRO) на vnic), что приводит к росту задержки
  • Поэтому в гипервизорах есть функционал по сути «обхода виртуализации» (частичного или полного): он появился из-за высокой потребности снижения задержек в продуктивных сценариях с очень высокими требованиями по задержке (до десятков микросекунд) таких как: distributed in-memory data management, stock trading, high-performance computing (HPC). Для поддержки таких продуктивных сценариев vmware рекомендует включать «обход виртуализации» для конкретных элементов (виртуальных машин, сетевых карт, cpu, памяти дисков), давая возможность vm использовать ресурсы напрямую минуя по сути гипервизор (лучше) или с высоким приоритетом (хуже, но тоже сценарий), тем самым по сути исключая проблемы виртуализации (конкуренция за ресурсы и уровни абстракции) и во многом саму виртуализацию. Примером такого функционала являются: 
    • pci passthrough (direct path i/o)/ sr-iov –  bypasses the network virtualization layer
    • latency sensitivity – The Latency-Sensitivity feature aims at eliminating the major sources of extra latency imposed by virtualization to achieve low response time and jitter. Briefly, this per-VM feature achieves the goal by 1) giving exclusive access to physical resources to avoid resource contention due to sharing, 2) bypassing virtualization layers to eliminate the overhead of extra processing, and 3) tuning virtualization layers to reduce the overhead.
      • virtual machines exclusively own physical cores, thus avoiding overhead related to CPU scheduling and contention ((and bypassing virtualization layers)), enabling the latency-sensitivity 
      • also requires memory ((RAM)) reservation. When the VMXNET3 paravirtualized device is used for VNICs in the VM, VNIC interrupt coalescing and LRO support for the VNICs are automatically disabled to reduce response time and its jitter. ((Рекомендуют если невозможно использовать passthrough/sr-iov))
      • Also, we recommend over-provisioning CPU to reduce contention; the number of VCPUs in the host should be less than the number of PCPUs to leave one or more PCPUs for VMkernel threads for I/O processing and system management. 
Conclusion
vSphere 5.5 provides a new feature called latency-sensitivity to better support extremely-latency sensitive applications. This paper explains the latency-sensitivity feature and evaluates its performance. With this feature enabled, it is demonstrated that both the average and worse case timing behaviors considerably improve, achieving much lower response time and jitter compared to the default configuration. Such a performance improvement is accomplished by removing the major sources of overhead:
1) giving exclusive access to physical resources to avoid resource contention due to sharing, 
2) bypassing virtualization layers to eliminate the overhead of extra processing, and 
3) tuning virtualization layers to reduce the overhead.

Best Practices
Based on the results and discussions so far, we recommend the following best practices for virtualizing extremely latency-sensitive application using the latency-sensitivity feature.
• Set Latency Sensitivity to High. This requires 100% memory reservation.
• Consider reserving 100% of the CPU. This guarantees exclusive PCPU access, which in turn helps to reduce VCPU halt/wake-up cost.
• Consider overprovisioning PCPUs. This reduces the impact of sharing the LLC (last level cache) and also helps to improve the performance of latency-sensitive VMs that use VNICs for network I/O.
• Consider using a pass-through mechanism such as SR-IOV to bypass the network virtualization layer, if the hardware supports one and virtualization features such as vMotion and FaultTolerance are not needed.
• Consider using a separate PNIC for latency sensitive VMs to avoid network contention.
• Consider using NetIOC, if a pass-through mechanism is not used and there is contention for network bandwidth. ((SHAPER/POLICER))
• Consider disabling all power management in both the BIOS and vSphere.
  • Упоминают проблемы с latency из-за power management функционала, рекомендуют его отключать в bios и настройках vsphere при требованиях к задержкам, в последующем описании так же отключили power management и в ОС (получается в трех местах)
Power management in both the BIOS and vSphere can negatively affect latency. It is therefore recommended to turn off all power management schemes to achieve the lowest latency.
All power management features are disabled in the BIOS and Red Hat Linux (by using the kernel boot option of intel_idle.max_cstate=0). 
  • Так же упоминают про память hdd/ssd (помимо RAM, который резервируется при использовании latency sensitivity и cpu cache / llc, который НЕ исключается резервацией cpu, но может влиять на производительность) как возможную причину проблем с latency, но без деталей
Latency can be also impacted by other shared resources such as memory and storage. Since the Latency-Sensitivity feature addresses only CPU and network related issues on the host where the VM is running, we will not discuss latency overhead from other shared resources.
  • Так же интересно: У vmware отдельная команда/группа людей занимаются производительностью, причем как минимум два сотрудника фокусируются именно на сетевой производительности продуктов vmware ((по крайней бере была на момент написания статьи в 2015)).
Jin Heo is a Senior Member of Technical Staff in the Performance Engineering group at VMware. His work focuses on improving network performance of VMware’s virtualization products. He has a PhD in Computer Science from the University of Illinois at Urbana-Champaign.

Lenin Singaravelu is a Staff Engineer in the Performance Engineering group at VMware. His work focuses on improving network performance of VMware’s virtualization products. He has a PhD in Computer Science from Georgia Institute of Technology.
  • Для доказательства влияния описанных опций и улучшения производительности/задержки с ними использовали ping (1000 ping/sec; обрабатываются в ядре) и netperf (request-response, обрабатываются в userspace), фичи и целевые показатели проверяли в разделенных сценариях, в том числе без гипервизора вовсе, но со спорным на мой взгляд setup когда на vm выделяется столько же ресурсов, сколько на хост без гипервизора, хотя и гипотетически часть и фактическая часть нагрузки же может обрабатывать гипервизор ресурсами выше лимита (СПОРНО 1! см. их же рекомендацию по over-provisionning CPU выше, корректнее было бы сравнивать отключив ядра CPU в BIOS/vSphere)
Workloads
Two different request-response type workloads are used to evaluate the latency-sensitivity feature: 1) Ping, 2) Netperf_RR. In this type of workload, the client sends a request to the server, which replies back with a response after processing the request. This kind of workload is very commonly seen: Ping, HTTP, and most RPC workloads all fall into this category. 
The key difference between Ping and Netperf_RR is that ping requests are processed in the kernel, whereas netperf requests are processed in user-space. 
Ping – Default ping parameters are used except that the interval is set to .001 seconds (1000 ping requests are sent out for every second from the client machine) and a 256 byte of message size is used.
Netperf_RR – The Netperf micro benchmark [5] is one of the most popular network performance benchmarks. The TCP_RR type is used to generate a request-response workload in TCP. A 256-byte message size is used.
Configurations
• VM-Default – This is the default configuration without any changes to VMs or the vSphere host except those explained in the “Testbed” subsection above.
• VM-SRIOV – In this configuration, SR-IOV is enabled for the VMs.
• VM-Latency-SRIOV – In this configuration, the latency-sensitivity feature is enabled and SR-IOV is enabled for VMs.
• Native – In this configuration, both the client and server machines run native RHEL6 Linux. 
The evaluation results with the Ping workload are presented first, followed by the results with the Netperf workload. Only one session of the workload is generated per VM (or per machine for the Native configuration).
With the three VM configurations (the VM-Default, VM-SRIOV, VM-Latency-SRIOV), we vary the number of VMs (1 and 4 VMs). VMs are configured with 2 VCPUs and 2GB RAM. The Native configuration is only compared with the 1 VM setup, since there is no straightforward way to match the 4VM setup. The server machine for the Native configuration is configured to have only 2 CPUs online for fair comparison with the 1 VM configurations. In both 1 VM and 4 VM setups, the number of VCPUs is less than that of PCPUs so that the vSphere host is able to give all VMs exclusive access to PCPUs when the latency-sensitivity feature is enabled. The entire guest memory is reserved for the VM-SRIOV and VM-Latency-SRIOV configurations to properly enforce the pass-through mechanism and the latency-sensitivity feature.
  • Недостатки использования latency sensitivity понятны
    • Ресурсы пропадают из шаринга других vm
    • Если продолжает использоваться vnic vmxnet3, а не passthrough/sr-iov
      • могут быть проблемы с разделением ресурса другими vm (выделенные ядра для этих VM не обслуживают vnic, vnic используют общие ядра!) даже на виртуальной машине с включенным latency sensitivity
      • могут быть проблемы с производительностью VM и всего хоста из-за роста количества обрабатываемых пакетов/прерываний в следствии отключения на VNIC interrupt coalescing и LRO
  • Но даже с их использованием в сравнении “БЕЗ ВИРТУАЛИЗАЦИИ” и даже с самой накрученной виртуализацией (все по максимуму проброшено в VM/зарезервировано) решение с виртуализацией проигрывает – пример с ping и response time (us), несмотря на в целом низкие значения в тесте (задержки с выбросами по 99.99 перцентилю не более 512 микросекунд, что = 0.5 миллисекунд) явно видно негативное влияние технологий виртуализации на задержку и даже в самом лучшем случае (который является спорным с точки зрения конфига, выше писал в СПОРНО 1) для ping выбросы задержки примерно два раза хуже чем без виртуализации вовсе (27 микросекунд против 46 микросекунд), хотя и медиана очень близка к эталону, аналогичное по 99.99 перцентилю видно и на графиках netperf с сетевыми картами SolarFlare. Для тестов с приближением к сценариям с высокими требованиями к задержке (достижение задержки 10 микросекунд) использовали специализированную NIC – Solarflare SFC9020, которая оффлоудит сетевой стек на себя (OpenOnload stack – specialized network hardware employs proprietary techniques that bypass the OS’s TCP/IP networking stack to achieve lower latency); при этом тест ping в результатах решили не показывать (не удивлюсь, что там результаты выше native). Еще из интересного. Так же в документе использовали:
      • как медиану вместо среднего для защиты от всплесков/выбросов (outliers),
      • (СПОРНО 2!) так и перцентили 90-99.99, интересно что max не использовали, хотя по факту он тоже может быть важным с аргументацией аналогичной описанной для перцентилей (т.е. отражение worst case behavior)
        • – Median response time – This metric is used to compare the average behavior between various configurations. Median is used instead of mean, since large outliers may distort the latter.
        • – 90/99/99.9/99.99 percentile response time – In extremely latency-sensitive applications, the worst case timing behavior (jitter in response time) is equally or more important than the average behavior. For example, response time may need to be bounded to some threshold (or deadline) or every (network) transaction needs to be finished at a certain fixed interval. Exceeding those requirements can be considered as failure. In order to observe the trend in the tail of the response time distribution, 90, 99, 99.9, and 99.99 percentile values are used to measure jitter of the workload.
      • В целом технологии обхода работают – для netperf теста результаты самого лучшего случая с виртуализацией по сути не хуже чем без виртуализации по приведенным тестам (мне бы еще было бы интересно посмотреть на MAX Latency, писал выше в СПОРНО 2!). 
      • Цифры с учетом обхода виртуализации хорошие, особенно показателен сценарий с 4-мя VM (сравнивать с конфигурацией БЕЗ ГИПЕРВИЗОРА некорректно т.к. такую конфигурации невозможно запустить БЕЗ ГИПЕРВИЗОРА), который по нагрузке “тяжелее” первого теста (как минимум для всех сценариев независимо от технологии самих пакетов больше на NIC и происходит шаринг LLC CPU), но задержка при этом выросла не сильно.
      • Самое интересное в виде пруфов:
- As expected, the Native configuration is the one that gives the best latency results for both the average timing behavior (represented by median values) and the worst case behavior (represented by 99/99.9/99.99 percentile values). 
- The VM-Latency-SRIOV gives the second best performance, which is achieved by avoiding the network I/O virtualization layer and the CPU scheduling overhead (hence the cost of VCPU halt/wake-up operations). 
The SRIOV comes in the third place by avoiding the network virtualization layer, followed by the default.
- Figure 4 shows the results with the 4VM setup. The Native configuration is not compared, since there is no straightforward way to match the 4VM setup. The Y-axis is depicted in a logarithmic scale.  The trend is very similar to the 1 VM setup: the VM Latency-SRIOV performs best in all metrics (median, 90/99/99.9/99.99 percentiles), followed by the VM-SRIOV and the VM-default configurations. The values are generally higher in all configurations compared to the 1 VM results except the median. This is because more packets need to be processed at the PNIC and they compete among each other for the processing. Also, the last level cache still needs to be shared by VMs that may add more jitter to response time. For the VM-default and VM-SRIOV configurations, running more VMs requires more work by the virtualization layer (network virtualization and CPU scheduling). 
- Following the Native configuration, the VM-Latency-SRIOV is the one that gives the best latency results among the three VM configurations by avoiding the network I/O virtualization and VCPU halt/wake-up latency both for 1VM and 4VM setups. The VM-SRIOV comes next, followed by the VM-Default configuration. Compared to the VM-Default, the VM-Latency-SRIOV considerably reduces the median response time from 47us to 30us in the 1 VM setup and from 56us to 33us in the 4-VM setup. Improvement is even bigger in jitter; for example, the VM-Latency-SRIOV reduces the 99.99 percentile by 87us compared to the VM-Default on the 4 VM setup, from 163us to 76us. This again clearly proves the efficacy of the latency-sensitivity feature. 
- Figure 7 shows the results comparing the three configurations (Native-Intel, Native-SFC, VM-Latency-SFC). VM-Latency-SFC shows very close performance to Native-SFC. The median and 90th percentile values (6 and 7us respectively) show the same performance to Native. The 99th percentile shows only 1us in difference. Not surprisingly, Native-Intel is placed in the last place since it does not use a specialized NIC. The results above clearly demonstrate that vSphere 5.5 is able to drive near-native performance even with specialized NICs with the latency-sensitivity feature enabled, achieving a very low latency in terms of both response time and jitter.

Pasted Graphic 2.png

Pasted Graphic 1.png

Pasted Graphic 5.png

Pasted Graphic 4.png

Achieving 10us Latency 
Extremely latency-sensitive applications such as high frequency trading sometimes utilize specialized network devices (PNICs) to further reduce response time and jitter. Such specialized network hardware often employs proprietary techniques that bypass the OS’s TCP/IP networking stack to achieve lower latency. This section evaluates latency using a Solarflare PNIC, SFC9020, with a TCP Onload feature [12]. The same testbed machines shown in Table 1 are used. 

Configurations 
Native-Intel – In this configuration, both client and server machines run RHEL6 Linux. Intel 82599EB 10Gbps
adapters are used to connect the two machines. 
Native-SFC – This configuration is exactly the same as the Native-Intel above except that Solarflare NICs are used instead of the Intel NIC. OpenOnload stack from Solarflare is used to fully utilize the benefits of Solarflare NICs.
VM-Latency-SFC – In this configuration, the client machine runs RHEL6 Linux and the server machine runs a 2-VCPU VM on vSphere 5.5. Both machines are connected using SolarFlare NICs. The latency-sensitivity feature is enabled for the VM and the VM DirectPath I/O feature is used to allow for the VM to directly access the Solarflare NIC. Like the Native-SFC, the OpenOnload stack from Solarflare is used to fully utilize the benefits of Solarflare NICs. 
The server machine of the two native configurations (Native and Native-SFC) is set to have only 2 CPUs online to match the number of VCPUs of the VM-Latency-SFC configuration. 
Since the benefit of using Solarflare NICs is better differentiated with the Netperf_RR workload than the Ping workload, only the Netperf_RR workload is used.

Pasted Graphic 6.png

Introduction
Performance demands of latency-sensitive applications have long been thought to be incompatible with virtualization. Such applications as distributed in-memory data management, stock trading, and high-performance computing (HPC) demand very low latency or jitter, typically of the order of up to tens of microseconds. Although virtualization brings the benefits of simplifying IT management and saving costs, the benefits come with an inherent overhead due to abstracting physical hardware and resources and sharing them.

Virtualization overhead may incur increased processing time and its variability. VMware vSphere® ensures that this overhead induced by virtualization is minimized so that it is not noticeable for a wide range of applications including most business critical applications such as database systems, Web applications, and messaging systems. vSphere also supports well applications with millisecond-level latency constraints such as VoIP streaming applications [6]. However, certain applications that are extremely latency-sensitive would still be affected by the overhead due to strict latency requirements.

In order to support virtual machines with strict latency requirements, vSphere 5.5 introduces a new per-VM feature called Latency Sensitivity. Among other optimizations, this feature allows virtual machines to exclusively own physical cores, thus avoiding overhead related to CPU scheduling and contention. Combined with a pass-through functionality, which bypasses the network virtualization layer, applications can achieve near-native performance in both response time and jitter.

Briefly, this paper presents the following:

• It explains major sources of latency increase due to virtualization, which are divided into two categories: 1) contention created by sharing resources and 2) overhead due to the extra layers of processing for virtualization.

• It presents details of the latency-sensitivity feature that improves performance in terms of both response time and jitter by eliminating the major sources of extra latency added by using virtualization.

• It presents evaluation results demonstrating that the latency-sensitivity feature combined with pass-through mechanisms considerably reduces both median response time and jitter compared to the default configuration, achieving near-native performance.

• It discusses the side effects of using the latency-sensitivity feature and presents best practices.

Latency Issues in a Virtualized Environment
Latency-sensitive applications typically demand a strict requirement for both response time of a transaction and its variability. The worst-case timing behavior is equally important to the average timing behavior. Transactions finishing too late (say, because packets are delivered too late) may even be considered as failures in certain types of applications. In the virtualized environment, however, meeting those requirements are more challenging due to 1) resource contention due to sharing and 2) the additional layer of scheduling virtual machines (VMs) and processing network packets for enabling resource sharing.

Resource Contention due to Sharing
One of the benefits that virtualization brings is reduced costs due to resource sharing (by consolidating many VMs in a single physical host). However, under heavy resource sharing, latency easily increases as the wait time for the resources (that is, ready time) increases. For example, with a large number of VMs running on the same host, the average response time of individual transactions of the workload would increase fast as they contend each other for resources such as CPU, memory, and network bandwidth.

Properly enforcing resource entitlement for VMs (hence controlling resources allocated to VMs) handles well those resource contention issues for the majority of applications. vSphere’s fair share CPU scheduling allocates more CPU time to VMs with more CPU entitlement so that transactions can be quickly processed under CPU contention [2]. vSphere provides similar control knobs for enforcing memory entitlement [3]. Network I/O Control (NetIOC) partitions the physical network bandwidth based on its entitlement [8], which helps with bounding the

(average) network packet processing latency. Enforcing resource entitlement in vSphere, however, is done at a relatively coarser time scale (for example, milliseconds). This may not be sufficient to support extremely latency-sensitive applications; it is possible for individual transactions or packets to have missed their latency requirements.

Overhead Due to Virtualization Layers
In a virtualized environment, the guest cannot directly access the physical resources in the host; there are extra virtual layers to traverse and the guest sees only virtualized resources (unless the VM is specifically configured via a pass-through mechanism to be given direct access to a physical resource). This is essential to allow the benefit of sharing resources while giving the illusion that virtual machines own the hardware. This also implies that there is an overhead associated with those virtualization layers.

Network I/O Virtualization
Since network devices are typically shared by multiple VMs, a VM cannot be allowed direct access to a physical network interface card (PNIC). Instead, a VM can be configured with virtual NICs (VNIC) that are supported by the virtual machine hardware [1]. In addition, in order to properly connect VMs to the physical networks or connecting VMs to each other, a switching layer is necessary. The cost of NIC virtualization and virtual switching is directly added to the response time and affects its variance due to extra processing.

In vSphere, the virtual machine monitor (VMM) manages the virtual machine hardware for the guest, while VM kernel manages physical hardware resources. (Throughput this paper, the virtualization layer combining both VMM and VMkernel is collectively referred to as hypervisor .) VMkernel utilizes dedicated threads to process network I/O and perform network virtualization. The communication between VMM and VMkernel (threads) involving network I/O are batched in an attempt to reduce the inefficiencies due to frequent communication. This technique, referred to as V NIC coalescing in this paper, can add an extra delay and variance to the response time.

In addition to the VNIC coalescing, vSphere supports Large Receive Offload (LRO) for VNICs to further reduce CPU cost by aggregating multiple incoming TCP packets into a large single packet. The side effect is similar to that of VNIC coalescing; it can impact response time and jitter in processing packets.

CPU Virtualization
Similar to other resources such as NICs, physical CPUs (PCPUs) also need to be virtualized. VMs do not exclusively own PCPUs, but they are instead configured with virtual CPUs (VCPU) supported by the virtual machine hardware. vSphere’s proportional-share-based CPU scheduler enforces a necessary CPU time to VCPUs based on their entitlement [2]. This is an extra step in addition to the guest OS scheduling work. Any scheduling latency in the VMkernel’s CPU scheduler and the context-switching cost from the VMM to the VMkernel to run the scheduler therefore results in an additional delay.

The CPU scheduler overhead is more visible when VCPUs frequently halt and wake up. Such a behavior is fairly commonly seen in latency-sensitive workloads where the VCPU becomes idle after a packet is sent out because it has to wait for a subsequent request from the client. Whenever the VCPU becomes idle and enters a halted state, it is removed from the PCPU by the scheduler. Once a new packet comes in, the CPU scheduler runs to make the VCPU ready again. This process of descheduling and rescheduling of a VCPU performed at each transaction incurs a non-negligible and variable latency that leads to increased response time and jitter. 

Another consequence of CPU virtualization is the sharing of the last level cache (LLC) between VMs. The impact of sharing LLC depends on workloads that VMs run; a memory-intensive VM can negatively affect the performance of other VMs on the same socket by polluting the LLC.

Other Sources of Latency Issues
Power management in both the BIOS and vSphere can negatively affect latency. It is therefore recommended to turn off all power management schemes to achieve the lowest latency. For details on configuring power management settings, refer to the Host Power Management in VMware vSphere 5 [14].

Latency can be also impacted by other shared resources such as memory and storage. Since the Latency-Sensitivity feature addresses only CPU and network related issues on the host where the VM is running, we will not discuss latency overhead from other shared resources.

Latency-Sensitivity Feature
The Latency-Sensitivity feature aims at eliminating the aforementioned major sources of extra latency imposed by virtualization to achieve low response time and jitter. Briefly, this per-VM feature achieves the goal by 1) giving exclusive access to physical resources to avoid resource contention due to sharing, 2) bypassing virtualization layers to eliminate the overhead of extra processing, and 3) tuning virtualization layers to reduce the overhead. Performance can be further improved when the latency-sensitivity feature is used together with a pass-through mechanism such as single-root I/O virtualization (SR-IOV).

Enabling the Latency-Sensitivity Feature
To enable the latency-sensitivity feature, the virtual machine’s Latency Sensitivity should be set to be High. The High setting is designed for extremely latency-sensitive applications and all the functionalities and tunings that this feature provides are applied. The Normal setting does not engage the latency-sensitivity feature. 

The latency-sensitivity feature is applied per VM, and thus a vSphere host can run a mix of normal VMs and VMs with this feature enabled. To enable the latency sensitivity for a given VM from the UI, access the Advanced Settings from the VM Options tab in the VM’s Edit Settings pop-up window and select High for the Latency Sensitivity.

Enabling the latency-sensitivity feature requires memory reservation. Also, we recommend over-provisioning CPU to reduce contention; the number of VCPUs in the host should be less than the number of PCPUs to leave one or more PCPUs for VMkernel threads for I/O processing and system management. Since CPU contention from other VMs can change over time (for example, due to configuration changes), we strongly recommended maximizing CPU reservations of latency-sensitive VMs for best performance.

What the Latency-Sensitivity Feature Does
Gives Exclusive Access to Physical Resources
• With the latency-sensitivity feature enabled, the CPU scheduler determines whether exclusive access to PCPUs can be given or not considering various factors including whether PCPUs are over-committed or not. Reserving 100% of VCPU time guarantees exclusive PCPU access to the VM. With exclusive PCPU access given, each VCPU entirely owns a specific PCPU; no other VCPUs and threads (including VMkernel I/O threads) are allowed to run on it. This achieves nearly zero ready time and no interruption from other VMkernel threads, improving response time and jitter under CPU contention. Note that even with exclusive access to PCPUs, the LLC is still shared with other VMs and threads residing on the same socket.

• The latency-sensitivity feature requires the user to reserve the VM’s memory to ensure that the memory size requested by the VM is always available. Without memory reservation, vSphere may reclaim memory from the VM, when the host free memory gets scarce. Some memory reclamation techniques such as ballooning and hypervisor swapping may significantly downgrade VM performance, when the VM accesses the memory region that has been swapped out to the disk. Memory reservation prevents such performance degradation from happening. More details on memory management in vSphere can be found in VMware’s memory resource management white paper [3].

Bypasses Virtualization Layers
• Once exclusive access to PCPUs is obtained, the feature allows the VCPUs to bypass the VMkernel’s CPU scheduling layer and directly halt in the VMM, since there are no other contexts that need to be scheduled.

That way, the cost of running the CPU scheduler code and the cost of switching between the VMkernel and VMM are avoided, leading to much faster VCPU halt/wake-up operations. VCPUs still experience switches between the direct guest code execution and the VMM, but this operation is relatively cheap with the hardware-assisted visualization technologies provided by recent CPU architectures [10][11].

Tunes Virtualization Layers
• When the VMXNET3 paravirtualized device is used for VNICs in the VM, VNIC interrupt coalescing and LRO support for the VNICs are automatically disabled to reduce response time and its jitter. Although such tunings can help improve performance, they may have a negative side effect in certain scenarios, which is discussed later in this paper. If hardware supports a pass-through mechanism such as single-root I/O virtualization (SR-IOV) and the VM doesn’t need a certain virtualization features such as vMotion, NetIOC, and fault tolerance, we recommend the use of a pass-through mechanism for the latency-sensitive feature. Tuning techniques to improve latency for normal VMs (without the latency-sensitivity feature) can be found in the best practices white paper [4].

Using a Pass-Through Mechanism with the Latency-Sensitivity Feature

Although, the latency-sensitivity feature tunes the VMXNET3 device to reduce response time and jitter, packets still have to go through the whole network virtualization layer. Avoiding the network virtualization layer requires the use of a pass-through mechanism. Single-root I/O virtualization (SR-IOV) is a standard that enables one PCI Express (PCIe) adapter to be presented as multiple, separate logical devices to VMs [7]. On supported hardware, one or more VMs can be configured to directly access one or more of the logical devices directly. vSphere also supports VM DirectPath I/O, which allows VMs to access a wider range of network devices, but does not allow multiple VMs to share the same device. Please note that the use of a pass-through mechanism is incompatible

with many of the benefits of virtualization such as vMotion (except DirectPath I/O with vMotion on the Cisco UCS platform), NetIOC, network virtualization, and fault tolerance. For configuring pass-through mechanisms

including SR-IOV, refer to the vSphere Networking Guide for vSphere 5.1 or later [13].

Side Effects of Latency-Sensitivity Feature
Impact of CPU Exclusive Access with the Latency-Sensitivity Feature
The evaluation so far is conducted in scenarios where there is not much CPU contention for the VMs, if any. In a real deployment scenario, it is common to run many VMs in a single host to efficiently utilize resources. Exclusive PCPU access enabled by the latency-sensitivity feature allows the VM to achieve near-zero VCPU ready time, considerably improving performance. However, such a benefit comes at an expense:

• The PCPUs exclusively given to a VM with latency-sensitivity enabled may not be used by other VMs even when the PCPUs are idle. This may lower overall CPU utilization and hence system throughput, negatively impacting the performance of other VMs without latency-sensitivity enabled.
• If a latency-sensitive VM uses VNICs, VMkernel I/O threads are used for network processing. Since VMkernel I/O threads are not allowed to run on the PCPUs exclusively owned by the VM, they become to share the remaining PCPUs with others. If those VMkernel I/O threads do not get enough CPU due to contention, the VM can experience a negative performance impact, even when all VCPUs are given exclusive access to PCPUs.

Once exclusive PCPU access is given to the latency-sensitive VMs (by enabling the latency-sensitive feature for the VMs and making sure these VMs have enough CPU allocation), they show much better response time (73us) than without it (106us), clearly demonstrating the benefit of exclusively owning PCPUs. However, once the two latency-sensitive VMs exclusively occupy PCPUs, throughput-intensive VMs experience a much higher ready time and, as a result, throughput drops from 209K transactions per second to 90K transactions per second.

Image.heic

Impact of Using VMXNET3 Device with Latency-Sensitivity Feature
When VMXNET3 devices are used (instead of a pass-through mechanism such as SR-IOV), the latency-sensitivity feature automatically disables the VNIC interrupt coalescing and LRO. While doing so helps to improve latency, it may in turn increase CPU cost both for the guest and the hypervisor as the packet rate becomes higher. VMs have to process more interrupts and the hypervisor has to wake up the VMs more frequently. This may negatively impact throughput in certain scenarios such as workloads with a high packet rate due to an increased per-packet processing cost.
Hyper-V

Hyper-V устанавливается через дополнительные компоненты как простой компонент типа Telnet.  И работает хорошо на первый взгляд – легко развернулась VM Ubuntu 18.04. Легко заресайзил с его использованием VHD/VHDX диски. Огонь.

  • Отключение IPv6 для раздачи Hyper-V на VM (кейс – неизвестный адрес девайса по IPv4, а по консоли доступа по какой-то причине нет, напр. отключена) – просто в сетевых параметрах адаптера Hyper-V Virtual Adapter (vEthernet Default Switch) в панели управления отключаем IPv6, рестартуем адаптер (мне было достаточно) или возможно весь ПК.
    You can edit each network adapter and uncheck the IP6 binding; in your case edit the Hyper-V Virtual adapter. You may need to reboot for it to take effect. You should no longer have an IP6 address assigned to the adapter.
  • “Under the hood” Azure используется модифицированный под облачный сценарий Hyper-V.
https://www.quora.com/What-technology-is-Azure-running-on-Is-it-on-Hyper-V-or-some-other-kind-of-virtualization-technology     
Azure runs on a customized version of Hyper-V.

С самого Azure:
   root@user~# virt-what
   hyperv

   root@user:~# lscpu | grep Hypervisor
   Hypervisor vendor:   Microsoft

   root@user:~# cpuid -l 0x40000000
   CPU 0:
   hypervisor_id = "Microsoft Hv"

Работа с VHD/VHDX.

Virtual Hard Drive (VHD) — формат файла, содержащий полную структуру и содержание, сходные с жёстким диском. Используется для хранения виртуальных операционных систем, программ и других файлов в одном файле-образе, который можно открыть разными программами виртуализации или виртуальными машинами. C июня 2005 Microsoft сделала спецификацию формата VHD доступной третьим фирмам в рамках Microsoft Open Specification Promise.

Получение информации

Get-VHD -Path D:\livecd.ubuntu-cpc.azure-resized.vhd

Уменьшение размера, работает только для VHDX и даже для него без Optimize-VHD (тоже только для VHDX)/GPARTED можно не обойтись

Resize-VHD -Path D:\livecd.ubuntu-cpc.azure.vhdx -ToMinimumSize
Optimize-VHD -Path D:\livecd.ubuntu-cpc.azure.vhd -Mode Quick

# конвертируем в VHDX
Resize-VHD : Не удалось изменить размер виртуального диска.
Системе не удалось изменить размер "D:\livecd.ubuntu-cpc.azure.vhd".
Невозможно выполнить запрошенную операцию, так как изменение размера на значение, не превышающее текущее, поддерживается только для виртуальных жестких дисков формата VHDX.

# используем потенциально Optimize-VHD/GPART
Resize-VHD : Не удалось изменить размер виртуального диска.
Не удалось изменить размер виртуального диска.
Системе не удалось изменить размер "D:\livecd.ubuntu-cpc.azure.vhdx": Не удалось выполнить запрошенную операцию, так как
невозможно безопасно уменьшить размер виртуального диска. (0xC03A0027).

Увеличение размера (образ был 3GB)

Resize-VHD -Path D:\livecd.ubuntu-cpc.azure-resized.vhd -SizeBytes 4GB

Конвертация (удобнее в Hyper-V) из VHD в VHDX

Convert-VHD -Path D:\livecd.ubuntu-cpc.azure-resized.vhd -VHDType Fixed -DestinationPath D:\livecd.ubuntu-cpc.azure-resized.vhdx -DeleteSource

 

 

KVM/QEMU

  • https://www.linux-kvm.org/page/Management_Tools список managent утилит поверх KVM
  • KSM функционал KVM это крутая фича – kernel samepage merging is a memory-saving de-duplication feature, that merges anonymous (private) pages (not pagecache ones). KSM (Kernel Samepage Merging) is running in the Linux kernel and scans the memory of all the virtual machines running on a single host, looking for duplication and consolidating. With KSM we’re able to improve virtual machine density by as much as 300% without impacting performance. One of the great benefits of using Linux as the hypervisor means KSM is not limited to KVM and virtual machines, but can also reduce memory pressure with normal Linux applications. Just install several KVM virtual machines with the same OS (using at least 80% of your physical memory on the host) and wait a few minutes. You will notice higher CPU activities on the host (ksm daemon) and the used memory on the host will be lowered significantly (see start page showing the overall memory usage).Howto verify that KSM is working (how many pages are being shared between your KVM guests):
    watch cat /sys/kernel/mm/ksm/pages_sharing

Компания Google представила инициативу kvmCTF, в рамках которой исследователи безопасности могут получить денежное вознаграждение за выявление уязвимостей в гипервизоре KVM (Kernel-based Virtual Machine). Интерес Google к KVM обусловлен использованием данного гипервизора в сервисе Google Cloud, а также в платформах Android и ChromeOS (CrosVMоснован на KVM). Для получения вознаграждения должен быть продемонстрирован взлом специально подготовленного окружения CTF (Capture the Flag) на базе свежего ядра Linux, выполняющего виртуальную машину, доступ к которой предоставляется по заявкам. Атакующему предлагается эксплуатировать уязвимость в подсистеме KVM в ядре Linux, обеспечивающем работу хост-системы в данном окружении.

libvirt

ключевой демон, через который происходит взаимодействие между утилитами управления (virsh, virt-manager, virt-viewer) и гипервизорами (xen, kvm/qemu, vmware, virtualbox, etc).

 

Proxmox

  • (Proxmox, centos) В ядро linux делали доработки, в своей версии для ядра добавляют флаг pve (proxmox virtual edition), по аналогии с centos – там добавляли флаг el (enterprise linux)
Screenshot
Screenshot

Хорош, но даже для домашнего гипервизора зачастую проще/надежнее использовать ESXi – его бесплатной версии (после покупки broadcom бесплатной версии нет :)) чаще всего достаточно. Плюсы Proxmox:

    1. Основан на Debian, для виртуализации использует QEMU/KVM
    2. Популярен, напр. его используют
      1. в немаленькой компании carprice
      2. в достаточно маленьком сайте linkmeup (смигрировали с vmware)
      3. в jet для разных лаблраторных стендов
      4. в куче home lab и лабораториях, например при преподавании (LPIC-2)
        • Screenshot
        • Screenshot
    3. Имеет коммерческую поддержку
    4. Поддерживает в том числе “сетевые” (network function) VM – pfsense например
    5. Поддерживает массовые запуски/остановы VM, сценарии автоматизации деплоя VM (клонирование vm/дисков) на основе сценариев в CLI (оболочка proxmox console)
    6. Прост
      • первичный деплой возможен не только из пакета, но и из iso на bare-metal (аналогия с ESXi)
      • эксплуатация (WEB, CLI и даже API)
    7. Надежен
    8. Функционал/масштабирование достаточны для home/SOHO задач
    9. Умеет работать с разными хранилищами – lvm, btrfs, nfs, smb/cifs, glusterfs, iscsi, cephfs, zfs over iscsi, zfs, proxmox backup server; пример для glusterfs в статье про glusterfs

 

 

 

 

OVIRT

oVirt довольно неплох на практике:

    1. Глубокий и удобный функционал из GUI (по сути удобная прослойка к libvirt)
    2. Хорошая масштабируемость
    3. На его основе работают многие отечественные продукты (напр. РЕДОС)

Из недостатков oVirt:

    1. Основан на RHEL (RHEL, CentOS, Rocky Linux, Fedora), поэтому привязан к этому семейству ОС – как для host, так и для engine
    2. Для работы даже с одним хостом (гипервизором), требует установку контроллера Engine (аналогия vSphere)

EXPORT OVA/DISK/IMAGE

export ova ovirt и export/download disk image – могут не работать по факту, особенно если созданы snapshot для VM. Выгрузка с гипервизора ova через scp простая:

scp root@1.1.1.1:/tmp/Astra.ova

 

 

questions

Which of the following properties of a Linux system should be changed when a virtual machine is cloned? (Choose two.)

A. The partitioning scheme

B. The file system

C. The D-Bus Machine ID

D. The permissions of /root/

E. The SSH host keys

Answer: CE
Some configurations are machine specific. For example, a network card's MAC address should be unique for whole the network. If we are cloning a machine or sometimes creating them from templates, at least we need to change these on each machine before booting them:
Host Name
- NIC MAC Address
- NIC IP (If not using DHCP)
- Machine ID (delete the /etc/machine-idand /var/lib/dbus/machine-id and run dbus-uuidgen --ensure. These two files might be soft links to each other) - Encryption Keys like SSH Fingerprints and PGP keys - HDD UUIDs Any other UUIDs on the system

 

 

Leave a Reply