Конвертировать vmware в kvm
The virt-v2v tool converts virtual machines (VMs), including their disk images and metadata, from foreign hypervisors for use with Red Hat Enterprise Linux with KVM managed by libvirt, Red Hat Virtualization, and Red Hat OpenStack Platform.
This article provides instructions for converting a Windows VM from a VMware vCenter hypervisor to run on Red Hat Enterprise Linux 7 KVM and Red Hat Enterprise Linux 8 KVM.
For an overview of the virt-v2v tool, supported conversions, and links to other types of virtual machine conversions, see Converting Virtual Machines from Other Hypervisors to KVM with virt-v2v in RHEL 7 and RHEL 8.
On successful completion of the conversion process, virt-v2v creates a new libvirt domain XML file for the converted VM with the same name as the original VM. The VM can be started using libvirt tools, such as virt-manager or virsh.
Note: If virt-v2v is run as a non-root user, the virt-manager application will not detect the converted VM. This is because virt-v2v saves converted VMs to the current user's namespace, but libvirt maintains separate namespaces for the VMs for each user.
Available os options
To list the supported operation system you can use the osinfo-query os command
Можно ли использовать KVM на CPU без поддержки аппаратной виртуализации?¶
Нет. KVM требует наличие активной аппаратной виртуализации и при её осутствии работать не будет.
В то же время, без наличия этой функции со стороны CPU, могут работать VirtualBox до версии 6.1.0 и VMWare, хотя и с очень низкой производительностью.
Install
Open Device Manager
Open device Manager in the control panel or type devmgmt.msc on the command prompt.
Update the drivers
- balloon, the balloon driver affects the PCI device
- vioserial, affects the PCI simple communication controler
- NetKVM, the network driver affects the Network adapters.
- viostor, the block driver affects the Disk drives.
Update the PCI drivers
In windows 10 the PCI device and the PCI Simple Communications Controller have the missing driver icon. Right click on the PCI device and select update driver -> click on Browse my computer for driver software Specify the cdrom as the search location and click Next, this will install the Balloon driver.
Do the same for the PCI Simple Communications Controller this will install the “VirtIO Serial Driver”
install the VioStor driver
Add a temporary disk to the virtual machine and use VirtIO as the Bus Type In the Device Manager you’ll get a new device SCSI Controller right click it and update the driver. This will install the Red Hat VirtIO SCSI controller
Go to the device settings of your virtual machine and change the Disk bus to VirtIO and shutdown you virtual machine.
You can remove the temporary disk now or leave it if you can find some use for it…
Make sure that you disk is selected as the bootable device.
Start the virtual machine and make sure that the system is bootable.
install the netKVM driver
Update the Device model to virtio.
Start devmgmt.msc and update the driver as we did before….
And verify that you network card works correctly.
install the QXL graphical driver
Update the Microsoft Basic Display Adapter
After the installation you can change the the display resolution.
If you want to use higher screen resolutions you need to increase the video ram
Procedure
Какую систему управления виртуальными машинами лучше установить?¶
Рекомендуется использовать KVM , т.к. её гипервизор и необходимые модули уже находятся в ядре Linux и не вызывают проблем.
Как определить имеет ли процессор аппаратную поддержку виртуализации?¶
Проверим наличие флагов vmx (Intel), либо svm (AMD) в выводе /proc/cpuinfo :
Как правильно установить систему виртуализации KVM?¶
Установим KVM и графическую утилиту управления виртуальными машинами virt-manager:
Перезагрузим машину для вступления изменений в силу:
Как правильно установить VirtualBox в Fedora?¶
Сначала нужно подключить репозиторий RPM Fusion , затем выполнить:
Для нормальной работы с USB устройствами и общими папками потребуется также добавить свой аккаунт в группу vboxusers и vboxsf:
Step 6 [Optional]
Update the imported VM's network configuration.
The virt-v2v tool cannot currently reconfigure a VM's network configuration. If the converted VM is not connected to the same subnet as the source, its network configuration may have to be updated. For more information, see the virt-customize(1) man page.
Как оптимизировать KVM для работы с SSD-накопителей?¶
Каких-то особых оптимизаций производить не требуется. Достаточно лишь использовать дисковые образы гостевых ОС в формате QCOW2, а также при их подключении указать тип контроллера VirtIO и установить следующие опции:
discard mode: unmap;
detect zeroes: unmap.
Конечно же как в хостовой, так и в гостевой ОС, должна быть включена поддержка TRIM .
Шаг 2. Создаем новый виртуальный сервер в среде Hyper-V
После успешного завершения конвертирования, создаём новый виртуальный сервер с VHDX диском из прошлого шага.
Выбираем название для виртуального сервера:
Указываем поколение виртуальной машины. (Выбираем 1-ое поколение, со вторым не работает после конвертации, только для новых ВМ)
В меню жесткого диска выбираем “использовать имеющийся виртуальный жесткий диск” и указываем путь до него.
Запускаем виртуальный сервер и проверяем.
Для сжатия образа можете воспользоваться утилитой SDelete. Руководство по очистке свободного места на диске при помощи утилиты SDelete.
Linux KVM is getting more and more useable for desktop virtualization thanks to the the virtio and QXL/SPICE drivers.
Most Linux distributes have the virtio & QXL drivers you might need to install the spice-vdagent.
On Windows you can download and install the virtio and QXL drivers.
Using the virtio drivers will improve your guest system performance and your virtualization experience.
Запускаем конвертирование
Step 1
Install the virt-v2v package and its dependencies on the host system:
Step 5
Confirm that the VM was imported correctly with the following command:
If this command lists the new Windows VM, you have successfully converted and imported the VM.
Further resources
For more information on managing VMs with libvirt in RHEL 8, see Configuring and Managing Virtualization.
For more information on using virt-v2v to convert VMs, you can see the following articles:
In addition, you can refer to the virt-v2v man page and the virt-v2v upstream documentation.
Выбираем конвертируемый RAW-образ
Как правильно установить в KVM Windows?¶
Step 4
Observe the conversion progress. A successful conversion output looks similar to the following:
Import the disk image to KVM
We’ll inport the disk image with virt-install it’s also posible to import the images with virt-manager if you prefer a graphical interface or or just being lazy :-)
Further resources
For more information on managing virtual machines with libvirt in RHEL 7, see the Red Hat Enterprise Linux 7 Virtualization Deployment and Administration Guide.
For more information on managing virtual machines with libvirt in RHEL 8, see Configuring and Managing Virtualization.
For more information on using virt-v2v to convert virtual machines, you can see the following articles:
In addition, you can refer to the virt-v2v man page and the virt-v2v upstream documentation.
Так уж вышло, что потребовалось отказаться от виртуализации KVM в пользу Hyper-V и встала задача, как же быстро перенести порядка 25 рабочих мест клиента на Windows без дополнительных плясок с бубнами? Как оказалось - очень просто.
Как переместить виртуальную машину KVM на другой ПК?¶
Переместим образы дисков из каталога /var/lib/libvirt/images старого хоста на новый любым удобным способом .
Экспортируем конфигурацию виртуальной машины:
Здесь vmname – название машины KVM, а vmname.xml – имя файла, в котором будут сохранены настройки.
Импортируем ранее сохранённую конфигурацию:
Новая виртуальная машина появится в списке и будет готова к работе немедленно.
Как переместить виртуальную машину VirtualBox на другой ПК?¶
Получим список доступных виртуальных машин VirtualBox:
Экспортируем настройки и данные в открытый формат виртуализации версии 2.0:
Здесь vmname – название виртуальной машины VirtualBox, а vmname.ova – имя файла экспорта.
Переместим полученный файл на новый хост любым удобным способом , затем осуществим его импорт:
Через некоторое время новая виртуальная машина появится в списке и будет готова к работе.
Step 7 [Optional]
Update the imported VM's network configuration.
The virt-v2v tool cannot currently reconfigure a VM's network configuration. If the converted VM is not connected to the same subnet as the source, its network configuration may have to be updated. For more information, see the virt-customize(1) man page.
Как уменьшить размер дискового образа QCOW2?¶
Уменьшение размера дискового образа QCOW2 при помощи qemu-img – это достаточно небезопасная операция, которая может привести к его повреждению, поэтому вместо отрицательных значений для resize сначала уменьшим размер дисковых разделов внутри самой гостевой ОС при помощи fdisk, Gparted или любого другого редактора разделов диска так, чтобы справа осталось лишь неразмеченное пространство.
Далее воспользуемся утилитой qemu-img и сделаем копию образа, которая уже не будет включать неразмеченное дисковое пространство:
В случае необходимости создания образа фиксированного размера , добавим параметр -o preallocation=full :
Подключим новый образ к виртуальной машине вместо старого и проверим работу. Если всё верно, старый можно удалить.
Convert the disk image
Get them…
Type of virtio drivers
The following virtio windows drivers are available.
- block (disk drivers)
- network
- baloon ((dynamic memory management)
The fedoraproject provides pre compiled iso images containig all the virtio drivers and installation images for windows XP.
ISO contents
- NetKVM/ - Virtio network driver
- viostor/ - Virtio block driver
- vioscsi/ - Virtio Small Computer System Interface (SCSI) driver
- viorng/ - Virtio RNG driver
- vioser/ - Virtio serial driver
- Balloon/ - Virtio memory balloon driver
- qxl/ - QXL graphics driver for Windows 7 and earlier. (build virtio-win-0.1.103-1 and later)
- qxldod/ - QXL graphics driver for Windows 8 and later. (build virtio-win-0.1.103-2 and later)
- pvpanic/ - QEMU pvpanic device driver (build virtio-win-0.1.103-2 and later)
- guest-agent/ - QEMU Guest Agent 32bit and 64bit MSI installers
- qemupciserial/ - QEMU PCI serial device driver
- *.vfd VFD floppy images for using during install of Windows XP
Download
I use arch linux and download virtio-win AUR package with pacaur. You can download the images directly or use the installation packages for your Linux distribution.
This install virtio images to /usr/share/virtio/
virtio-win.iso is the ISO cdrom image containing all the drivers.
Как отключить запрос пароля во время запуска или остановки виртуальных машин при использовании KVM?¶
Возможностью управления виртуальными машинами обладают члены группы libvirt, поэтому нужно добавить в неё свой аккаунт:
Какой тип QCOW2 образов выбрать?¶
Существует два типа образов:
динамически расширяющийся ;
фиксированного размера .
У каждого есть как достоинства, так и недостатки.
mount the iso image
Make sure that the cdrom is mounted in windows.
Указываем путь для конвертируемого образа
В моем примере указан сервер Hyper-V, можно указать просто локальный путь.
Вводим доступы для подключения к Hyper-V серверу, в случае с локальным, эти действия не требуются.
Как увеличить размер дискового образа QCOW2?¶
Воспользуемся утилитой qemu-img для увеличения дискового образа:
При использовании образов фиксированного размера , добавим параметр --preallocation=full :
Здесь вместо +10G укажем насколько следует расширить образ. Все операции должны выполняться при остановленной виртуальной машине, в которой он смонтирован.
По окончании, внутри гостевой ОС расширим используемую файловую систему до новых границ образа при помощи fdisk, GParted или любого другого редактора разделов диска.
convert the vmdk image to qcow2
Convert the VMDK disk image to qcow2
Prerequisites
Note that on Red Hat Enterprise Linux 7, Windows VMs are supported only under specific subscription programs, such as Advanced Mission Critical (AMC).
virt-v2v must be run on a Red Hat Enterprise Linux 64-bit host system.
Ensure that the virtual machine is stopped prior to running the conversion process. In addition, remove the VMWare Tools program from the VM.
If attempting to convert a Windows 7 or a Windows Server 2008 R2 virtual machine (VM) using the virt-v2v utility, the support for SHA-2 signing certificates must be applied to the VM. For instructions to do so, see Microsoft Security Advisory 3033929. If SHA-2 support is not applied, the converted VM will not work properly.
The following minimum system resources must be available:
- Minimum network speed 1Gbps
- Disk space: sufficient space to store the VM's disk image, plus 1 GB
- Sufficient free space in the VM's file system according to the following table:
Выбираем формат образа
Выбираем необходимый формат образа. Поскольку в конвертируемом образе я использую Windows Server 2012 R2, то конвертировать буду в динамический VHDX.
Procedure
import
We need to import the disk image as IDE device since we don’t have the virtio driver in our windows disk image (yet).
Prerequisites
virt-v2v must be run on a Red Hat Enterprise Linux 64-bit host system.
Ensure that the VM is stopped prior to running the conversion process.
The following minimum system resources must be available:
- Minimum network speed 1Gbps
- Disk space: sufficient space to store the VM's disk image, plus 1 GB
- Sufficient free space in the VM file system according to the following table:
Step 2
Note: If the vpx user name contains a backslash character (such as DOMAIN\USER), it is necessary to enter a URI escape for the character: DOMAIN%5cUSER. Similarly, spaces in the Datacenter name must be entered using the %20 code.
For a full list of virt-v2v parameters, see the virt-v2v man page.
Что нужно знать об образах фиксированного размера?¶
практически не фрагментируются, т.к. все блоки для них заранее зарезервированы на диске;
имеют более высокую производительность по сравнению с динамически расширяющимися образами .
занимают очень много места на диске, хотя если файловая система поддерживает разреженные (sparse) файлы, эта функция будет использоваться в полном объёме.
Как преобразовать образ виртуальной машины Hyper-V в формат, совместимый с KVM?¶
Для преобразования образа воспользуемся штатной утилитой qemu-img:
Install the virtio drivers and QXL graphics drivers
Как создать ярлык запуска виртуальной машины KVM?¶
Для создания ярлыка в главном меню рабочей среды, создадим файл fedora-rawhide.desktop в каталоге ~/.local/share/applications следующего содержания:
Здесь вместо Fedora-Rawhide укажем реальное имя виртуальной машины KVM, а qemu:///session – сеанс, в котором она создана (session – пользовательский; system – системный).
The virt-v2v tool converts virtual machines (VMs), including their disk images and metadata, from foreign hypervisors for use with Red Hat Enterprise Linux with KVM managed by libvirt, Red Hat Virtualization, and Red Hat OpenStack Platform.
This article provides instructions for converting a Linux VM from a VMware vCenter hypervisor to run on Red Hat Enterprise Linux 7 KVM and Red Hat Enterprise Linux 8 KVM.
For an overview of the virt-v2v tool, supported conversions, and links to other types of VM conversions, see Converting Virtual Machines from Other Hypervisors to KVM with virt-v2v in RHEL 7 and RHEL 8.
On successful completion of the conversion process, virt-v2v creates a new libvirt domain XML file for the converted VM with the same name as the original VM. The VM can be started using libvirt tools, such as virt-manager or virsh.
Note: If virt-v2v is run as a non-root user, the virt-manager application will not detect the converted VM. This is because virt-v2v saves converted VMs to the current user's namespace, but libvirt maintains separate namespaces for the VMs for each user.
Step 2
Note: If the vpx username contains a backslash character (such as DOMAIN\USER), it is necessary to enter a URI escape for the character: DOMAIN%5cUSER. Similarly, spaces in the Datacenter name must be entered using the %20 code.
For a full list of virt-v2v parameters, see the virt-v2v man page.
Что нужно знать о динамически расширяющихся образах?¶
занимают меньше места на диске, постепенно расширяясь до заданного предела.
очень сильно фрагментируются;
производительность значительно уступает образам фиксированного размера .
Как конвертировать динамически расширяющийся образ диска VirtualBox в фиксированный?¶
Динамическая конвертация не поддерживается, поэтому воспользуемся утилитой VBoxManage, входящей в базовую поставку VirtualBox, для создания нового дискового образа на базе старого:
Теперь в свойствах виртуальной машины подключим новый образ фиксированного размера. Старый при этом можно удалить.
Можно ли перенести каталог с образами виртуальных машин KVM?¶
По умолчанию образы создаваемых виртуальных машин создаются в каталоге /var/lib/libvirt/images , что многих не устраивает.
Переместим образы виртуальных машин на отдельный накопитель, смонтированный как /media/foo-bar . ISO будем размещать в каталоге iso , а дисковые образы виртуальных машин – images .
Создаём собственные политики SELinux для указанных каталогов:
Сбросим контекст безопасности SELinux для них:
В настройках Virt Manager добавим новую библиотеку /media/foo-bar/images и зададим её использование для всех виртуальных машин по умолчанию.
Step 5
Confirm that the VM has been imported correctly:
If this command lists the new Linux VM, you have successfully converted and imported the VM. Boot the VM's guest OS and confirm its full functionality before deleting the original VM or migrating active services.
Какие дисковые образы лучше: динамически расширяющиеся или фиксированного размера?¶
Фиксированного размера, т.к. они меньше фрагментируются.
Можно ли отключить защиту от уязвимостей CPU в гостевых Windows внутри виртуальных машин?¶
Да, согласно MSDN, при помощи следующего REG файла:
Step 3
Authenticate to the VMware vCenter server.
Connecting to the VMware vCenter server requires authentication. virt-v2v supports password authentication when connecting to VMware vCenter. The password can be entered during conversion, or by using the --password-file option.
Note: When the VMware vCenter server is not configured with a valid vCenter CA certificate, for example if it uses a self-signed certificate, connecting to the server will fail. In this case, certificate checking can be explicitly disabled by adding ?no_verify=1 to the connection URI as shown below:
Step 3
Authenticate to the VMware vCenter server.
Connecting to the VMware vCenter server requires authentication. virt-v2v supports password authentication when connecting to VMware vCenter. The password can be entered during conversion, or by using the --password-file option.
Note: When the VMware vCenter server is not configured with a valid vCenter CA certificate, for example if it uses a self-signed certificate, connecting to the server will fail. In this case, certificate checking can be explicitly disabled by adding ?no_verify=1 to the connection URI as shown below:
Step 6
When the offline conversion is complete, the converted guest does not yet have all necessary drivers installed to work correctly. These will be installed automatically the first time the guest boots.
Important: Do not interrupt the automatic driver installation process when logging in to the guest for the first time, because this may prevent the guest from subsequently booting correctly.
Afterwards, confirm the full functionality of the VM before deleting the original VM or migrating active services.
Installation
Шаг 1. Конвертируем образ диска
Сперва я столкнулся с проблемой, что образ отказывается запускаться при конвертации его средствами qemu-img .
Получал ошибку следующего вида:
Поэтому было решено использовать бесплатный конвертер StarWind V2V Converter.
Step 4
Observe the conversion progress. A successful conversion output looks similar to the following:
Как преобразовать образ виртуальной машины VirtualBox в формат, совместимый с KVM?¶
Для конвертирования образов воспользуемся штатной утилитой qemu-img:
В случае необходимости создания образа фиксированного размера, добавим параметр -o preallocation=full :
merge the vmware disk images…
If you use split disk images on vmware ( or vmware player ) migrate them to a single disk images with the vmware-vdiskmanager command.
Step 1
Install the virt-v2v and virtio-win packages and their dependencies on the host system:
Как преобразовать образ виртуальной машины VMWare в формат, совместимый с KVM?¶
Вариант 1. Воспользуемся утилитой virt-v2v:
Вариант 2. Воспользуемся утилитой qemu-img:
Указываем путь для сохранения образа
Читайте также: