diff --git a/docs/ADMIN_GUIDE.md b/docs/ADMIN_GUIDE.md
index 9f7b55a4d3..7c72f81302 100644
--- a/docs/ADMIN_GUIDE.md
+++ b/docs/ADMIN_GUIDE.md
@@ -62,7 +62,29 @@ The `.spec.settings.dvcr.storage` block configures a persistent volume for stori
- `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName`: StorageClass name (for example, `sds-replicated-thin-r1`).
{{< alert level="warning" >}}
-The storage serving this storage class (`.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName`) must be accessible on the nodes where DVCR is running (system nodes, or worker nodes if there are no system nodes).
+Migrating images when changing the `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName` parameter value is not supported.
+
+When you change the DVCR StorageClass, all images stored in DVCR will be lost.
+{{< /alert >}}
+
+To change the DVCR StorageClass, perform the following steps:
+
+1. Change the value of the [`.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName`](/modules/virtualization/configuration.html#parameters-dvcr-storage-persistentvolumeclaim-storageclassname) parameter.
+
+1. Delete the old PVC for DVCR using the following command:
+
+ ```shell
+ d8 k -n d8-virtualization delete pvc -l app=dvcr
+ ```
+
+1. Restart DVCR by running the following command:
+
+ ```shell
+ d8 k -n d8-virtualization rollout restart deployment dvcr
+ ```
+
+{{< alert level="warning" >}}
+The storage that serves the `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName` StorageClass must be accessible from the nodes where DVCR runs (system nodes, or worker nodes if there are no system nodes).
{{< /alert >}}
**Network settings**
@@ -82,7 +104,7 @@ spec:
The first and the last subnet address are reserved and not available for use.
-{{< alert level="warning">}}
+{{< alert level="warning" >}}
The subnets in the `.spec.settings.virtualMachineCIDRs` block must not overlap with cluster node subnets, services subnet, or pods subnet (`podCIDR`).
It is forbidden to delete subnets if addresses from them have already been issued to virtual machines.
@@ -134,18 +156,18 @@ Where:
**Security Event Audit**
-{{< alert level="warning">}}
+{{< alert level="warning" >}}
Not available in CE edition.
-{{{< /alert >}}
+{{< /alert >}}
-{{{< alert level="warning">}}
+{{< alert level="warning" >}}
To set up auditing, the following modules must be enabled:
- `log-shipper`,
- `runtime-audit-engine`.
-{{{< /alert >}}
+{{< /alert >}}
-To enable security event auditing, set the module’s `.spec.settings.audit.enabled` parameter to` true`:
+To enable security event auditing, set the module’s `.spec.settings.audit.enabled` parameter to `true`:
```yaml
spec:
@@ -417,15 +439,63 @@ How to perform the operation in the web interface:
- Click the "Create" button.
- Wait until the image changes to `Ready` status.
+### Cleaning up image storage
+
+Over time, the creation and deletion of ClusterVirtualImage, VirtualImage, and VirtualDisk resources leads to the accumulation
+of outdated images in the intra-cluster storage. Scheduled garbage collection is implemented to keep the storage up to
+date, but this feature is disabled by default.
+
+```yaml
+apiVersion: deckhouse.io/v1alpha1
+kind: ModuleConfig
+metadata:
+ name: virtualization
+spec:
+ # ...
+ settings:
+ dvcr:
+ gc:
+ schedule: "0 20 * * *"
+ # ...
+```
+
+While garbage collection is running, the storage is switched to read-only mode, and all resources created during this time will wait for the cleanup to finish.
+
+To check for outdated images in the storage, you can run the following command:
+
+```bash
+d8 k -n d8-virtualization exec deploy/dvcr -- dvcr-cleaner gc check
+```
+
+It prints information about the storage status and a list of outdated images that can be deleted.
+
+```console
+Found 2 cvi, 5 vi, 1 vd manifests in registry
+Found 1 cvi, 5 vi, 11 vd resources in cluster
+ Total Used Avail Use%
+36.3GiB 13.1GiB 22.4GiB 39%
+Images eligible for cleanup:
+KIND NAMESPACE NAME
+ClusterVirtualImage debian-12
+VirtualDisk default debian-10-root
+VirtualImage default ubuntu-2204
+```
+
## Virtual machine classes
The VirtualMachineClass resource is designed for centralized configuration of preferred virtual machine settings. It allows you to define CPU instructions, configuration policies for CPU and memory resources for virtual machines, as well as define ratios of these resources. In addition, VirtualMachineClass provides management of virtual machine placement across platform nodes. This allows administrators to effectively manage virtualization platform resources and optimally place virtual machines on platform nodes.
During installation, a single VirtualMachineClass `generic` resource is automatically created. It represents a universal CPU type based on the older, but widely supported, Nehalem architecture. This enables running VMs on any nodes in the cluster and allows live migration.
+
+The administrator can modify the parameters of the `generic` VirtualMachineClass resource (except for the `.spec.cpu` section) or delete this resource.
+
{{< alert level="info" >}}
-It is recommended that you create at least one VirtualMachineClass resource in the cluster with the `Discovery` type immediately after all nodes are configured and added to the cluster. This allows virtual machines to utilize a generic CPU with the highest possible CPU performance considering the CPUs on the cluster nodes. This allows the virtual machines to utilize the maximum CPU capabilities and migrate seamlessly between cluster nodes if necessary.
-For a configuration example, see [vCPU Discovery configuration example](#vcpu-discovery-configuration-example)
+It is not recommended to use the `generic` VirtualMachineClass for running workloads in production environments, since this class corresponds to a CPU with the smallest feature set.
+
+After all nodes are configured and added to the cluster, it is recommended to create at least one VirtualMachineClass resource of the `Discovery` type. This ensures that the best available CPU configuration compatible with all CPUs in your cluster is selected, allows virtual machines to make full use of CPU capabilities, and enables seamless migration between nodes.
+
+For a configuration example, see [vCPU Discovery configuration example](#vcpu-discovery-configuration-example).
{{< /alert >}}
To list all VirtualMachineClass resources, run the following command:
@@ -529,7 +599,7 @@ Next, let's take a closer look at the setting blocks.
The `.spec.cpu` block allows you to specify or configure the vCPU for the VM.
-{{< alert level="warning">}}
+{{< alert level="warning" >}}
Settings in the `.spec.cpu` block cannot be changed after the VirtualMachineClass resource is created.
{{< /alert >}}
@@ -704,7 +774,7 @@ Invalid option (overlapping values):
max: 8
```
-{{< alert level = "warning" >}}
+{{< alert level="warning" >}}
Rule: Each new range must start with a value that immediately follows the max of the previous range.
{{< /alert >}}
@@ -717,7 +787,7 @@ Additional requirements can be specified for each range of cores:
2. Allowed fractions of cores (`coreFractions`) — a list of allowed values (for example, [25, 50, 100] for 25%, 50%, or 100% core usage).
-{{< alert level = "warning" >}}
+{{< alert level="warning" >}}
Important: For each range of cores, be sure to specify:
- Either memory (or `memoryPerCore`),
diff --git a/docs/ADMIN_GUIDE.ru.md b/docs/ADMIN_GUIDE.ru.md
index c75dd09ffa..27bad49ee9 100644
--- a/docs/ADMIN_GUIDE.ru.md
+++ b/docs/ADMIN_GUIDE.ru.md
@@ -62,7 +62,29 @@ spec:
- `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName` — класс хранения (например, `sds-replicated-thin-r1`).
{{< alert level="warning" >}}
-Хранилище, обслуживающее данный класс хранения (`.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName`), должно быть доступно на узлах, где запускается DVCR (system-узлы, либо worker-узлы, при отсутствии system-узлов).
+Перенос образов при изменении значения параметра `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName` не поддерживается.
+
+При смене StorageClass DVCR все образы, хранящиеся в DVCR, будут утеряны.
+{{< /alert >}}
+
+Для изменения StorageClass DVCR выполните следующие действия:
+
+1. Измените значение [параметра `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName`](/modules/virtualization/configuration.html#parameters-dvcr-storage-persistentvolumeclaim-storageclassname).
+
+1. Удалите старый PVC для DVCR с помощью следующей команды:
+
+ ```shell
+ d8 k -n d8-virtualization delete pvc -l app=dvcr
+ ```
+
+1. Перезапустите DVCR, выполнив следующую команду:
+
+ ```shell
+ d8 k -n d8-virtualization rollout restart deployment dvcr
+ ```
+
+{{< alert level="warning" >}}
+Хранилище, обслуживающее данный класс хранения `.spec.settings.dvcr.storage.persistentVolumeClaim.storageClassName`, должно быть доступно на узлах, где запускается DVCR (system-узлы, либо worker-узлы, при отсутствии system-узлов).
{{< /alert >}}
**Сетевые настройки**
@@ -420,6 +442,48 @@ d8 k describe cvi ubuntu-22-04
- Нажмите кнопку «Создать».
- Дождитесь пока образ перейдет в состояние `Готов`.
+### Очистка хранилища образов
+
+Со временем создание и удаление ресурсов ClusterVirtualImage, VirtualImage, VirtualDisk приводит к накоплению
+неактуальных образов во внутрикластерном хранилище. Для поддержания хранилища в актуальном состоянии предусмотрена сборка мусора по расписанию.
+По умолчанию эта функция отключена. Для включения очистки нужно задать расписание в настройках модуля в ресурсе ModuleConfig/virtualization:
+
+```yaml
+apiVersion: deckhouse.io/v1alpha1
+kind: ModuleConfig
+metadata:
+ name: virtualization
+spec:
+ # ...
+ settings:
+ dvcr:
+ gc:
+ schedule: "0 20 * * *"
+ # ...
+```
+
+На время работы сборки мусора хранилище переводится в режим «только чтение». Все создаваемые в это время ресурсы будут ожидать окончания очистки.
+
+Для проверки наличия неактуальных образов в хранилище можно выполнить такую команду:
+
+```bash
+d8 k -n d8-virtualization exec deploy/dvcr -- dvcr-cleaner gc check
+```
+
+На экран будут выведены сведения о состоянии хранилища и список неактуальных образов, которые могут быть удалены.
+
+```console
+Found 2 cvi, 5 vi, 1 vd manifests in registry
+Found 1 cvi, 5 vi, 11 vd resources in cluster
+ Total Used Avail Use%
+36.3GiB 13.1GiB 22.4GiB 39%
+Images eligible for cleanup:
+KIND NAMESPACE NAME
+ClusterVirtualImage debian-12
+VirtualDisk default debian-10-root
+VirtualImage default ubuntu-2204
+```
+
## Классы виртуальных машин
Ресурс VirtualMachineClass предназначен для централизованной конфигурации предпочтительных параметров виртуальных машин.
@@ -429,11 +493,15 @@ d8 k describe cvi ubuntu-22-04
Во время установки автоматически создаётся ресурс VirtualMachineClass с именем `generic`. Он представляет собой универсальный тип процессора на основе более старой, но широко поддерживаемой архитектуры Nehalem. Это позволяет запускать виртуальные машины на любых узлах кластера и поддерживает их живую миграцию.
+Администратор может изменять параметры ресурса VirtualMachineClass `generic` (за исключением секции `.spec.cpu`), либо удалить данный ресурс.
+
{{< alert level="info" >}}
-Рекомендуется создать как минимум один ресурс VirtualMachineClass в кластере с типом `Discovery` сразу после того, как все узлы будут настроены и добавлены в кластер.
-Это позволит использовать в виртуальных машинах универсальный процессор с максимально возможными характеристиками с учетом CPU на узлах кластера, что позволит виртуальным машинам использовать максимум возможностей CPU и при необходимости беспрепятственно осуществлять миграцию между узлами кластера.
-Пример настройки смотрите в разделе [Пример конфигурации vCPU Discovery](#пример-конфигурации-vcpu-discovery)
+Не рекомендуется использовать VirtualMachineClass `generic` для запуска рабочих нагрузок в production-средах, поскольку данный класс соответствует процессору с наименьшей функциональностью.
+
+Рекомендуется после добавления и настройки всех узлов в кластере создать хотя бы один ресурс VirtualMachineClass с типом `Discovery`. Это обеспечит выбор наилучшей доступной конфигурации процессора с учётом всех CPU в вашем кластере, позволит виртуальным машинам максимально эффективно использовать возможности процессоров и обеспечит беспрепятственную миграцию между узлами.
+
+Пример настройки смотрите в разделе [Пример конфигурации vCPU Discovery](#пример-конфигурации-vcpu-discovery).
{{< /alert >}}
Чтобы вывести список ресурсов VirtualMachineClass, выполните следующую команду:
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index d8629328d3..34992c317c 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -16,92 +16,23 @@ The module supports the following configuration:
- Maximum number of nodes: `1000`.
- Maximum number of virtual machines: `50000`.
-The module has no additional restrictions and is compatible with any hardware that is supported by [operating systems](#supported-os-for-platform-nodes) on which it can be installed.
-
-## Hardware requirements
-
-1. A dedicated **machine for installation**.
-
- This machine will run the Deckhouse installer. For example, it can be an administrator's laptop or any other computer that is not intended to be added to the cluster. Requirements for this machine:
-
- - OS: Windows 10+, macOS 10.15+, Linux (Ubuntu 18.04+, Fedora 35+).
- - Installed Docker Engine or Docker Desktop (instructions for [Ubuntu](https://docs.docker.com/engine/install/ubuntu/), [macOS](https://docs.docker.com/desktop/mac/install/), [Windows](https://docs.docker.com/desktop/windows/install/)).
- - HTTPS access to the container image registry at `registry.deckhouse.io`.
- - SSH-key-based access to the node that will serve as the **master node** of the future cluster.
- - SSH-key-based access to the node that will serve as the **worker node** of the future cluster (if the cluster will consist of more than one master node).
-
-1. **Server for the master node**
-
- There can be multiple servers running the cluster’s control plane components, but only one server is required for installation. The others can be added later via node management mechanisms.
-
- Requirements for a physical bare-metal server:
-
- - Resources:
- - CPU:
- - x86-64 architecture.
- - Support for Intel-VT (VMX) or AMD-V (SVM) instructions.
- - At least 4 cores.
- - RAM: At least 8 GB.
- - Disk space:
- - At least 60 GB.
- - High-speed disk (400+ IOPS).
- - OS [from the list of supported ones](#supported-os-for-platform-nodes):
- - Linux kernel version `5.7` or newer.
- - **Unique hostname** across all servers in the future cluster.
- - Network access:
- - HTTPS access to the container image registry at `registry.deckhouse.io`.
- - Access to the package repositories of the chosen OS.
- - SSH key-based access from the **installation machine** (see item 1).
- - Network access from the **installation machine** (see item 1) on port `22322/TCP`.
- - Required software:
- - The `cloud-utils` and `cloud-init` packages must be installed (package names may vary depending on the chosen OS).
-
- > The container runtime will be installed automatically, so there's no need to install any `containerd` or `docker` packages.
-
-1. **Servers for worker nodes**
-
- These nodes will run virtual machines, so the servers must have enough resources to handle the planned number of VMs. Additional disks may be required if you deploy a software-defined storage solution.
-
- Requirements for a physical bare-metal server:
-
- - Resources:
- - CPU:
- - x86-64 architecture.
- - Support for Intel-VT (VMX) or AMD-V (SVM) instructions.
- - At least 4 cores.
- - RAM: At least 8 GB.
- - Disk space:
- - At least 60 GB.
- - High-speed disk (400+ IOPS).
- - Additional disks for software-defined storage.
- - OS [from the list of supported ones](#supported-os-for-platform-nodes):
- - Linux kernel version `5.7` or newer;
- - **Unique hostname** across all servers in the future cluster.
- - Network access:
- - HTTPS access to the container image registry at `registry.deckhouse.io`.
- - Access to the package repositories of the chosen OS.
- - SSH key-based access from the **installation machine** (see item 1).
- - Required software:
- - The `cloud-utils` and `cloud-init` packages must be installed (package names may vary depending on the chosen OS).
-
- > The container runtime will be installed automatically, so there's no need to install any `containerd` or `docker` packages.
-
-1. **Storage hardware**
-
- Depending on the chosen storage solution, additional resources may be required. For details, refer to [Storage Management](/products/virtualization-platform/documentation/admin/platform-management/storage/sds/lvm-local.html).
-
-## Supported OS for platform nodes
-
-| Linux distribution | Supported versions |
-| ------------------ | ------------------- |
-| CentOS | 7, 8, 9 |
-| Debian | 10, 11, 12 |
-| Ubuntu | 20.04, 22.04, 24.04 |
-
-{{< alert level="warning">}}
-Ensuring stable operation of live migration mechanisms requires the use of an identical version of the Linux kernel on all cluster nodes.
-
-This is because differences in kernel versions can lead to incompatible interfaces, system calls, and resource handling, which can disrupt the virtual machine migration process.
+The module has no additional restrictions and is compatible with any hardware supported by the operating systems on which it can be installed.
+
+## Hardware and software requirements
+
+Hardware requirements for the virtualization module match the requirements for the [Deckhouse Kubernetes Platform](/products/kubernetes-platform/guides/production.html#resource-requirements), with an additional requirement: CPU virtualization support on the hosts where virtual machines will be launched.
+
+### Additional requirements for virtualization support
+
+On all cluster nodes where virtual machines are planned to be launched, hardware virtualization support must be provided:
+
+- CPU: Support for Intel-VT (VMX) or AMD-V (SVM) instructions.
+- BIOS/UEFI: Hardware virtualization support enabled in the BIOS/UEFI settings.
+
+{{< alert level="warning" >}}
+Ensuring the stable operation of live migration mechanisms requires using the same Linux kernel version on all cluster nodes.
+
+Differences between kernel versions can lead to incompatible interfaces, system calls, and resource handling, which can disrupt the virtual machine migration process.
{{< /alert >}}
## Supported guest operating systems
@@ -126,7 +57,7 @@ For Windows family operating systems, the platform supports initialization with
## Supported storage systems
-Virtual machines use `PersistentVolume` resources. To manage these resources and allocate disk space within the cluster, one or more supported storage systems must be installed:
+Virtual machine disks are created using PersistentVolume resources. To manage these resources and allocate disk space in the cluster, one or more supported storage systems must be deployed:
| Storage System | Disk Location |
| ------------------------- | ------------------------- |
@@ -207,27 +138,38 @@ Virtual machines use `PersistentVolume` resources. To manage these resources and
The distribution of components across cluster nodes depends on the cluster's configuration. For example, a cluster may consist of:
-- only master nodes, for running the control plane and workload components;
-- only master nodes and worker nodes;
-- master nodes, system nodes, and worker nodes;
-- other combinations (depending on the architecture).
-
-The table lists the management plane components and the node types for their placement. Components are distributed by priority only if the corresponding nodes are available in the cluster configuration.
-
-| Name | Node group for running components | Comment |
-| ----------------------------- | --------------------------------- | -------------------------------------------- |
-| `cdi-operator-*` | system/worker | |
-| `cdi-apiserver-*` | master | |
-| `cdi-deployment-*` | system/worker | |
-| `virt-api-*` | master | |
-| `virt-controller-*` | system/worker | |
-| `virt-operator-*` | system/worker | |
-| `virtualization-api-*` | master | |
-| `virtualization-controller-*` | master | |
-| `virtualization-audit-*` | system/worker | |
-| `dvcr-*` | system/worker | Storage must be available on the node |
-| `virt-handler-*` | All cluster nodes | |
-| `vm-route-forge-*` | All cluster nodes | |
+- Only master nodes, for running the control plane and workload components.
+- Only master nodes and worker nodes.
+- Master nodes, system nodes, and worker nodes.
+- Other combinations (depending on the architecture).
+
+{{< alert level="warning" >}}
+In this context, worker nodes are nodes that do not have taints preventing regular workloads (pods, virtual machines) from running.
+{{< /alert >}}
+
+The table lists the main components of the virtualization control plane and the nodes where they can be placed. Components are scheduled by priority: if a suitable node type is available in the cluster, the component will be placed on it.
+
+| Component name | Node group | Comment |
+|-------------------------------|-------------------|---------------------------------------|
+| `cdi-operator-*` | system/worker | |
+| `cdi-apiserver-*` | master | |
+| `cdi-deployment-*` | system/worker | |
+| `virt-api-*` | master | |
+| `virt-controller-*` | system/worker | |
+| `virt-operator-*` | system/worker | |
+| `virtualization-api-*` | master | |
+| `virtualization-controller-*` | master | |
+| `virtualization-audit-*` | system/worker | |
+| `dvcr-*` | system/worker | Storage must be available on the node |
+| `virt-handler-*` | All cluster nodes | |
+| `vm-route-forge-*` | All cluster nodes | |
+
+Components used to create and import virtual machine images or disks (they run only for the duration of the creation or import operation):
+
+| Component name | Node group | Comment |
+|----------------|---------------|---------|
+| `importer-*` | system/worker | |
+| `uploader-*` | system/worker | |
## Module update
diff --git a/docs/INSTALL.ru.md b/docs/INSTALL.ru.md
index e7b0ad5bc2..8f1ef929bd 100644
--- a/docs/INSTALL.ru.md
+++ b/docs/INSTALL.ru.md
@@ -16,91 +16,18 @@ weight: 15
- максимальное количество узлов: `1000`;
- максимальное количество виртуальных машин: `50000`.
-Модуль не имеет дополнительных ограничений и совместим с любым оборудованием, которое поддерживается [операционными системами](#поддерживаемые-ос-для-узлов-платформы), на которые он может быть установлен.
-
-## Требования к аппаратному обеспечению
-
-1. Отдельная **машина для установки**.
-
- Здесь будет запускаться установщик Deckhouse. Это может быть ноутбук администратора или любой другой компьютер, который **не планируется** добавлять в кластер. Требования к этой машине:
-
- - ОС: Windows 10+, macOS 10.15+, Linux (Ubuntu 18.04+, Fedora 35+);
- - установленный Docker Engine или Docker Desktop (инструкции [для Ubuntu](https://docs.docker.com/engine/install/ubuntu/), [macOS](https://docs.docker.com/desktop/mac/install/), [Windows](https://docs.docker.com/desktop/windows/install/));
- - HTTPS-доступ к хранилищу образов контейнеров `registry.deckhouse.ru`;
- - SSH-доступ по ключу к узлу, который будет **master-узлом** будущего кластера;
- - SSH-доступ по ключу к узлу, который будет **worker-узлом** будущего кластера (если кластер будет состоять не из одного master-узла).
-
-1. **Сервер для master-узла**.
-
- Серверов для запуска управляющих компонентов кластера может быть несколько. Для установки достаточно одного сервера, а остальные нужно будет добавить через механизмы управления узлами.
-
- Требования к физическому bare-metal-серверу:
-
- - Ресурсы:
- - процессор:
- - архитектура x86-64;
- - поддержка инструкций Intel-VT (VMX) или AMD-V (SVM);
- - не менее 4 ядер;
- - ОЗУ не менее 8 ГБ;
- - дисковое пространство:
- - не менее 60 ГБ;
- - быстрый диск (400+ IOPS);
- - ОС [из списка поддерживаемых](#поддерживаемые-ос-для-узлов-платформы):
- - ядро Linux версии `5.7` или новее;
- - **Уникальный hostname** среди всех серверов будущего кластера;
- - Сетевые доступы:
- - HTTPS-доступ к хранилищу образов контейнеров `registry.deckhouse.ru`;
- - доступ к репозиториям пакетов используемой ОС;
- - SSH-доступ от **машины для установки** (см. п.1) по ключу;
- - сетевой доступ от **машины для установки** (см. п.1) по порту `22322/TCP`;
- - Требуемое ПО:
- - пакеты `cloud-utils` и `cloud-init` должны быть установлены.
-
- > Container runtime будет установлен автоматически, поэтому пакеты `containerd` и/или `docker` устанавливать не нужно.
-
-1. **Серверы для worker-узлов**.
-
- Это узлы, где будут запускаться виртуальные машины, поэтому ресурсов на этих серверах должно хватать для запуска планируемого количества виртуальных машин. При использовании программно-определяемого хранилища могут потребоваться дополнительные диски.
-
- Требования к физическому bare metal-серверу:
-
- - Ресурсы:
- - процессор:
- - архитектура x86-64;
- - поддержка инструкций Intel-VT (VMX) или AMD-V (SVM);
- - не менее 4 ядер;
- - ОЗУ не менее 8 ГБ;
- - дисковое пространство:
- - не менее 60 ГБ;
- - быстрый диск (400+ IOPS);
- - дополнительные диски для программно-определяемого хранилища;
- - ОС [из списка поддерживаемых](#поддерживаемые-ос-для-узлов-платформы):
- - ядро Linux версии `5.7` или новее;
- - **Уникальный hostname** среди всех серверов будущего кластера;
- - Сетевые доступы:
- - HTTPS-доступ к хранилищу образов контейнеров `registry.deckhouse.ru`;
- - доступ к репозиториям пакетов используемой ОС;
- - SSH-доступ от **машины для установки** (см. п.1) по ключу;
- - Требуемое ПО:
- - пакеты `cloud-utils` и `cloud-init` должны быть установлены (названия могут отличаться в зависимости от выбранной ОС).
-
- > Container runtime будет установлен автоматически, поэтому пакеты `containerd` и/или `docker` устанавливать не нужно.
-
-1. **Оборудование для хранилища**.
-
- В зависимости от выбранного хранилища могут потребоваться дополнительные ресурсы. Подробности смотрите в разделе [Управление хранилищами](/products/virtualization-platform/documentation/admin/platform-management/storage/sds/lvm-local.html).
-
-## Поддерживаемые ОС для узлов платформы
-
-| Дистрибутив Linux | Поддерживаемые версии |
-| --------------------------- | ------------------------------- |
-| РЕД ОС | 7.3, 8.0 |
-| РОСА Сервер | 7.9, 12.4, 12.5.1 |
-| ALT Linux | p10, 10.0, 10.1, 10.2, 11 |
-| Astra Linux Special Edition | 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.8 |
-| CentOS | 7, 8, 9 |
-| Debian | 10, 11, 12 |
-| Ubuntu | 18.04, 20.04, 22.04, 24.04 |
+Модуль не накладывает дополнительных ограничений и совместим с любым оборудованием, поддерживаемым операционными системами, на которые он может быть установлен.
+
+## Требования к программному и аппаратному обеспечению
+
+Требования к аппаратному обеспечению для модуля виртуализации совпадают с требованиями, предъявляемыми к [Deckhouse Kubernetes Platform](/products/kubernetes-platform/guides/production.html#требования-к-ресурсам), с дополнительным требованием поддержки виртуализации CPU на хостах, где будут запускаться виртуальные машины.
+
+### Дополнительные требования для поддержки виртуализации
+
+На всех узлах кластера, где планируется запуск виртуальных машин, необходимо обеспечить поддержку аппаратной виртуализации:
+
+- Процессор: поддержка инструкций Intel-VT (VMX) или AMD-V (SVM);
+- BIOS/UEFI: включена поддержка аппаратной виртуализации в настройках BIOS/UEFI.
{{< alert level="warning" >}}
Обеспечение стабильной работы механизмов живой миграции требует использования идентичной версии ядра Linux на всех узлах кластера.
@@ -130,7 +57,7 @@ weight: 15
## Поддерживаемые хранилища
-Виртуальные машины используют ресурсы `PersistentVolume`. Для управления этими ресурсами и выделения дискового пространства в кластере должно быть установлено одно или несколько поддерживаемых хранилищ:
+Диски виртуальных машин создаются на основе ресурсов PersistentVolume. Для управления этими ресурсами и выделения дискового пространства в кластере должно быть развернуто одно или несколько поддерживаемых хранилищ:
| Хранилище | Расположение дисков |
| ------------------------- | ------------------------- |
@@ -216,22 +143,33 @@ weight: 15
- master-узлы, system-узлы и worker-узлы;
- другие комбинации (в зависимости от архитектуры).
-В таблице указаны компоненты плоскости управления и типы узлов для их размещения. Компоненты распределяются по приоритету, только если соответствующие узлы доступны в конфигурации кластера.
-
-| Название | Группа узлов для запуска компонент | Комментарий |
-| ----------------------------- | ---------------------------------- | --------------------------------------- |
-| `cdi-operator-*` | system/worker | |
-| `cdi-apiserver-*` | master | |
-| `cdi-deployment-*` | system/worker | |
-| `virt-api-*` | master | |
-| `virt-controller-*` | system/worker | |
-| `virt-operator-*` | system/worker | |
-| `virtualization-api-*` | master | |
-| `virtualization-controller-*` | master | |
-| `virtualization-audit-*` | system/worker | |
-| `dvcr-*` | system/worker | На узле должно быть доступно хранилище |
-| `virt-handler-*` | Все узлы кластера | |
-| `vm-route-forge-*` | Все узлы кластера | |
+{{< alert level="warning" >}}
+Под worker-узлами понимаются узлы, на которых нет ограничений (taints), мешающих запуску обычной рабочей нагрузки (подов, виртуальных машин).
+{{< /alert >}}
+
+В таблице приведены основные компоненты control plane виртуализации и узлы, на которых они могут быть размещены. Компоненты распределяются по приоритету — если в кластере есть подходящий тип узлов, компонент будет размещён на нём.
+
+| Название компонента | Группа узлов | Комментарий |
+|-------------------------------|-------------------|----------------------------------------|
+| `cdi-operator-*` | system/worker | |
+| `cdi-apiserver-*` | master | |
+| `cdi-deployment-*` | system/worker | |
+| `virt-api-*` | master | |
+| `virt-controller-*` | system/worker | |
+| `virt-operator-*` | system/worker | |
+| `virtualization-api-*` | master | |
+| `virtualization-controller-*` | master | |
+| `virtualization-audit-*` | system/worker | |
+| `dvcr-*` | system/worker | На узле должно быть доступно хранилище |
+| `virt-handler-*` | Все узлы кластера | |
+| `vm-route-forge-*` | Все узлы кластера | |
+
+Компоненты для создания и загрузки (импорта) образов или дисков виртуальных машин (они запускаются только на время создания или загрузки):
+
+| Название компонента | Группа узлов | Комментарий |
+|---------------------|---------------|-------------|
+| `importer-*` | system/worker | |
+| `uploader-*` | system/worker | |
## Обновление модуля
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 393cd0e473..0c56b522d0 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -6,7 +6,7 @@ weight: 50
## Introduction
-This guide is intended for users of Deckhouse Virtualization Platform (DVP) and describes how to create and modify resources that are available for creation in projects and cluster namespaces.
+This guide is intended for users of the `virtualization` module in the Deckhouse ecosystem and describes the procedure for creating and modifying resources that are available for creation in cluster projects and namespaces.
## Quick start on creating a VM
@@ -234,7 +234,7 @@ When connected to a virtual machine, the image is accessed in read-only mode.
The image creation process includes the following steps:
- The user creates a `VirtualImage` resource.
-- After creation, the image is automatically loaded from the specified source into the storage (DVCR).
+- After creation, the image is automatically downloaded from the source specified in the specification to DVCR or PVC storage, depending on the type.
- Once the download is complete, the resource becomes available for disk creation.
There are different types of images:
@@ -244,6 +244,7 @@ There are different types of images:
Examples of resources for obtaining virtual machine images:
+
| Distribution | Default user. |
| --------------------------------------------------------------------------------- | ------------------------- |
| [AlmaLinux](https://almalinux.org/get-almalinux/#Cloud_Images) | `almalinux` |
@@ -605,7 +606,7 @@ EOF
## Disks
-Disks in virtual machines are necessary for writing and storing data, ensuring that applications and operating systems can fully function. DVP provides the storage for these disks.
+Virtual machine disks are used to write and store data required for operating systems and applications to run. Various types of storage can be used for this purpose.
Depending on the storage properties, the behavior of disks during creation of virtual machines during operation may differ:
@@ -622,7 +623,7 @@ VolumeBindingMode property:
AccessMode:
- `ReadWriteMany (RWX)`: Multiple disk access. Live migration of virtual machines with such disks is possible.
-- `ReadWriteOnce (RWO)`: Only one instance of the virtual machine can access the disk. Live migration of virtual machines with such disks is supported only in DVP commercial editions. Live migration is only available if all disks are connected statically via (`.spec.blockDeviceRefs`). Disks connected dynamically via `VirtualMachineBlockDeviceAttachments` must be reattached statically by specifying them in `.spec.blockDeviceRefs`.
+- `ReadWriteOnce (RWO)`: The disk can be accessed by only a single virtual machine instance. Live migration of virtual machines that use such disks is supported only in commercial editions. Live migration is available only if all disks are attached statically via `.spec.blockDeviceRefs`. Disks attached dynamically via VirtualMachineBlockDeviceAttachments must be reattached statically by specifying them in `.spec.blockDeviceRefs`.
When creating a disk, the controller will independently determine the most optimal parameters supported by the storage.
@@ -649,7 +650,7 @@ nfs-4-1-wffc nfs.csi.k8s.io Delet
A full description of the disk configuration settings can be found at [link](cr.html#virtualdisk).
-How to find out the available storage options in the DVP web interface:
+How to find out the available storage options in the web interface:
- Go to the "System" tab, then to the "Storage" section → "Storage Classes".
@@ -676,17 +677,18 @@ EOF
After creation, the `VirtualDisk` resource can be in the following states (phases):
-- `Pending` - waiting for all dependent resources required for disk creation to be ready.
-- `Provisioning` - disk creation process is in progress.
-- `Resizing` - the process of resizing the disk is in progress.
-- `WaitForFirstConsumer` - the disk is waiting for the virtual machine that will use it to be created.
-- `WaitForUserUpload` - the disk is waiting for the user to upload an image (type: Upload).
-- `Ready` - the disk has been created and is ready for use.
-- `Failed` - an error occurred during the creation process.
-- `PVCLost` - system error, PVC with data has been lost.
-- `Terminating` - the disk is being deleted. The disk may "hang" in this state if it is still connected to the virtual machine.
+- `Pending`: Waiting for all dependent resources required for disk creation to be ready.
+- `Provisioning`: Disk creation process is in progress.
+- `Resizing`: Process of resizing the disk is in progress.
+- `WaitForFirstConsumer`: Disk is waiting for the virtual machine that will use it to be created.
+- `WaitForUserUpload`: Disk is waiting for the user to upload an image (type: Upload).
+- `Ready`: Disk has been created and is ready for use.
+- `Migrating`: Live migration of a disk.
+- `Failed`: An error occurred during the creation process.
+- `PVCLost`: System error, PVC with data has been lost.
+- `Terminating`: Disk is being deleted. The disk may "hang" in this state if it is still connected to the virtual machine.
-As long as the disk has not entered the `Ready` phase, the contents of the entire `.spec` block can be changed. If changes are made, the disk creation process will start over.
+As long as the disk has not reached the `Ready` phase, you can modify any fields in the `.spec` block. When changes are made, the disk creation process is restarted.
If the `.spec.persistentVolumeClaim.storageClassName` parameter is not specified, the default `StorageClass` at the cluster level will be used, or for images if specified in [module settings](./admin_guide.html#storage-class-settings-for-disks).
@@ -810,6 +812,58 @@ How to create a disk from an image in the web interface (this step can be skippe
- Click the "Create" button.
- The disk status is displayed at the top left, under the disk name.
+### Upload a disk from the command line
+
+To upload a disk from the command line, first create the VirtualDisk resource as shown in the following example:
+
+```yaml
+d8 k apply -f - <",
+ "inCluster": "http://10.222.165.239/upload"
+}
+```
+
+Upload the disk using the following command:
+
+```bash
+curl https://virtualization.example.com/upload/ --progress-bar -T | cat
+```
+
+After the upload completes, the disk should be created and enter the `Ready` phase:
+
+```bash
+d8 k get vd uploaded-disk
+```
+
+Example output:
+
+```txt
+NAMESPACE NAME PHASE CAPACITY AGE
+default uploaded-disk Ready 3Gi 7d23h
+```
+
### Change disk size
You can increase the size of disks even if they are already attached to a running virtual machine. To do this, edit the `spec.persistentVolumeClaim.size` field:
@@ -831,6 +885,10 @@ Let's apply the changes:
```bash
d8 k patch vd linux-vm-root --type merge -p '{"spec":{"persistentVolumeClaim":{"size":"11Gi"}}}'
+
+# Alternatively, apply the changes by editing the resource.
+
+d8 k edit vd linux-vm-root
```
Let's check the size after the change:
@@ -866,46 +924,53 @@ Method #2:
- Click on the "Save" button that appears.
- The disk status is displayed at the top left, under its name.
-### Changing the disk StorageClass
+### Migrating disks to other storage
-In the DVP commercial editions, it is possible to change the StorageClass for existing disks. Currently, this is only supported for running VMs (`Phase` should be `Running`).
+In commercial editions, you can migrate (move) a virtual machine disk to another storage by changing its StorageClass.
{{< alert level="warning">}}
-Storage class migration is only available for disks connected statically via `.spec.blockDeviceRefs`.
+Limitations of disk migration between storage:
-To migrate the storage class of disks attached via `VirtualMachineBlockDeviceAttachments`, they must be reattached statically by specifying disks names in `.spec.blockDeviceRefs`.
+- Migration is only available for virtual machines in the `Running` state.
+- Migration is only supported between disks of the same type: `Block` ↔ `Block`, `FileSystem` ↔ `FileSystem`; conversion between different types is not possible.
+- Migration is only supported for disks attached statically via the `.spec.blockDeviceRefs` parameter in the virtual machine specification.
+- If a disk was attached via the VirtualMachineBlockDeviceAttachments resource, it must be temporarily reattached directly for migration by specifying the disk name in `.spec.blockDeviceRefs`.
{{< /alert >}}
-Example:
+Example of migrating a disk to the `new-storage-class-name` StorageClass:
```bash
d8 k patch vd disk --type=merge --patch '{"spec":{"persistentVolumeClaim":{"storageClassName":"new-storage-class-name"}}}'
+
+# Alternatively, apply the changes by editing the resource.
+
+d8 k edit vd disk
```
-After the disk configuration is updated, a live migration of the VM is triggered, during which the disk is migrated to the new storage.
+After the disk configuration is updated, a live migration of the VM is triggered, during which the VM disk is moved to the new storage.
-If a VM has multiple disks attached and you need to change the storage class for several of them, this operation must be performed sequentially:
+If a VM has multiple disks attached, and you need to change the storage class for several of them, this operation must be performed sequentially:
```bash
d8 k patch vd disk1 --type=merge --patch '{"spec":{"persistentVolumeClaim":{"storageClassName":"new-storage-class-name"}}}'
d8 k patch vd disk2 --type=merge --patch '{"spec":{"persistentVolumeClaim":{"storageClassName":"new-storage-class-name"}}}'
```
-If migration fails, repeated attempts are made with increasing delays (exponential backoff algorithm). The maximum delay is 300 seconds (5 minutes). Delays: 5 seconds (1st attempt), 10 seconds (2nd), then each delay doubles, reaching 300 seconds (7th and subsequent attempts). The first attempt is performed without delay.
+If migration fails, retry attempts are performed with increasing delays (exponential backoff algorithm). The maximum delay is 300 seconds (5 minutes). Delays are: 5 seconds (1st attempt), 10 seconds (2nd), then each delay doubles until it reaches 300 seconds (7th and subsequent attempts). The first attempt is performed without delay.
-To cancel migration, the user must return the storage class in the specification to the original one.
+To cancel migration, the StorageClass in the specification must be reverted to its original value.
## Virtual machines
The `VirtualMachine` resource is used to create a virtual machine, its parameters allow you to configure:
-- [virtual machine class](admin_guide.html#virtual-machine-classes)
-- resources required for virtual machine operation (processor, memory, disks and images);
-- rules of virtual machine placement on cluster nodes;
-- bootloader settings and optimal parameters for the guest OS;
-- virtual machine startup policy and policy for applying changes;
-- initial configuration scenarios (cloud-init);
-- list of block devices.
+- [Virtual machine class](admin_guide.html#virtual-machine-classes).
+- Resources required for virtual machine operation (processor, memory, disks and images).
+- Rules of virtual machine placement on cluster nodes.
+- Bootloader settings and optimal parameters for the guest OS.
+- Virtual machine startup policy and policy for applying changes.
+- Initial configuration scenarios (cloud-init).
+- List of block devices.
The full description of virtual machine configuration parameters can be found at [link](cr.html#virtualmachine)
@@ -936,7 +1001,7 @@ spec:
packages:
- nginx
- qemu-guest-agent
- run_cmd:
+ runcmd:
- systemctl daemon-reload
- systemctl enable --now nginx.service
- systemctl enable --now qemu-guest-agent.service
@@ -1002,7 +1067,7 @@ How to create a virtual machine in the web interface:
packages:
- nginx
- qemu-guest-agent
- run_cmd:
+ runcmd:
- systemctl daemon-reload
- systemctl enable --now nginx.service
- systemctl enable --now qemu-guest-agent.service
@@ -1080,7 +1145,7 @@ A virtual machine (VM) goes through several phases in its existence, from creati
The VM is migrated to another node in the cluster (live migration).
- Features:
- - VM migration is supported only for non-local disks, the `type: Migratable` condition displays information about whether the VM can migrate or not.
+ - The `type: Migratable` condition indicates whether the VM can be migrated.
- Possible issues:
- Incompatibility of processor instructions (when using host or host-passthrough processor types).
- Difference in kernel versions on hypervisor nodes.
@@ -1254,6 +1319,143 @@ status:
coresPerSocket: 1
```
+### Initialization scripts
+
+Initialization scripts are used for the initial configuration of a virtual machine when it is started.
+
+The following initialization scripts are supported:
+
+- [Cloud-Init](https://cloudinit.readthedocs.io).
+- [Sysprep](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/sysprep--system-preparation--overview).
+
+#### Cloud-Init
+
+Cloud-Init is a tool for automatically configuring virtual machines on first boot. It allows you to perform a wide range of configuration tasks without manual intervention.
+
+{{< alert level="warning" >}}
+Cloud-Init configuration is written in YAML format and must start with the `#cloud-config` header at the beginning of the configuration block. For information about other possible headers and their purpose, see the [official Cloud-Init documentation](https://cloudinit.readthedocs.io/en/latest/explanation/format.html#headers-and-content-types).
+{{< /alert >}}
+
+The main capabilities of Cloud-Init include:
+
+- Creating users, setting passwords, and adding SSH keys for access.
+- Automatically installing necessary software on first boot.
+- Running arbitrary commands and scripts for system configuration.
+- Automatically starting and enabling system services (for example, [`qemu-guest-agent`](#guest-os-agent)).
+
+##### Typical usage scenarios
+
+1. Adding an SSH key for a [pre-installed user](#image-resources-table) that may already be present in the cloud image (for example, the `ubuntu` user in official Ubuntu images). The name of such a user depends on the image. Check the documentation for your distribution.
+
+ ```yaml
+ #cloud-config
+ ssh_authorized_keys:
+ - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
+ ```
+
+1. Creating a user with a password and SSH key:
+
+ ```yaml
+ #cloud-config
+ users:
+ - name: cloud
+ passwd: "$6$rounds=4096$saltsalt$..."
+ lock_passwd: false
+ sudo: ALL=(ALL) NOPASSWD:ALL
+ shell: /bin/bash
+ ssh-authorized-keys:
+ - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
+ ssh_pwauth: True
+ ```
+
+ To generate a password hash, use the command `mkpasswd --method=SHA-512 --rounds=4096`.
+
+1. Installing packages and services:
+
+ ```yaml
+ #cloud-config
+ package_update: true
+ packages:
+ - nginx
+ - qemu-guest-agent
+ runcmd:
+ - systemctl daemon-reload
+ - systemctl enable --now nginx.service
+ - systemctl enable --now qemu-guest-agent.service
+ ```
+
+##### Using Cloud-Init
+
+The Cloud-Init script can be embedded directly into the virtual machine specification, but its size is limited to a maximum of 2048 bytes:
+
+```yaml
+spec:
+ provisioning:
+ type: UserData
+ userData: |
+ #cloud-config
+ package_update: true
+ ...
+```
+
+For longer scenarios and/or when private data is involved, the script for initial initialization of the virtual machine can be created in a Secret resource. An example of a Secret with a Cloud-Init script is shown below:
+
+```yaml
+apiVersion: v1
+kind: Secret
+metadata:
+ name: cloud-init-example
+data:
+ userData:
+type: provisioning.virtualization.deckhouse.io/cloud-init
+```
+
+A fragment of the virtual machine configuration when using the Cloud-Init initialization script stored in a Secret:
+
+```yaml
+spec:
+ provisioning:
+ type: UserDataRef
+ userDataRef:
+ kind: Secret
+ name: cloud-init-example
+```
+
+{{< alert level="info" >}}
+The value of the `.data.userData` field must be Base64 encoded. To encode it, you can use the `base64 -w 0` command or `echo -n "content" | base64`.
+{{< /alert >}}
+
+#### Sysprep
+
+When configuring virtual machines running Windows using Sysprep, only the Secret-based option is supported.
+
+An example of a Secret with a Sysprep script is shown below:
+
+```yaml
+apiVersion: v1
+kind: Secret
+metadata:
+ name: sysprep-example
+data:
+ unattend.xml:
+type: provisioning.virtualization.deckhouse.io/sysprep
+```
+
+{{< alert level="info" >}}
+The value of the `.data.unattend.xml` field must be Base64 encoded. To encode, you can use the command `base64 -w 0` or `echo -n "content" | base64`.
+{{< /alert >}}
+
+A fragment of the virtual machine configuration using the Sysprep initialization script in a Secret:
+
+```yaml
+spec:
+ provisioning:
+ type: SysprepRef
+ sysprepRef:
+ kind: Secret
+ name: sysprep-example
+```
+
### Guest OS agent
To improve VM management efficiency, it is recommended to install the QEMU Guest Agent, a tool that enables communication between the hypervisor and the operating system inside the VM.
@@ -1317,46 +1519,14 @@ You can automate the installation of the agent for Linux OS using a cloud-init i
package_update: true
packages:
- qemu-guest-agent
- run_cmd:
+ runcmd:
- systemctl enable --now qemu-guest-agent.service
```
-### User Configuration for Cloud Images
+QEMU Guest Agent does not require additional configuration after installation. However, to ensure application-level snapshot consistency (without stopping services), you can add scripts that are executed automatically in the guest OS before and after filesystem `freeze` and `thaw` operations. The scripts must be executable and placed in a special directory, whose path depends on the Linux distribution in use:
-When using cloud images (with cloud-init support), you must specify an SSH key or a password for the pre-installed user, or create a new user with a password or SSH key via cloud-init. Otherwise, it will be impossible to log in to the virtual machine!
-
-Examples:
-
-1. Setting a password for an existing user (for example, `ubuntu` is often present in official cloud images):
-
- In many cloud images, the default user is already predefined (e.g., `ubuntu` in Ubuntu Cloud Images), and its name cannot always be overridden via the `cloud-init` `users` block. In such cases, it is recommended to use dedicated cloud-init parameters for managing the default user.
-
- In a cloud image, you can add a public SSH key for the default user using the `ssh_authorized_keys` parameter at the root level of cloud-init:
-
- ```yaml
- #cloud-config
- ssh_authorized_keys:
- - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
- ```
-
-2. Creating a new user with a password and SSH key:
-
- ```yaml
- #cloud-config
- users:
- - name: cloud
- passwd: "$6$rounds=4096$QktreHgVzeZy70h3$C8c4gjzYMY75.C7IjN1.GgrjMSdeyG79W.hZgsTNnlrJIzuB48qzCui8KP1par.OvCEV3Xi8FzRiqqZ74LOK6."
- lock_passwd: false
- sudo: ALL=(ALL) NOPASSWD:ALL
- shell: /bin/bash
- ssh-authorized-keys:
- - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
- ssh_pwauth: True
- ```
-
-{{< alert level="info" >}}
-The value of the `passwd` field is a hashed password (for example, you can generate it using `mkpasswd --method=SHA-512 --rounds=4096`).
-{{< /alert >}}
+- `/etc/qemu-ga/hooks.d/`: For Debian/Ubuntu-based distributions.
+- `/etc/qemu/fsfreeze-hook.d/`: For RHEL/CentOS/Fedora-based distributions.
### Connecting to a virtual machine
@@ -1522,6 +1692,10 @@ Apply the following patch to the virtual machine to change the number of cores f
```bash
d8 k patch vm linux-vm --type merge -p '{"spec":{"cpu":{"cores":2}}}'
+
+# Alternatively, apply the changes by editing the resource.
+
+d8 k edit vm linux-vm
```
Example output:
@@ -1613,79 +1787,6 @@ How to perform the operation in the web interface:
- Enable the "Auto-apply changes" switch.
- Click on the "Save" button that appears.
-### Initialization scripts
-
-Initialization scripts are intended for the initial configuration of a virtual machine when it is started.
-
-The initial initial initialization scripts supported are:
-
-- [CloudInit](https://cloudinit.readthedocs.io)
-- [Sysprep](https://learn.microsoft.com/ru-ru/windows-hardware/manufacture/desktop/sysprep--system-preparation--overview).
-
-The CloudInit script can be embedded directly into the virtual machine specification, but this script is limited to a maximum length of 2048 bytes:
-
-```yaml
-spec:
- provisioning:
- type: UserData
- userData: |
- #cloud-config
- package_update: true
- ...
-```
-
-For longer scenarios and/or the presence of private data, the script for initial initial initialization of the virtual machine can be created in Secret. An example of Secret with a CloudInit script is shown below:
-
-```yaml
-apiVersion: v1
-kind: Secret
-metadata:
- name: cloud-init-example
-data:
- userData:
-type: provisioning.virtualization.deckhouse.io/cloud-init
-```
-
-A fragment of the virtual machine configuration using the CloudInit initialization script stored in Secret:
-
-```yaml
-spec:
- provisioning:
- type: UserDataRef
- userDataRef:
- kind: Secret
- name: cloud-init-example
-```
-
-Note: The value of the `.data.userData` field must be Base64 encoded.
-
-To configure Windows virtual machines using Sysprep, only the Secret variant is supported.
-
-An example of Secret with Sysprep script is shown below:
-
-```yaml
-apiVersion: v1
-kind: Secret
-metadata:
- name: sysprep-example
-data:
- unattend.xml:
-type: provisioning.virtualization.deckhouse.io/sysprep
-```
-
-Note: The value of the `.data.unattend.xml` field must be Base64 encoded.
-
-fragment of virtual machine configuration using Sysprep initialization script in Secret:
-
-```yaml
-spec:
- provisioning:
- type: SysprepRef
- sysprepRef:
- kind: Secret
- name: sysprep-example
-```
-
### Placement of VMs by nodes
The following methods can be used to manage the placement of virtual machines (placement parameters) across nodes:
@@ -1707,7 +1808,15 @@ All of the above parameters (including the `.spec.nodeSelector` parameter from V
- Use combinations of labels instead of single restrictions. For example, instead of required for a single label (e.g. env=prod), use several preferred conditions.
- Consider the order in which interdependent VMs are launched. When using Affinity between VMs (for example, the backend depends on the database), launch the VMs referenced by the rules first to avoid lockouts.
- Plan backup nodes for critical workloads. For VMs with strict requirements (e.g., AntiAffinity), provide backup nodes to avoid downtime in case of failure or maintenance.
-- Consider existing `taints` on nodes.
+- Consider existing `taints` on nodes. If necessary, you can add appropriate `tolerations` to the VM. An example of using `tolerations` to allow scheduling on nodes with the `node.deckhouse.io/group=:NoSchedule` taint is provided below.
+
+```yaml
+spec:
+ tolerations:
+ - key: "node.deckhouse.io/group"
+ operator: "Exists"
+ effect: "NoSchedule"
+```
{{< alert level="info" >}}
When changing placement parameters:
@@ -2189,7 +2298,7 @@ How to publish a VM service using Ingress in the web interface:
### Live virtual machine migration
-Live virtual machine (VM) migration is the process of moving a running VM from one physical host to another without shutting it down. This feature plays a key role in the management of virtualized infrastructure, ensuring application continuity during maintenance, load balancing, or upgrades.
+Live virtual machine (VM) migration is the process of moving a running VM from one physical host to another without shutting it down. This feature plays a key role in managing virtualized infrastructure, ensuring application continuity during maintenance, load balancing, or upgrades.
#### How live migration works
@@ -2197,132 +2306,53 @@ The live migration process involves several steps:
1. **Creation of a new VM instance**
- A new VM is created on the target host in a suspended state. Its configuration (CPU, disks, network) is copied from the source node.
+ A new VM is created on the target node in a suspended state. Its configuration (CPU, disks, network) is copied from the source node.
-2. **Primary Memory Transfer**
+1. **Primary memory transfer**
The entire RAM of the VM is copied to the target node over the network. This is called primary transfer.
-3. **Change Tracking (Dirty Pages)**
+1. **Change tracking (Dirty Pages)**
+
+ While memory is being transferred, the VM continues to run on the source node and may change some memory pages. These pages are called dirty pages, and the hypervisor marks them.
- While memory is being transferred, the VM continues to run on the source node and may change some memory pages. These pages are called dirty pages and the hypervisor marks them.
+1. **Iterative synchronization**
-4. **Iterative synchronization**.
+ After the initial transfer, only the modified pages are sent again. This process is repeated over several cycles:
- After the initial transfer, only the modified pages are resent. This process is repeated in several cycles:
- The higher the load on the VM, the more "dirty" pages appear, and the longer the migration takes.
- With good network bandwidth, the amount of unsynchronized data gradually decreases.
-5. **Final synchronization and switching**.
+1. **Final synchronization and switching**
- When the number of dirty pages becomes minimal, the VM on the source node is suspended (typically for 100 milliseconds):
- - The remaining memory changes are transferred to the target node.
- - The state of the CPU, devices, and open connections are synchronized.
- - The VM is started on the new node and the source copy is deleted.
+ When the number of dirty pages becomes minimal, the VM on the source node is suspended (typically for 100 milliseconds):
-
+ - The remaining memory changes are transferred to the target node.
+ - The state of the CPU, devices, and open connections are synchronized.
+ - The VM is started on the new node, and the source copy is deleted.
-{{< alert level="warning" >}}
-For successful live migration, all disks attached to the VM must be accessible on the target nodes to which the migration is planned.
-
-If a disk uses storage with local disks, such storage must be available to create a new local volume on the target node.
-
-Otherwise, migration will not be possible.
-{{< /alert >}}
+Until the VM switches to the new node (Phase 5), the VM on the source node continues to operate normally and provide services to users.
+
-{{< alert level="warning">}}
-Network speed plays an important role. If bandwidth is low, there are more iterations and VM downtime can increase. In the worst case, the migration may not complete at all.
-
-To manage the migration process, configure the live migration policy using [`.spec.liveMigrationPolicy`](#configuring-migration-policy) in the VM settings.
-{{< /alert >}}
+#### Requirements and limitations
-#### AutoConverge mechanism
+For successful live migration, certain requirements must be met. Failure to meet these requirements can lead to limitations and issues during migration.
-If the network struggles to handle data transfer and the number of "dirty" pages keeps growing, the AutoConverge mechanism can be useful. It helps complete migration even with low network bandwidth.
+- Disk availability: All disks attached to the VM must be accessible on the target node, otherwise migration will be impossible. For network storage (NFS, Ceph, etc.), this requirement is usually met automatically, as disks are accessible on all cluster nodes. For local storage, the situation is different: the storage system must be available on the target node to create a new local volume. If local storage exists only on the source node, migration cannot be performed.
-The working principles of AutoConverge mechanism:
+- Network bandwidth: Network speed is critical for live migration. With low bandwidth, the number of memory synchronization iterations increases, VM downtime during the final stage of migration increases, and in the worst case, migration may not complete due to a timeout. To manage the migration process, configure the live migration policy [`.spec.liveMigrationPolicy`](#configuring-migration-policy) in the virtual machine settings. For network problems, use the AutoConverge mechanism (see the [Migration with insufficient network bandwidth](#migration-with-insufficient-network-bandwidth) section).
-1. **VM CPU slowdown**.
+- Kernel versions on nodes: For stable live migration operation, all cluster nodes must use the same Linux kernel version. Differences in kernel versions can lead to incompatible interfaces, system calls, and resource handling features, which can disrupt the virtual machine migration process.
- The hypervisor gradually reduces the CPU frequency of the source VM. This reduces the rate at which new "dirty" pages appear. The higher the load on the VM, the greater the slowdown.
+- CPU compatibility: CPU compatibility depends on the CPU type specified in the virtual machine class. When using the `Host` type, migration is only possible between nodes with similar CPU types: migration between nodes with Intel and AMD processors does not work, and it also does not work between different CPU generations due to differences in instruction sets. When using the `HostPassthrough` type, the VM can only migrate to a node with exactly the same processor as on the source node. To ensure migration compatibility between nodes with different processors, use the `Discovery`, `Model`, or `Features` types in the virtual machine class.
-2. **Synchronization acceleration**.
+- Migration execution time: A completion timeout is set for live migration, which is calculated using the formula: `Completion timeout = 800 seconds × (Memory size in GiB + Disk size in GiB (if Block Migration is used))`. If migration does not complete within this time, the operation is considered failed and is canceled automatically. For example, for a virtual machine with 4 GiB of memory and 20 GiB of disk, the timeout will be `800 seconds × (4 GiB + 20 GiB) = 19200 seconds (320 minutes or ~5.3 hours)`. With low network speed or high load on the VM, migration may not complete within the allotted time.
- Once the data transfer rate exceeds the memory change rate, final synchronization is started and the VM switches to the new node.
-
-3. **Automatic Termination**
-
- Final synchronization is started when the data transfer rate exceeds the memory change rate.
-
-AutoConverge is a kind of "insurance" that ensures that the migration completes even if the network struggles to handle data transfer. However, CPU slowdown can affect the performance of applications running on the VM, so its use should be monitored.
-
-#### Configuring migration policy
-
-To configure migration behavior, use the `.spec.liveMigrationPolicy` parameter in the VM configuration. The following options are available:
-
-- `AlwaysSafe` - Migration is performed without slowing down the CPU (AutoConverge is not used). Suitable for cases where maximizing VM performance is important but requires high network bandwidth.
-- `PreferSafe` - (used as the default policy) By default, migration runs without AutoConverge, but CPU slowdown can be enabled manually if the migration fails to complete. This is done by using the VirtualMachineOperation resource with `type=Evict` and `force=true`.
-- `AlwaysForced` - Migration always uses AutoConverge, meaning the CPU is slowed down when necessary. This ensures that the migration completes even if the network is bad, but may degrade VM performance.
-- `PreferForced` - By default migration goes with AutoConverge, but slowdown can be manually disabled via VirtualMachineOperation with the parameter `type=Evict` and `force=false`.
-
-#### Migration types
-
-Migration can be performed manually by the user, or automatically by the following system events:
-
-- Updating the "firmware" of a virtual machine.
-- Redistribution of load in the cluster.
-- Transferring a node into maintenance mode (Node drain).
-- When you change [VM placement settings](#placement-of-vms-by-nodes) (not available in Community edition).
-
-The trigger for live migration is the appearance of the `VirtualMachineOperations` resource with the `Evict` type.
-
-The table shows the `VirtualMachineOperations` resource name prefixes with the `Evict` type that are created for live migrations caused by system events:
-
-| Type of system event | Resource name prefix |
-|---------------------------------|------------------------|
-| Firmware update | firmware-update-* |
-| Load shifting | evacuation-* |
-| Drain node | evacuation-* |
-| Modify placement parameters | nodeplacement-update-* |
-| Disk storage migration | volume-migration-* |
-
-This resource can be in the following states:
-
-- `Pending` - the operation is pending.
-- `InProgress` - live migration is in progress.
-- `Completed` - live migration of the virtual machine has been completed successfully.
-- `Failed` - the live migration of the virtual machine has failed.
-
-Diagnosing problems with a resource is done by analyzing the information in the `.status.conditions` block.
-
-You can view active operations using the command:
-
-```bash
-d8 k get vmop
-```
-
-Example output:
-
-```txt
-NAME PHASE TYPE VIRTUALMACHINE AGE
-firmware-update-fnbk2 Completed Evict static-vm-node-00 148m
-```
-
-You can interrupt any live migration while it is in the `Pending`, `InProgress` phase by deleting the corresponding `VirtualMachineOperations` resource.
-
-How to view active operations in the web interface:
-
-- Go to the "Projects" tab and select the desired project.
-- Go to the "Virtualization" → "Virtual Machines" section.
-- Select the required VM from the list and click on its name.
-- Go to the "Events" tab.
-
-#### How to perform a live migration of a virtual machine using `VirtualMachineOperations`
+#### How to perform a live VM migration
Let's look at an example. Before starting the migration, view the current status of the virtual machine:
-
```bash
d8 k get vm
```
@@ -2336,15 +2366,17 @@ linux-vm Running virtlab-pt-1 10.66.10.14 79m
We can see that it is currently running on the `virtlab-pt-1` node.
-To migrate a virtual machine from one host to another, taking into account the virtual machine placement requirements, the command is used:
+To migrate a virtual machine from one node to another while taking into account VM placement requirements, use the following command:
```bash
-d8 v evict -n
+d8 v evict -n [--force]
```
-execution of this command leads to the creation of the `VirtualMachineOperations` resource.
+Running this command creates a VirtualMachineOperations resource.
-You can also start the migration by creating a `VirtualMachineOperations` (`vmop`) resource with the `Evict` type manually:
+When used during virtual machine migration, the `--force` flag activates a special mechanism called AutoConverge (for more details, see the [Migration with insufficient network bandwidth](#migration-with-insufficient-network-bandwidth) section). This mechanism automatically reduces the CPU load of the virtual machine (slows down its CPU) when it is necessary to speed up the completion of migration and help it complete successfully, even when the virtual machine memory transfer is too slow. Use this flag if a standard migration cannot complete due to high virtual machine activity.
+
+You can also start the migration by creating a VirtualMachineOperations (`vmop`) resource with the `Evict` type manually:
```yaml
d8 k create -f - <
+ ```
+
+ Then restart the migration using the `--force` flag to enable the AutoConverge mechanism. Using the `--force` flag must comply with the current [virtual machine migration policy](#configuring-migration-policy).
+
+#### System-initiated migrations
+
+Migration can be performed automatically by the following system events:
+
+- Updating the "firmware" of a virtual machine.
+- Redistribution of load in the cluster.
+- Transferring a node into maintenance mode (Node drain).
+- When you change [VM placement settings](#placement-of-vms-by-nodes) (not available in Community edition).
+
+The trigger for live migration is the appearance of the VirtualMachineOperations resource with the `Evict` type.
+
+The table shows the VirtualMachineOperations resource name prefixes with the `Evict` type that are created for live migrations caused by system events:
+
+| Type of system event | Resource name prefix |
+|--------------------------------------|------------------------|
+| Firmware update | `firmware-update-*` |
+| Load redistribution in the cluster | `evacuation-*` |
+| Node drain | `evacuation-*` |
+| VM placement settings change | `nodeplacement-update-*` |
+| Disk storage migration | `volume-migration-*` |
+
+This resource can be in the following states:
+
+- `Pending`: The operation is pending.
+- `InProgress`: Live migration is in progress.
+- `Completed`: Live migration of the virtual machine has completed successfully.
+- `Failed`: Live migration of the virtual machine has failed.
+
+You can view active operations using the command:
+
+```bash
+d8 k get vmop
+```
+
+Example output:
+
+```txt
+NAME PHASE TYPE VIRTUALMACHINE AGE
+firmware-update-fnbk2 Completed Evict linux-vm 148m
+```
+
+To cancel the migration, delete the corresponding resource.
+
+How to view active operations in the web interface:
+
+1. Go to the "Projects" tab and select the desired project.
+1. Go to the "Virtualization" → "Virtual Machines" section.
+1. Select the required VM from the list and click on its name.
+1. Go to the "Events" tab.
+
#### Live migration of virtual machine when changing placement parameters (not available in CE edition)
Let's consider the migration mechanism on the example of a cluster with two node groups (`NodeGroups`): green and blue. Suppose a virtual machine (VM) is initially running on a node in the green group and its configuration contains no placement restrictions.
@@ -2503,6 +2644,10 @@ Remove the `.metadata.ownerReferences` blocks from the resource found:
```bash
d8 k patch vmip linux-vm-7prpx --type=merge --patch '{"metadata":{"ownerReferences":null}}'
+
+# Alternatively, apply the changes by editing the resource.
+
+d8 k edit vmip linux-vm-7prpx
```
After the virtual machine is deleted, the `vmip` resource is preserved and can be reused again in the newly created virtual machine:
@@ -2528,23 +2673,21 @@ EOF
### Additional network interfaces
-Virtual machines can be connected not only to the main cluster network interface but also to additional networks provided by the `d8-sdn` module. Such networks include project Networks and ClusterNetworks.
-
-Additional networks are defined in the `.spec.networks` configuration block. If this block is absent (default value), the VM is connected only to the main cluster network.
-
-{{< alert level=“warning” >}}
-Changes to the list of additional networks (adding or removing) take effect only after the VM is rebooted.
+{{< alert level="warning" >}}
+To work with additional networks, the `sdn` module must be enabled.
{{< /alert >}}
-{{< alert level=“info” >}}
-To avoid changing the order of network interfaces inside the guest OS, always add new networks to the end of the `.spec.networks` list.
-{{< /alert >}}
+Virtual machines can be connected to additional networks: project networks (`Network`) or cluster networks (`ClusterNetwork`).
+
+To do this, specify the desired networks in the configuration section `.spec.networks`. If this block is not specified (which is the default behavior), the VM will use only the main cluster network.
-Conditions and limitations:
+Important considerations when working with additional network interfaces:
-- The `d8-sdn` module is required to work with additional networks.
-- The order of networks in `.spec.networks` determines the sequence in which interfaces are attached to the VM bus.
-- Configuration of network parameters (IP addresses, gateways, DNS, etc.) in additional networks must be performed manually inside the guest OS (for example, via cloud-init).
+- The order of listing networks in `.spec.networks` determines the order in which interfaces are connected inside the virtual machine.
+- Adding or removing additional networks takes effect only after the VM is rebooted.
+- To preserve the order of network interfaces inside the guest operating system, it is recommended to add new networks to the end of the `.spec.networks` list (do not change the order of existing ones).
+- Network security policies (NetworkPolicy) do not apply to additional network interfaces.
+- Network parameters (IP addresses, gateways, DNS, etc.) for additional networks are configured manually from within the guest OS (for example, using Cloud-Init).
Example of connecting a VM to the project network `user-net`:
@@ -2632,7 +2775,27 @@ When a network is removed from the VM configuration:
## Snapshots
-Snapshots are designed to save the state of a resource at a particular point in time. Disk snapshots and virtual machine snapshots are currently supported.
+Snapshots allow you to capture the current state of a resource for later recovery or cloning: a disk snapshot saves only the data from the selected disk, while a virtual machine snapshot includes the VM settings and the state of all its disks.
+
+### Consistent snapshots
+
+Snapshots can be consistent or inconsistent; this is controlled by the `requiredConsistency` parameter. By default, `requiredConsistency` is set to `true`, which means a consistent snapshot is required.
+
+A consistent snapshot guarantees a consistent and complete state of the virtual machine's disks. Such a snapshot can be created when one of the following conditions is met:
+
+- The virtual machine is turned off.
+- [`qemu-guest-agent`](#guest-os-agent) is installed in the guest system, which temporarily suspends the file system at the time the snapshot is created to ensure its consistency.
+
+QEMU Guest Agent supports hook scripts that allow you to prepare applications for snapshot creation without stopping services, ensuring application-level consistency. For more information on configuring hooks scripts, see the [Guest OS agent](#guest-os-agent) section.
+
+An inconsistent snapshot may not reflect a consistent state of the virtual machine's disks and its components. Such a snapshot is created in the following cases:
+
+- The VM is running, and `qemu-guest-agent` is not installed or not running in the guest OS.
+- The snapshot manifest explicitly specifies the `requiredConsistency: false` parameter, and you want to avoid suspending the file system.
+
+{{< alert level="warning" >}}
+When restoring from such a snapshot, file system integrity issues may occur, as the data state may be inconsistent.
+{{< /alert >}}
### Creating disk snapshots
@@ -2751,22 +2914,6 @@ A virtual machine snapshot is a saved state of a virtual machine at a specific p
It is recommended to disconnect all images (VirtualImage/ClusterVirtualImage) from the virtual machine before creating its snapshot. Disk images are not saved together with the VM snapshot, and their absence in the cluster during recovery may cause the virtual machine to fail to start and remain in a Pending state while waiting for the images to become available.
{{< /alert >}}
-#### Types of snapshots
-
-Snapshots can be consistent or inconsistent, which is determined by the `requiredConsistency` parameter. By default, the `requiredConsistency` parameter is set to `true`, which requires a consistent snapshot.
-
-A consistent snapshot guarantees a consistent and complete state of the virtual machine's disks. Such a snapshot can be created when one of the following conditions is met:
-- The virtual machine is turned off.
-- `qemu-guest-agent` is installed in the guest system, which temporarily suspends the file system at the time the snapshot is created to ensure its consistency.
-
-An inconsistent snapshot may not reflect the consistent state of the virtual machine's disks and its components. Such a snapshot is created in the following cases:
-- The VM is running, and `qemu-guest-agent` is not installed or running in the guest OS.
-- The VM is running, and `qemu-guest-agent` is not installed in the guest OS, but the snapshot manifest specifies the `requiredConsistency: false` parameter, and you want to avoid suspending the file system.
-
-{{< alert level="warning" >}}
-There is a risk of data loss or integrity violation when restoring from such a snapshot.
-{{< /alert >}}
-
#### Creating snapshots
Creating a virtual machine snapshot will fail if at least one of the following conditions is met:
@@ -2881,16 +3028,79 @@ d8 k get vmop -o json | jq “.status.resources”
It is not recommended to cancel the restore operation (delete the `VirtualMachineOperation` resource in the `InProgress` phase) from a snapshot, which can result in an inconsistent state of the restored virtual machine.
{{< /alert >}}
+{{< alert level="info" >}}
+When restoring a VM from a snapshot, the disks associated with it are also restored from the corresponding snapshots, so the disk specification will contain a `dataSource` parameter with a reference to the required disk snapshot.
+{{< /alert >}}
## Creating a VM clone
-VM cloning is performed using the `VirtualMachineOperation` resource with the `clone` operation type.
+You can create a VM clone in two ways: from an existing VM or from a previously created snapshot of that VM.
+
+{{< alert level="warning">}}
+The cloned VM will be assigned a new IP address for the cluster network and MAC addresses for additional network interfaces (if any), so you will need to reconfigure the guest OS network settings after cloning.
+{{< /alert >}}
+
+Cloning creates a copy of a VM, so the resources of the new VM must have unique names. To do this, use the `nameReplacements` and/or `customization` parameters:
+
+- `nameReplacements`: Allows you to replace the names of existing resources with new ones to avoid conflicts.
+- `customization`: Sets a prefix or suffix for the names of all cloned VM resources (disks, IP addresses, etc.).
+
+Configuration example:
+
+```yaml
+nameReplacements:
+ - from:
+ kind:
+ name:
+ to:
+ name:
+customization:
+ namePrefix:
+ nameSuffix:
+```
+
+As a result, a VM named will be created.
+
+One of three modes can be used for the cloning operation:
+
+- `DryRun`: Test run to check for possible conflicts. The results are displayed in the `status.resources` field of the corresponding operation resource.
+- `Strict`: Strict mode, requiring all resources with new names and their dependencies (e.g., images) to be present in the cloned VM.
+- `BestEffort`: Mode in which missing external dependencies (e.g., ClusterVirtualImage, VirtualImage) are automatically removed from the configuration of the cloned VM.
+
+Information about conflicts that arose during cloning can be viewed in the operation resource status:
+
+```bash
+# For cloning from an existing VM.
+d8 k get vmop -o json | jq '.status.resources'
+
+# For cloning from a VM snapshot.
+d8 k get vmsop -o json | jq '.status.resources'
+```
+
+## Creating a clone from an existing VM
+
+VM cloning is performed using the VirtualMachineOperation resource with the `Clone` operation type.
{{< alert level="warning">}}
Before cloning, the source VM must be [powered off](#vm-start-and-state-management-policy).
It is recommended to set the `.spec.runPolicy: AlwaysOff` parameter in the configuration of the VM being cloned if you want to prevent the VM clone from starting automatically. This is because the clone inherits the behaviour of the parent VM.
{{< /alert >}}
+Before cloning, you need to prepare the guest OS to avoid conflicts with unique identifiers and network settings.
+
+Linux:
+
+- Clear the `machine-id` using `sudo truncate -s 0 /etc/machine-id` (for systemd) or delete the `/var/lib/dbus/machine-id` file.
+- Remove SSH host keys: `sudo rm -f /etc/ssh/ssh_host_*`.
+- Clear network interface configuration (if static settings are used).
+- Clear the Cloud-Init cache (if used): `sudo cloud-init clean`.
+
+Windows:
+
+- Run `sysprep` with the `/generalize` option, or use tools to reset unique identifiers (SID, hostname, etc.).
+
+Example of creating a VM clone:
+
```yaml
apiVersion: virtualization.deckhouse.io/v1alpha2
kind: VirtualMachineOperation
@@ -2905,58 +3115,60 @@ spec:
customization: {}
```
-{{< alert level="warning">}}
-The cloned VM will be assigned a new IP address for the cluster network and MAC addresses for additional network interfaces (if any), so you will need to reconfigure the network settings of the guest OS after cloning.
+The `nameReplacements` and `customization` parameters are configured in the `.spec.clone` block (see [general description](#creating-a-vm-clone) above).
+
+{{< alert level="info" >}}
+During cloning, temporary snapshots are automatically created for the virtual machine and all its disks. The new VM is then assembled from these snapshots. After cloning is complete, the temporary snapshots are automatically deleted, so they are not visible in the resource list. However, the specification of cloned disks still contains a reference (`dataSource`) to the corresponding snapshot, even if the snapshot itself no longer exists. This is expected behavior and does not indicate a problem: such references remain valid because, by the time the clone starts, all necessary data has already been transferred to the new disks.
{{< /alert >}}
-Cloning creates a copy of an existing VM, so the resources of the new VM must have unique names. To do this, use the `.spec.clone.nameReplacements` and/or `.spec.clone.customisation` parameters.
+## Creating a clone from a VM snapshot
-- `.spec.clone.nameReplacements`: Allows you to replace the names of existing resources with new ones to avoid conflicts.
-- `.spec.clone.customization`: Sets a prefix or suffix for the names of all cloned VM resources (disks, IP addresses, etc.).
+Cloning a VM from a snapshot is performed using the VirtualMachineSnapshotOperation resource with the `CreateVirtualMachine` operation type.
-Configuration example:
+Example of creating a VM clone from a snapshot:
```yaml
+apiVersion: virtualization.deckhouse.io/v1alpha2
+kind: VirtualMachineSnapshotOperation
+metadata:
+ name:
spec:
- clone:
- nameReplacements:
- - from:
- kind:
- name:
- - to:
- name:
- customization:
- namePrefix:
- nameSuffix:
+ type: CreateVirtualMachine
+ virtualMachineSnapshotName:
+ createVirtualMachine:
+ mode: DryRun | Strict | BestEffort
+ nameReplacements: []
+ customization: {}
```
-As a result, a VM named will be created.
+The `nameReplacements` and `customization` parameters are configured in the `.spec.createVirtualMachine` block (see [general description](#creating-a-vm-clone) above).
-One of three modes can be used for the cloning operation:
-- `DryRun`: A test run to check for possible conflicts. The results are displayed in the `status.resources` field of the VirtualMachineOperation resource.
-- `Strict`: Strict mode, requiring all resources with new names and their dependencies (e.g., images) to be present in the cloned VM.
-- `BestEffort`: Mode in which missing external dependencies (e.g., ClusterVirtualImage, VirtualImage) are automatically removed from the configuration of the cloned VM.
-
-Information about conflicts that arose during cloning can be viewed in the resource status:
-
-```bash
-d8 k get vmop -o json | jq '.status.resources'
-```
+{{< alert level="info" >}}
+When cloning a VM from a snapshot, the disks associated with it are also created from the corresponding snapshots, so the disk specification will contain a `dataSource` parameter with a reference to the required disk snapshot.
+{{< /alert >}}
## Data export
-DVP allows you to export virtual machine disks and disk images using the `d8` utility (version 1.17 and above).
+You can export virtual machine disks and disk snapshots using the `d8` utility (version 0.20.7 and above). For this function to work, the module [`storage-volume-data-manager`](/modules/storage-volume-data-manager/) must be enabled.
+
+{{< alert level="warning" >}}
+The disk must not be in use at the time of export. If it is attached to a VM, that VM must be stopped first.
+{{< /alert >}}
Example: export a disk (run on a cluster node):
```bash
-d8 download -n vd/ -o file.img
+d8 data download -n vd/ -o file.img
```
Example: export a disk snapshot (run on a cluster node):
```bash
-d8 download -n vds/ -o file.img
+d8 data download -n vds/ -o file.img
```
-To export resources outside the cluster, you must also use the `--publish` flag.
+If you are exporting data from a machine other than a cluster node (for example, from your local machine), use the `--publish` flag.
+
+{{< alert level="info" >}}
+To import a downloaded disk back into the cluster, upload it as an [image](#load-an-image-from-the-command-line) or as a [disk](#upload-a-disk-from-the-command-line).
+{{< /alert >}}
diff --git a/docs/USER_GUIDE.ru.md b/docs/USER_GUIDE.ru.md
index 66bc4a1e4f..05e9c5b5b0 100644
--- a/docs/USER_GUIDE.ru.md
+++ b/docs/USER_GUIDE.ru.md
@@ -6,7 +6,7 @@ weight: 50
## Введение
-Данное руководство предназначено для пользователей Deckhouse Virtualization Platform (DVP) и описывает порядок создания и изменения ресурсов, которые доступны для создания в проектах и пространствах имен кластера.
+Данное руководство предназначено для пользователей модуля `virtualization` в экосистеме Deckhouse и описывает порядок создания и изменения ресурсов, которые доступны для создания в проектах и пространствах имён кластера.
## Быстрый старт по созданию ВМ
@@ -235,7 +235,7 @@ weight: 50
Процесс создания образа включает следующие шаги:
- Пользователь создаёт ресурс `VirtualImage`.
-- После создания образ автоматически загружается из указанного в спецификации источника в хранилище (DVCR).
+- После создания образ автоматически загружается из указанного в спецификации источника в хранилище DVCR или PVC в зависимости от типа.
- После завершения загрузки, ресурс становится доступным для создания дисков.
Существуют различные типы образов:
@@ -245,6 +245,7 @@ weight: 50
Примеры ресурсов для получения образов виртуальной машины:
+
| Дистрибутив | Пользователь по умолчанию |
| --------------------------------------------------------------------------------- | ------------------------- |
| [AlmaLinux](https://almalinux.org/get-almalinux/#Cloud_Images) | `almalinux` |
@@ -613,7 +614,7 @@ EOF
## Диски
-Диски в виртуальных машинах используются для записи и хранения данных, что необходимо для корректной работы приложений и операционных систем. Для этих целей в DVP можно использовать различные типы хранилищ.
+Диски в виртуальных машинах используются для записи и хранения данных, что необходимо для работы операционных систем и приложений. Для этих целей можно использовать различные типы хранилищ.
В зависимости от выбранного типа хранилища, поведение дисков при создании виртуальных машин и в процессе эксплуатации может отличаться.
@@ -630,8 +631,7 @@ EOF
Режим доступа AccessMode:
- `ReadWriteMany (RWX)` - множественный доступ к диску. Живая миграция виртуальных машин с такими дисками возможна.
-- `ReadWriteOnce (RWO)` - доступ к диску предоставляется только одному экземпляру виртуальной машины. Живая миграция виртуальных машин с такими дисками поддерживается только для платных редакций DVP. Живая миграция доступна только если все диски подключены статически через `.spec.blockDeviceRefs`. Диски, подключенные динамически через `VirtualMachineBlockDeviceAttachments`, необходимо статически переподключить, указав их в `.spec.blockDeviceRefs`.
-
+- `ReadWriteOnce (RWO)` - доступ к диску предоставляется только одному экземпляру виртуальной машины. Живая миграция виртуальных машин с такими дисками поддерживается только для платных редакций. Живая миграция доступна только если все диски подключены статически через `.spec.blockDeviceRefs`. Диски, подключенные динамически через VirtualMachineBlockDeviceAttachments, необходимо статически переподключить, указав их в `.spec.blockDeviceRefs`.
При создании диска контроллер самостоятельно определит наиболее оптимальные параметры поддерживаемые хранилищем.
@@ -658,7 +658,7 @@ nfs-4-1-wffc nfs.csi.k8s.io Delet
С полным описанием параметров конфигурации дисков можно ознакомиться [в документации ресурса](cr.html#virtualdisk).
-Как узнать доступные варианты хранилищ веб-интерфейсе DVP:
+Как узнать доступные варианты хранилищ в веб-интерфейсе:
- Перейдите на вкладку «Система», далее в раздел «Хранилище» → «Классы хранилищ».
@@ -691,11 +691,12 @@ EOF
- `WaitForFirstConsumer` - диск ожидает создания виртуальной машины, которая будет его использовать.
- `WaitForUserUpload` - диск ожидает от пользователя загрузки образа (type: Upload).
- `Ready` - диск создан и готов для использования.
+- `Migrating` - живая миграция диска.
- `Failed` - произошла ошибка в процессе создания.
- `PVCLost` - системная ошибка, PVC с данными утерян.
- `Terminating` - идет процесс удаления диска. Диск может «зависнуть» в данном состоянии, если он еще подключен к виртуальной машине.
-До тех пор пока диск не перешёл в фазу `Ready` содержимое всего блока `.spec` допускается изменять. При изменении процесс создании диска запустится заново.
+До тех пор, пока диск не перешёл в фазу `Ready`, можно изменять любые поля блока `.spec`. При изменении процесс создания диска будет запущен заново.
Диагностика проблем с ресурсом осуществляется путем анализа информации в блоке `.status.conditions`.
@@ -734,7 +735,7 @@ blank-disk Ready 100Mi 1m2s
На примере ранее созданного проектного образа `VirtualImage`, рассмотрим команду позволяющую определить размер распакованного образа:
```bash
-d8 k get cvi ubuntu-22-04 -o wide
+d8 k get vi ubuntu-22-04 -o wide
```
Пример вывода:
@@ -819,6 +820,58 @@ linux-vm-root-2 Ready 2590Mi 7m15s
- Нажмите кнопку «Создать».
- Статус диска отображается слева вверху, под именем диска.
+### Загрузка диска из командной строки
+
+Чтобы загрузить диск из командной строки, предварительно создайте ресурс, как представлено ниже на примере VirtualDisk:
+
+```yaml
+d8 k apply -f - <",
+ "inCluster": "http://10.222.165.239/upload"
+}
+```
+
+Выполните загрузку диска с использованием следующей команды:
+
+```bash
+curl https://virtualization.example.com/upload/ --progress-bar -T | cat
+```
+
+После завершения загрузки диск должен быть создан и перейти в фазу `Ready`:
+
+```bash
+d8 k get vd uploaded-disk
+```
+
+Пример вывода:
+
+```txt
+NAMESPACE NAME PHASE CAPACITY AGE
+default uploaded-disk Ready 3Gi 7d23h
+```
+
### Изменение размера диска
Размер дисков можно увеличивать, даже если они уже подключены к работающей виртуальной машине. Для этого отредактируйте поле `spec.persistentVolumeClaim.size`:
@@ -840,6 +893,10 @@ linux-vm-root Ready 10Gi 10m
```bash
d8 k patch vd linux-vm-root --type merge -p '{"spec":{"persistentVolumeClaim":{"size":"11Gi"}}}'
+
+# Или внесите аналогичные изменения, отредактировав ресурс.
+
+d8 k edit vd linux-vm-root
```
Проверьте размер после изменения:
@@ -875,23 +932,30 @@ linux-vm-root Ready 11Gi 12m
- Нажмите на появившуюся кнопку «Сохранить».
- Статус диска отображается слева вверху, под его именем.
-### Изменение класса хранения диска
+### Миграция дисков на другие хранилища
-В платных редакциях DVP можно изменить класс хранения для существующих дисков. Сейчас это поддерживается только для работающих ВМ (`Phase` должна быть `Running`).
+В платных редакциях вы можете мигрировать (перенести) диск виртуальной машины на другое хранилище, изменив для него класс хранилища (StorageClass).
{{< alert level="warning">}}
-Миграция класса хранения поддерживается только для дисков, статически подключенных через параметр `.spec.blockDeviceRefs` в конфигурации виртуальной машины.
+Ограничения миграции дисков между хранилищами:
-Для миграции класса хранения дисков, подключенных через `VirtualMachineBlockDeviceAttachments`, необходимо переподключить их статически, указав имена дисков в `.spec.blockDeviceRefs`.
+- Миграция доступна только для виртуальных машин в состоянии `Running`.
+- Миграция поддерживается только между дисками одного типа: `Block` ↔ `Block`, `FileSystem` ↔ `FileSystem`; перевод между разными типами невозможен.
+- Миграция поддерживается только для дисков, подключённых статически через параметр `.spec.blockDeviceRefs` в спецификации виртуальной машины.
+- Если диск был подключён посредством ресурса VirtualMachineBlockDeviceAttachments, для выполнения миграции его необходимо временно переподключить напрямую, указав имя диска в `.spec.blockDeviceRefs`.
{{< /alert >}}
-Пример:
+Пример миграции диска на класс хранения `new-storage-class-name`:
```bash
d8 k patch vd disk --type=merge --patch '{"spec":{"persistentVolumeClaim":{"storageClassName":"new-storage-class-name"}}}'
+
+# Или внесите аналогичные изменения, отредактировав ресурс.
+
+d8 k edit vd disk
```
-После изменения конфигурации диска запустится живая миграция ВМ, в процессе которой диск ВМ будет мигрирован на новое хранилище.
+После изменения конфигурации диска запустится живая миграция ВМ, в процессе которой диск ВМ будет перемещен в новое хранилище.
Если к виртуальной машине подключены несколько дисков и требуется изменить класс хранения для нескольких дисков, эту операцию необходимо выполнить последовательно:
@@ -908,7 +972,7 @@ d8 k patch vd disk2 --type=merge --patch '{"spec":{"persistentVolumeClaim":{"sto
Для создания виртуальной машины используется ресурс `VirtualMachine`. Его параметры позволяют сконфигурировать:
-- [класс виртуальной машины](admin_guide.html#классы-виртуальных-машин)
+- [класс виртуальной машины](admin_guide.html#классы-виртуальных-машин);
- ресурсы, требуемые для работы виртуальной машины (процессор, память, диски и образы);
- правила размещения виртуальной машины на узлах кластера;
- настройки загрузчика и оптимальные параметры для гостевой ОС;
@@ -945,7 +1009,7 @@ spec:
packages:
- nginx
- qemu-guest-agent
- run_cmd:
+ runcmd:
- systemctl daemon-reload
- systemctl enable --now nginx.service
- systemctl enable --now qemu-guest-agent.service
@@ -1011,7 +1075,7 @@ linux-vm Running virtlab-pt-2 10.66.10.12 11m
packages:
- nginx
- qemu-guest-agent
- run_cmd:
+ runcmd:
- systemctl daemon-reload
- systemctl enable --now nginx.service
- systemctl enable --now qemu-guest-agent.service
@@ -1095,7 +1159,7 @@ linux-vm Running virtlab-pt-2 10.66.10.12 11m
ВМ переносится на другой узел кластера (живая миграция).
- Особенности:
- - Миграция ВМ поддерживается только для нелокальных дисков, условие `type: Migratable` отображает информацию о том может ли ВМ мигрировать или нет.
+ - Условие `type: Migratable` показывает, может ли ВМ мигрировать.
- Возможные проблемы:
- Несовместимость процессорных инструкций (при использовании типов процессоров host или host-passthrough).
- Различие версиях ядер на узлах гипервизоров.
@@ -1269,6 +1333,143 @@ status:
coresPerSocket: 1
```
+### Сценарии начальной инициализации ВМ
+
+Сценарии начальной инициализации предназначены для первичной конфигурации виртуальной машины при её запуске.
+
+В качестве сценариев начальной инициализации поддерживаются:
+
+- [Cloud-Init](https://cloudinit.readthedocs.io).
+- [Sysprep](https://learn.microsoft.com/ru-ru/windows-hardware/manufacture/desktop/sysprep--system-preparation--overview).
+
+#### Cloud-Init
+
+Cloud-Init — это инструмент для автоматической настройки виртуальных машин при первом запуске. Он позволяет выполнять широкий спектр задач конфигурации без ручного вмешательства.
+
+{{< alert level="warning" >}}
+Конфигурация Cloud-Init записывается в формате YAML и должна начинаться с заголовка `#cloud-config` в начале блока конфигурации. О других возможных заголовках и их назначении вы можете узнать в [официальной документации по cloud-init](https://cloudinit.readthedocs.io/en/latest/explanation/format.html#headers-and-content-types).
+{{< /alert >}}
+
+Основные возможности Cloud-Init:
+
+- создание пользователей, установка паролей, добавление SSH-ключей для доступа;
+- автоматическая установка необходимого программного обеспечения при первом запуске;
+- запуск произвольных команд и скриптов для настройки системы;
+- автоматический запуск и включение системных сервисов (например, [`qemu-guest-agent`](#агент-гостевой-ос)).
+
+##### Типичные сценарии использования
+
+1. Добавление SSH-ключа для [предустановленного пользователя](#image-resources-table), который уже может присутствовать в cloud-образе (например, пользователь `ubuntu` в официальных образах Ubuntu). Имя такого пользователя зависит от образа. Уточните его в документации к вашему дистрибутиву.
+
+ ```yaml
+ #cloud-config
+ ssh_authorized_keys:
+ - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
+ ```
+
+1. Создание пользователя с паролем и SSH-ключом:
+
+ ```yaml
+ #cloud-config
+ users:
+ - name: cloud
+ passwd: "$6$rounds=4096$saltsalt$..."
+ lock_passwd: false
+ sudo: ALL=(ALL) NOPASSWD:ALL
+ shell: /bin/bash
+ ssh-authorized-keys:
+ - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
+ ssh_pwauth: True
+ ```
+
+ Для генерации хеша пароля используйте команду `mkpasswd --method=SHA-512 --rounds=4096`.
+
+1. Установка пакетов и сервисов:
+
+ ```yaml
+ #cloud-config
+ package_update: true
+ packages:
+ - nginx
+ - qemu-guest-agent
+ runcmd:
+ - systemctl daemon-reload
+ - systemctl enable --now nginx.service
+ - systemctl enable --now qemu-guest-agent.service
+ ```
+
+##### Использование Cloud-Init
+
+Сценарий Cloud-Init можно встраивать непосредственно в спецификацию виртуальной машины, но этот сценарий ограничен максимальной длиной в 2048 байт:
+
+```yaml
+spec:
+ provisioning:
+ type: UserData
+ userData: |
+ #cloud-config
+ package_update: true
+ ...
+```
+
+При более длинных сценариях и/или наличии приватных данных, сценарий начальной инициализации виртуальной машины может быть создан в ресурсе Secret. Пример ресурса Secret со сценарием Cloud-Init приведен ниже:
+
+```yaml
+apiVersion: v1
+kind: Secret
+metadata:
+ name: cloud-init-example
+data:
+ userData:
+type: provisioning.virtualization.deckhouse.io/cloud-init
+```
+
+Фрагмент конфигурации виртуальной машины при использовании скрипта начальной инициализации Cloud-Init, хранящегося в ресурсе Secret:
+
+```yaml
+spec:
+ provisioning:
+ type: UserDataRef
+ userDataRef:
+ kind: Secret
+ name: cloud-init-example
+```
+
+{{< alert level="info" >}}
+Значение поля `.data.userData` должно быть закодировано в формате Base64. Для кодирования можно использовать команду `base64 -w 0` или `echo -n "content" | base64`.
+{{< /alert >}}
+
+#### Sysprep
+
+Для конфигурирования виртуальных машин под управлением ОС Windows с использованием Sysprep поддерживается только вариант с ресурсом Secret.
+
+Пример ресурса Secret со сценарием Sysprep:
+
+```yaml
+apiVersion: v1
+kind: Secret
+metadata:
+ name: sysprep-example
+data:
+ unattend.xml:
+type: provisioning.virtualization.deckhouse.io/sysprep
+```
+
+{{< alert level="info" >}}
+Значение поля `.data.unattend.xml` должно быть закодировано в формате Base64. Для кодирования можно использовать команду `base64 -w 0` или `echo -n "content" | base64`.
+{{< /alert >}}
+
+Фрагмент конфигурации виртуальной машины с использованием скрипта начальной инициализации Sysprep в ресурсе Secret:
+
+```yaml
+spec:
+ provisioning:
+ type: SysprepRef
+ sysprepRef:
+ kind: Secret
+ name: sysprep-example
+```
+
### Агент гостевой ОС
Для повышения эффективности управления ВМ рекомендуется установить QEMU Guest Agent — инструмент, который обеспечивает взаимодействие между гипервизором и операционной системой внутри ВМ.
@@ -1332,46 +1533,14 @@ sudo systemctl enable --now qemu-guest-agent
package_update: true
packages:
- qemu-guest-agent
- run_cmd:
+ runcmd:
- systemctl enable --now qemu-guest-agent.service
```
-### Настройка пользователя для cloud-образов
-
-При использовании cloud-образов (с поддержкой cloud-init) обязательно задайте SSH-ключ или пароль для предустановленного пользователя, либо создайте нового пользователя с заданным паролем или SSH-ключом через cloud-init. В противном случае войти в виртуальную машину будет невозможно!
-
-Примеры:
-
-1. Установка пароля для существующего пользователя (например, `ubuntu`, часто присутствует в официальных cloud-образах):
-
- Во многих cloud-образах пользователь по умолчанию уже предопределён (например, `ubuntu` в Ubuntu Cloud Images) и его имя не всегда можно переопределить через `cloud-init` с помощью блока `users`. В таких случаях рекомендуется использовать специализированные параметры cloud-init для управления дефолтным пользователем.
-
- При использовании облачного образа можно добавить публичный SSH-ключ для пользователя по умолчанию с помощью параметра `ssh_authorized_keys` на корневом уровне cloud-init:
-
- ```yaml
- #cloud-config
- ssh_authorized_keys:
- - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
- ```
-
-2. Создание нового пользователя с паролем и SSH-ключом:
-
- ```yaml
- #cloud-config
- users:
- - name: cloud
- passwd: "$6$rounds=4096$QktreHgVzeZy70h3$C8c4gjzYMY75.C7IjN1.GgrjMSdeyG79W.hZgsTNnlrJIzuB48qzCui8KP1par.OvCEV3Xi8FzRiqqZ74LOK6."
- lock_passwd: false
- sudo: ALL=(ALL) NOPASSWD:ALL
- shell: /bin/bash
- ssh-authorized-keys:
- - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD... your-public-key ...
- ssh_pwauth: True
- ```
+QEMU Guest Agent не требует дополнительной настройки после установки. Однако для обеспечения консистентности снимков на уровне приложений (без остановки сервисов) можно добавить скрипты, которые будут автоматически выполняться в гостевой ОС до и после операций заморозки (`freeze`) и оттаивания (`thaw`) файловой системы. Скрипты должны иметь права на выполнение и размещаться в специальном каталоге, путь к которому зависит от используемого дистрибутива:
-{{< alert level="info" >}}
-Значение поля `passwd` — это захешированный пароль (например, можно получить командой `mkpasswd --method=SHA-512 --rounds=4096`).
-{{< /alert >}}
+- `/etc/qemu-ga/hooks.d/` — для дистрибутивов на базе Debian/Ubuntu;
+- `/etc/qemu/fsfreeze-hook.d/` — для дистрибутивов на базе RHEL/CentOS/Fedora.
### Подключение к виртуальной машине
@@ -1538,6 +1707,10 @@ d8 v ssh cloud@linux-vm --local-ssh --command "nproc"
```bash
d8 k patch vm linux-vm --type merge -p '{"spec":{"cpu":{"cores":2}}}'
+
+# Или внесите аналогичные изменения, отредактировав ресурс.
+
+d8 k edit vm linux-vm
```
Пример вывода:
@@ -1629,79 +1802,6 @@ spec:
- Включите переключатель «Автоприменение изменений».
- Нажмите на появившуюся кнопку «Сохранить».
-### Сценарии начальной инициализации ВМ
-
-Сценарии начальной инициализации предназначены для первичной конфигурации виртуальной машины при её запуске.
-
-В качестве сценариев начальной инициализации поддерживаются:
-
-- [CloudInit](https://cloudinit.readthedocs.io).
-- [Sysprep](https://learn.microsoft.com/ru-ru/windows-hardware/manufacture/desktop/sysprep--system-preparation--overview).
-
-Сценарий CloudInit можно встраивать непосредственно в спецификацию виртуальной машины, но этот сценарий ограничен максимальной длиной в 2048 байт:
-
-```yaml
-spec:
- provisioning:
- type: UserData
- userData: |
- #cloud-config
- package_update: true
- ...
-```
-
-При более длинных сценариях и/или наличия приватных данных, сценарий начальной инициализации виртуальной машины может быть создан в ресурсе Secret. Пример ресурса Secret со сценарием CloudInit приведен ниже:
-
-```yaml
-apiVersion: v1
-kind: Secret
-metadata:
- name: cloud-init-example
-data:
- userData:
-type: provisioning.virtualization.deckhouse.io/cloud-init
-```
-
-фрагмент конфигурации виртуальной машины с при использовании скрипта начальной инициализации CloudInit хранящегося в ресурсе Secret:
-
-```yaml
-spec:
- provisioning:
- type: UserDataRef
- userDataRef:
- kind: Secret
- name: cloud-init-example
-```
-
-Примечание: Значение поля `.data.userData` должно быть закодировано в формате Base64.
-
-Для конфигурирования виртуальных машин под управлением ОС Windows с использованием Sysprep, поддерживается только вариант с ресурсом Secret.
-
-Пример ресурса Secret с сценарием Sysprep приведен ниже:
-
-```yaml
-apiVersion: v1
-kind: Secret
-metadata:
- name: sysprep-example
-data:
- unattend.xml:
-type: provisioning.virtualization.deckhouse.io/sysprep
-```
-
-Примечание: Значение поля `.data.unattend.xml` должно быть закодировано в формате Base64.
-
-фрагмент конфигурации виртуальной машины с использованием скрипта начальной инициализации Sysprep в ресурсе Secret:
-
-```yaml
-spec:
- provisioning:
- type: SysprepRef
- sysprepRef:
- kind: Secret
- name: sysprep-example
-```
-
### Размещение ВМ по узлам
Для управления размещением виртуальных машин (параметров размещения) по узлам можно использовать следующие подходы:
@@ -1723,7 +1823,15 @@ spec:
- Используйте комбинации меток вместо одиночных ограничений. Например, вместо required для одного лейбла (например, env=prod) используйте несколько preferred условий.
- Учитывайте порядок запуска взаимозависимых ВМ. При использовании Affinity между ВМ (например, бэкенд зависит от базы данных) запускайте сначала ВМ, на которые ссылаются правила, чтобы избежать блокировок.
- Планируйте резервные узлы для критических нагрузок. Для ВМ с жесткими требованиями (например, AntiAffinity) предусмотрите дополнительные узлы, чтобы избежать простоев при сбое или выводе узла в режим обслуживания.
-- Учитывайте существующие ограничения (`taints`) на узлах.
+- Учитывайте существующие ограничения (`taints`) на узлах. При необходимости можно добавить соответствующие `tolerations` для ВМ. Пример использования `tolerations` для разрешения запуска на узлах с taint `node.deckhouse.io/group=:NoSchedule`:
+
+```yaml
+spec:
+ tolerations:
+ - key: "node.deckhouse.io/group"
+ operator: "Exists"
+ effect: "NoSchedule"
+```
{{< alert level="info" >}}
При изменении параметров размещения:
@@ -2242,102 +2350,25 @@ EOF
- Состояние процессора, устройств и открытых соединений синхронизируется.
- ВМ запускается на новом узле, а исходная копия удаляется.
-
-
-{{< alert level="warning" >}}
-Для успешной живой миграции необходимо, чтобы все подключённые к ВМ диски были доступны на целевых узлах, куда планируется миграция.
-
-Если диск использует хранилище с локальными дисками, такое хранилище должно быть доступно для создания нового локального тома на целевом узле.
-
-В противном случае миграция будет невозможна.
-{{< /alert >}}
-
-{{< alert level="warning" >}}
-Cкорость сети играет важную роль. Если пропускная способность низкая, итераций становится больше, а время простоя ВМ может увеличиться. В худшем случае миграция может вообще не завершиться.
-
-Для управления процессом миграции настройке политику живой миграции [`.spec.liveMigrationPolicy`](#настройка-политики-миграции) в настройках ВМ.
-{{< /alert >}}
-
-#### Механизм AutoConverge
-
-Если сеть не справляется с передачей данных, а количество «грязных» страниц продолжает расти, будет полезен механизм AutoConverge. Он помогает завершить миграцию даже при низкой пропускной способности сети.
-
-Принципы работы механизма AutoConverge:
-
-1. **Замедление процессора ВМ**
-
- Гипервизор постепенно снижает частоту процессора исходной ВМ. Это уменьшает скорость появления новых «грязных» страниц. Чем выше нагрузка на ВМ, тем сильнее замедление.
-
-2. **Ускорение синхронизации**
-
- Как только скорость передачи данных превышает скорость изменения памяти, запускается финальная синхронизация, и ВМ переключается на новый узел.
-
-3. **Автоматическое завершение**
-
- Финальная синхронизация запускается, когда скорость передачи данных превышает скорость изменения памяти.
+До момента переключения ВМ на новый узел (Фаза 5), ВМ на исходном узле продолжает работать в обычном режиме и предоставлять сервис пользователям.
-AutoConverge — это своего рода «страховка», которая гарантирует, что миграция завершится, даже если сеть не справляется с передачей данных. Однако замедление процессора может повлиять на производительность приложений, работающих на ВМ, поэтому его использование нужно контролировать.
+
-#### Настройка политики миграции
-
-Для настройки поведения миграции используйте параметр `.spec.liveMigrationPolicy` в конфигурации ВМ. Допустимые значения параметра:
-
-- `AlwaysSafe` — Миграция всегда выполняется без замедления процессора (AutoConverge не используется). Подходит для случаев, когда важна максимальная производительность ВМ, но требует высокой пропускной способности сети.
-- `PreferSafe` — (используется в качестве политики по умолчанию) Миграция выполняется без замедления процессора (AutoConverge не используется). Однако можно запустить миграцию с замедлением процессора, используя ресурс VirtualMachineOperation с параметрами `type=Evict` и `force=true`.
-- `AlwaysForced` — Миграция всегда использует AutoConverge, то есть процессор замедляется при необходимости. Это гарантирует завершение миграции даже при плохой сети, но может снизить производительность ВМ.
-- `PreferForced` — Миграция использует AutoConverge, то есть процессор замедляется при необходимости. Однако можно запустить миграцию без замедления процессора, используя ресурс VirtualMachineOperation с параметрами `type=Evict` и `force=false`.
-
-#### Виды миграции
-
-Миграция может осуществляться пользователем вручную, либо автоматически при следующих системных событиях:
-
-- Обновлении «прошивки» виртуальной машины.
-- Перераспределение нагрузки в кластере.
-- Перевод узла в режим технического обслуживания (Drain узла)
-- При изменении [параметров размещения ВМ](#размещение-вм-по-узлам) (не доступно в Community-редакции).
-
-Триггером к живой миграции является появление ресурса `VirtualMachineOperations` с типом `Evict`.
+#### Требования и ограничения
-В таблице приведены префиксы названия ресурса `VirtualMachineOperations` с типом `Evict`, создаваемые для живых миграций вызванных системными событиями:
+Для успешной живой миграции необходимо выполнить определённые требования. Несоблюдение этих требований приводит к ограничениям и проблемам при миграции.
-| Вид системного события | Префикс имени ресурса |
-| ------------------------------- | ----------------------- |
-| Обновлении «прошивки» | firmware-update-\* |
-| Перераспределение нагрузки | evacuation-\* |
-| Drain узла | evacuation-\* |
-| Изменение параметров размещения | nodeplacement-update-\* |
-| Миграция хранилища дисков | volume-migration-\* |
+- Доступность дисков: Все подключённые к ВМ диски должны быть доступны на целевом узле, иначе миграция будет невозможна. Для сетевых хранилищ (NFS, Ceph и т.д.) это требование обычно выполняется автоматически, так как диски доступны на всех узлах кластера. Для локальных хранилищ ситуация иная: хранилище должно быть доступно для создания нового локального тома на целевом узле. Если локальное хранилище есть только на исходном узле, миграция не может быть выполнена.
-Данный ресурс может находится в следующих состояниях:
+- Пропускная способность сети: Скорость сети критически важна для живой миграции. При низкой пропускной способности увеличивается количество итераций синхронизации памяти, возрастает время простоя ВМ на финальном этапе миграции, а в худшем случае миграция может не завершиться из-за превышения таймаута. Для управления процессом миграции настройте политику живой миграции [`.spec.liveMigrationPolicy`](#настройка-политики-миграции) в настройках ВМ. При проблемах с сетью используйте механизм AutoConverge (см. раздел [Миграции при недостаточной пропускной способности сети](#миграции-при-недостаточной-пропускной-способности-сети)).
-- `Pending` - ожидается выполнение операции.
-- `InProgress` - живая миграция выполняется.
-- `Completed` - живая миграция виртуальной машины завершилась успешно.
-- `Failed` - живая миграция виртуальной машины завершилась неуспешно.
+- Версии ядер на узлах: Для стабильной работы живой миграции на всех узлах кластера должна использоваться идентичная версия ядра Linux. Различия в версиях ядра могут привести к несовместимости интерфейсов, системных вызовов и особенностей работы с ресурсами, что нарушает процесс миграции виртуальных машин.
-Посмотреть активные операции можно с использованием команды:
+- Совместимость процессоров: Совместимость процессоров зависит от типа CPU, указанного в классе виртуальной машины. При использовании типа `Host` миграция возможна только между узлами с похожими типами процессоров: миграция между узлами с процессорами Intel и AMD не работает, также не работает между разными поколениями CPU из-за различий в наборе инструкций. При использовании типа `HostPassthrough` ВМ может мигрировать только на узел с точно таким же процессором, как на исходном узле. Для обеспечения совместимости миграции между узлами с разными процессорами используйте типы `Discovery`, `Model` или `Features` в классе виртуальной машины.
-```bash
-d8 k get vmop
-```
+- Время выполнения миграции: Для живой миграции устанавливается таймаут завершения, который рассчитывается по формуле: `Таймаут завершения = 800 секунд × (Размер памяти в GiB + Размер диска в GiB (если используется Block Migration))`. Если миграция не завершается в течение этого времени, операция считается неудачной и отменяется. Например, для виртуальной машины с 4 GiB памяти и 20 GiB диска таймаут составит `800 секунд × (4 GiB + 20 GiB) = 19200 секунд (320 минут или ~5,3 часа)`. При низкой скорости сети или высокой нагрузке на ВМ миграция может не успеть завершиться в отведённое время.
-Пример вывода:
-
-```txt
-NAME PHASE TYPE VIRTUALMACHINE AGE
-firmware-update-fnbk2 Completed Evict linux-vm 1m
-```
-
-Прервать любую живую миграцию пока она находится в фазе `Pending`, `InProgress` можно удалив соответствующий ресурс `VirtualMachineOperations`.
-
-Как посмотреть активные операции в веб-интерфейсе:
-
-- Перейдите на вкладку «Проекты» и выберите нужный проект.
-- Перейдите в раздел «Виртуализация» → «Виртуальные машины».
-- Из списка выберите необходимую ВМ и нажмите на её имя.
-- Перейдите на вкладку «События».
-
-#### Как выполнить живую миграцию ВМ с использованием `VirtualMachineOperations`
+#### Как выполнить живую миграцию ВМ
Рассмотрим пример. Перед запуском миграции посмотрите текущий статус виртуальной машины:
@@ -2354,15 +2385,17 @@ linux-vm Running virtlab-pt-1 10.66.10.14 79
Мы видим что на данный момент она запущена на узле `virtlab-pt-1`.
-Для осуществления миграции виртуальной машины с одного узла на другой, с учетом требований к размещению виртуальной машины используется команда:
+Для миграции виртуальной машины с одного узла на другой с учётом требований к её размещению используйте команду:
```bash
-d8 v evict -n
+d8 v evict -n [--force]
```
-Выполнение данной команды приводит к созданию ресурса `VirtualMachineOperations`.
+Выполнение этой команды приводит к созданию ресурса VirtualMachineOperations.
+
+Флаг `--force` при выполнении миграции виртуальной машины активирует специальный механизм AutoConverge (подробнее см. раздел [Миграции при недостаточной пропускной способности сети](#миграции-при-недостаточной-пропускной-способности-сети)). Этот механизм автоматически снижает нагрузку на процессор виртуальной машины (замедляет её CPU), если требуется ускорить завершение миграции и обеспечить её успешное выполнение, даже если передача памяти ВМ идёт слишком медленно. Используйте этот флаг, если стандартная миграция не может завершиться из-за высокой активности ВМ.
-Запустить миграцию можно также создав ресурс `VirtualMachineOperations` (`vmop`) с типом `Evict` вручную:
+Запустить миграцию можно также создав ресурс VirtualMachineOperations (`vmop`) с типом `Evict` вручную:
```yaml
d8 k create -f - <
+ ```
+
+1. Повторно запустить миграцию с использованием флага `--force`, чтобы включить механизм AutoConverge. Использование флага `--force` должно соответствовать текущей [политике миграции виртуальной машины](#настройка-политики-миграции).
+
+#### Миграции, запускаемые системой
+
+Миграция может осуществляться автоматически при следующих системных событиях:
+
+- обновление «прошивки» виртуальной машины;
+- перераспределение нагрузки в кластере;
+- перевод узла в режим технического обслуживания (drain узла);
+- изменение [параметров размещения ВМ](#размещение-вм-по-узлам) (недоступно в Community-редакции).
+
+Триггером к живой миграции является появление ресурса VirtualMachineOperations с типом `Evict`.
+
+В таблице приведены префиксы названия ресурса VirtualMachineOperations с типом `Evict`, создаваемые для живых миграций, вызванных системными событиями:
+
+| Вид системного события | Префикс имени ресурса |
+|---------------------------------|-------------------------|
+| Обновление «прошивки» | `firmware-update-\*` |
+| Перераспределение нагрузки | `evacuation-\*` |
+| Drain узла | `evacuation-\*` |
+| Изменение параметров размещения | `nodeplacement-update-\*` |
+| Миграция хранилища дисков | `volume-migration-\*` |
+
+Данный ресурс может находиться в следующих состояниях:
+
+- `Pending` — ожидается выполнение операции;
+- `InProgress` — живая миграция выполняется;
+- `Completed` — живая миграция виртуальной машины завершилась успешно;
+- `Failed` — живая миграция виртуальной машины завершилась с ошибкой.
+
+Посмотреть активные операции можно с использованием команды:
+
+```bash
+d8 k get vmop
+```
+
+Пример вывода:
+
+```txt
+NAME PHASE TYPE VIRTUALMACHINE AGE
+firmware-update-fnbk2 Completed Evict linux-vm 1m
+```
+
+Для отмены миграции удалите соответствующий ресурс.
+
+Как посмотреть активные операции в веб-интерфейсе:
+
+1. Перейдите на вкладку «Проекты» и выберите нужный проект.
+1. Перейдите в раздел «Виртуализация» → «Виртуальные машины».
+1. Из списка выберите необходимую ВМ и нажмите на её имя.
+1. Перейдите на вкладку «События».
+
#### Живая миграция ВМ при изменении параметров размещения
{{< alert level="warning" >}}
@@ -2534,6 +2675,10 @@ linux-vm-7prpx
```bash
d8 k patch vmip linux-vm-7prpx --type=merge --patch '{"metadata":{"ownerReferences":null}}'
+
+# Или внесите аналогичные изменения, отредактировав ресурс.
+
+d8 k edit vmip linux-vm-7prpx
```
После удаления виртуальной машины, ресурс `vmip` сохранится и его можно будет переиспользовать снова во вновь созданной виртуальной машине:
@@ -2559,23 +2704,21 @@ EOF
### Дополнительные сетевые интерфейсы
-Виртуальные машины могут быть подключены не только к основному сетевому интерфейсу кластера, но и к дополнительным сетям, предоставляемым модулем `d8-sdn`. К таким сетям относятся проектные сети (Network) и кластерные сети (ClusterNetwork).
-
-Дополнительные сети задаются в конфигурационном блоке `.spec.networks`. Если этот блок отсутствует (значение по умолчанию), ВМ подключается только к основной сети кластера.
-
{{< alert level="warning" >}}
-Изменения в списке дополнительных сетей (добавление или удаление) применяются только после перезагрузки ВМ.
+Для работы с дополнительными сетями необходимо, чтобы модуль `sdn` был активирован.
{{< /alert >}}
-{{< alert level="info" >}}
-Чтобы избежать изменения порядка сетевых интерфейсов внутри гостевой ОС, добавляйте новые сети в конец списка `.spec.networks`.
-{{< /alert >}}
+Виртуальные машины могут быть подключены к дополнительным сетям — проектным (Network) или кластерным (ClusterNetwork).
+
+Для этого необходимо указать желаемые сети в конфигурационном разделе `.spec.networks`. Если данный блок не задан (что является значением по умолчанию), ВМ будет использовать только основную сеть кластера.
-Условия работы и ограничения:
+Особенности и важные моменты работы с дополнительными сетевыми интерфейсами:
-- Модуль `d8-sdn` обязателен для работы с дополнительными сетями.
-- Порядок сетей в `.spec.networks` определяет последовательность подключения интерфейсов к шине ВМ.
-- Настройка сетевых параметров (IP-адреса, шлюзы, DNS и т.д.) в дополнительных сетях выполняется вручную внутри гостевой ОС (например, через cloud-init).
+- порядок перечисления сетей в `.spec.networks` определяет порядок подключения интерфейсов внутри виртуальной машины;
+- добавление или удаление дополнительных сетей вступает в силу только после перезагрузки ВМ;
+- чтобы сохранить порядок сетевых интерфейсов внутри гостевой операционной системы, рекомендуется добавлять новые сети в конец списка `.spec.networks` (не менять порядок уже существующих);
+- политики сетевой безопасности (NetworkPolicy) не применяются к дополнительным сетевым интерфейсам;
+- параметры сети (IP-адреса, шлюзы, DNS и т.д.) для дополнительных сетей настраиваются вручную изнутри гостевой ОС (например, с помощью Cloud-Init).
Пример подключения ВМ к проектной сети `user-net`:
@@ -2663,7 +2806,27 @@ vm-01-fz9cr 5e:e6:19:22:0f:d8 Attached vm-01 5m42s
## Снимки
-Снимки предназначены для сохранения состояния ресурса в конкретный момент времени. На данный момент времени поддерживаются снимки дисков и снимки виртуальных машин.
+Снимки позволяют зафиксировать текущее состояние ресурса для последующего восстановления или клонирования: снимок диска сохраняет только данные выбранного диска, а снимок виртуальной машины включает в себя параметры ВМ и состояние всех её дисков.
+
+### Консистентные снимки
+
+Снимки могут быть консистентными и неконсистентными. За это отвечает параметр `requiredConsistency`, по умолчанию его значение равно `true`, что означает требование консистентного снимка.
+
+Консистентный снимок гарантирует согласованное и целостное состояние дисков виртуальной машины. Такой снимок можно создать при выполнении одного из следующих условий:
+
+- виртуальная машина выключена;
+- в гостевой системе установлен [`qemu-guest-agent`](#агент-гостевой-ос), который на момент создания снимка временно приостанавливает работу файловой системы для обеспечения её согласованности.
+
+QEMU Guest Agent поддерживает скрипты hooks, которые позволяют подготовить приложения к созданию снимка без остановки сервисов, обеспечивая согласованное состояние на уровне приложений. Подробнее о настройке скриптов hooks см. в разделе [«Агент гостевой ОС»](#агент-гостевой-ос).
+
+Неконсистентный снимок может не отражать согласованное состояние дисков виртуальной машины и её компонентов. Такой снимок создаётся в следующих случаях:
+
+- ВМ запущена, и в гостевой ОС не установлен или не запущен `qemu-guest-agent`;
+- в манифесте снимка явно указан параметр `requiredConsistency: false`, и требуется избежать приостановки работы файловой системы.
+
+{{< alert level="warning" >}}
+При восстановлении из такого снимка возможны проблемы с целостностью файловой системы, поскольку состояние данных может быть не согласовано.
+{{< /alert >}}
### Создание снимков дисков
@@ -2785,24 +2948,6 @@ EOF
Рекомендуется отключить все образы (VirtualImage/ClusterVirtualImage) от виртуальной машины перед созданием её снимка. Образы дисков не сохраняются вместе со снимком ВМ, и их отсутствие в кластере при восстановлении может привести к тому, что виртуальная машина не сможет запуститься и будет находиться в состоянии Pending, ожидая доступности образа.
{{< /alert >}}
-#### Типы снимков
-
-Снимки могут быть консистентными и неконсистентными, за это отвечает параметр `requiredConsistency`, по умолчанию его значение равно `true`, что означает требование консистентного снимка.
-
-Консистентный снимок гарантирует согласованное и целостное состояние дисков виртуальной машины. Такой снимок можно создать при выполнении одного из следующих условий:
-
-- Виртуальная машина выключена.
-- В гостевой системе установлен `qemu-guest-agent`, который на момент создания снимка временно приостанавливает работу файловой системы для обеспечения её согласованности.
-
-Неконсистентный снимок может не отражать согласованное состояние дисков виртуальной машины и её компонентов. Такой снимок создаётся в следующих случаях:
-
-- ВМ запущена, и в гостевой ОС не установлен или не запущен `qemu-guest-agent`.
-- ВМ запущена, и в гостевой ОС не установлен `qemu-guest-agent`, но в манифесте снимка указан параметр `requiredConsistency: false`, и хочется избежать приостановки работы файловой системы.
-
-{{< alert level="warning" >}}
-Существует риск потери данных или нарушения их целостности при восстановлении из такого снимка.
-{{< /alert >}}
-
#### Создание снимков
Создание снимка виртуальной машины будет неудачным, если выполнится хотя бы одно из следующих условий:
@@ -2875,7 +3020,6 @@ status:
Для восстановления ВМ из снимка используется ресурс `VirtualMachineOperation` с типом `restore`:
-
```yaml
apiVersion: virtualization.deckhouse.io/v1alpha2
kind: VirtualMachineOperation
@@ -2896,6 +3040,7 @@ spec:
- `BestEffort` — отсутствующие внешние зависимости (`ClusterVirtualImage`, `VirtualImage`) игнорируются и удаляются из конфигурации ВМ.
Восстановление виртуальной машины из снимка возможно только при выполнении всех следующих условий:
+
- Восстанавливаемая ВМ присутствует в кластере (ресурс `VirtualMachine` существует, а его `.metadata.uid` совпадает с идентификатором, использованным при создании снимка).
- Восстанавливаемые диски (определяются по имени) либо не подключены к другим ВМ, либо отсутствуют в кластере.
- Восстанавливаемый IP-адрес либо не занят другой ВМ, либо отсутствует в кластере.
@@ -2916,10 +3061,58 @@ d8 k get vmop -o json | jq '.status.resources'
Не рекомендуется отменять операцию восстановления (удалять ресурс `VirtualMachineOperation` в фазе `InProgress`) из снимка, так как это может привести к неконсистентному состоянию восстанавливаемой виртуальной машины.
{{< /alert >}}
+{{< alert level="info" >}}
+При восстановлении ВМ из снимка связанные с ней диски также восстанавливаются из соответствующих снимков, поэтому в спецификации диска будет указан параметр `dataSource` со ссылкой на нужный снимок диска.
+{{< /alert >}}
## Создание клона ВМ
-Клонирование ВМ выполняется с использованием ресурса `VirtualMachineOperation` с типом операции `clone`.
+Вы можете создать клон виртуальной машины двумя способами: либо на основании уже существующей ВМ, либо используя предварительно созданный снимок этой машины.
+
+{{< alert level="warning">}}
+Клону ВМ будет назначен новый IP-адрес для кластерной сети и MAC-адреса для дополнительных сетевых интерфейсов (если они есть), поэтому после клонирования потребуется перенастроить сетевые параметры гостевой ОС.
+{{< /alert >}}
+
+Клонирование создаёт копию ВМ, поэтому ресурсы новой ВМ должны иметь уникальные имена. Для этого используются параметры `nameReplacements` и/или `customization`:
+
+- `nameReplacements` — позволяет заменить имена существующих ресурсов на новые, чтобы избежать конфликтов.
+- `customization` — задает префикс или суффикс для имен всех клонируемых ресурсов ВМ (дисков, IP-адресов и т. д.).
+
+Пример конфигурации:
+
+```yaml
+nameReplacements:
+ - from:
+ kind:
+ name:
+ to:
+ name:
+customization:
+ namePrefix:
+ nameSuffix:
+```
+
+В результате будет создана ВМ с именем .
+
+Для операции клонирования возможно использовать один из трех режимов:
+
+- `DryRun` — тестовый запуск для проверки возможных конфликтов. Результаты отображаются в поле `status.resources` соответствующего ресурса операции.
+- `Strict` — строгий режим, требующий наличия всех ресурсов с новыми именами и их зависимостей (например, образов) в клонируемой ВМ.
+- `BestEffort` — режим, при котором отсутствующие внешние зависимости (например, ClusterVirtualImage, VirtualImage) автоматически удаляются из конфигурации клонируемой ВМ.
+
+Информацию о конфликтах, возникших при клонировании, можно просмотреть в статусе ресурса операции:
+
+```bash
+# Для клонирования из существующей ВМ.
+d8 k get vmop -o json | jq '.status.resources'
+
+# Для клонирования из снимка ВМ.
+d8 k get vmsop -o json | jq '.status.resources'
+```
+
+## Создание клона существующей ВМ
+
+Клонирование ВМ выполняется с использованием ресурса VirtualMachineOperation с типом операции `Clone`.
{{< alert level="warning">}}
Перед клонированием ВМ должна быть [выключена](#политика-запуска-и-управление-состоянием-вм).
@@ -2927,6 +3120,21 @@ d8 k get vmop -o json | jq '.status.resources'
Рекомендуется задавать параметр `.spec.runPolicy: AlwaysOff` в конфигурации клонируемой ВМ, чтобы предотвратить автоматический запуск клона ВМ. Это связано с тем, что клон наследует поведение родительской ВМ.
{{< /alert >}}
+Перед клонированием необходимо подготовить гостевую ОС, чтобы избежать конфликтов уникальных идентификаторов и сетевых настроек.
+
+Linux:
+
+- очистить `machine-id` с помощью команды `sudo truncate -s 0 /etc/machine-id` (для systemd) или удалить файл `/var/lib/dbus/machine-id`;
+- удалить SSH-ключи хоста: `sudo rm -f /etc/ssh/ssh_host_*`;
+- очистить конфигурации сетевых интерфейсов (если используются статические настройки);
+- очистить кэш Cloud-Init (если используется): `sudo cloud-init clean`.
+
+Windows:
+
+- выполнить генерализацию с помощью `sysprep` с параметром `/generalize` или использовать инструменты для очистки уникальных идентификаторов (SID, hostname и так далее).
+
+Пример создания клона ВМ:
+
```yaml
apiVersion: virtualization.deckhouse.io/v1alpha2
kind: VirtualMachineOperation
@@ -2941,59 +3149,104 @@ spec:
customization: {}
```
+Параметры `nameReplacements` и `customization` настраиваются в блоке `.spec.clone` (см. [общее описание](#создание-клона-вм) выше).
+
+{{< alert level="info" >}}
+В процессе клонирования для виртуальной машины и всех её дисков автоматически создаются временные снимки. Именно из этих снимков затем собирается новая ВМ. После завершения процесса клонирования временные снимки автоматически удаляются — их не будет видно в списке ресурсов. Однако внутри спецификации клонируемых дисков будет оставаться ссылка (`dataSource`) на соответствующий снимок, даже если самого снимка уже не существует. Это ожидаемое поведение и не свидетельствует о проблемах: такие ссылки корректны, потому что к моменту запуска клона все необходимые данные уже были перенесены на новые диски.
+{{< /alert >}}
+
+## Создание клона из снимка ВМ
+
+Клонирование ВМ из снимка выполняется с использованием ресурса VirtualMachineSnapshotOperation с типом операции `CreateVirtualMachine`.
+
+Пример создания клона ВМ из снимка:
+
+```yaml
+apiVersion: virtualization.deckhouse.io/v1alpha2
+kind: VirtualMachineSnapshotOperation
+metadata:
+ name:
+spec:
+ type: CreateVirtualMachine
+ virtualMachineSnapshotName:
+ createVirtualMachine:
+ mode: DryRun | Strict | BestEffort
+ nameReplacements: []
+ customization: {}
+```
+
+Параметры `nameReplacements` и `customization` настраиваются в блоке `.spec.createVirtualMachine` (см. [общее описание](#создание-клона-вм) выше).
+
+{{< alert level="info" >}}
+При клонировании ВМ из снимка связанные с ней диски также создаются из соответствующих снимков, поэтому в спецификации диска будет указан параметр `dataSource` с ссылкой на нужный снимок диска.
+{{< /alert >}}
+
+## Экспорт данных
+
+Экспортировать диски и снимки дисков виртуальных машин можно с помощью утилиты `d8` (версия 0.20.7 и выше). Для работы этой функции должен быть включен модуль [`storage-volume-data-manager`](/modules/storage-volume-data-manager/).
+
+{{< alert level="warning" >}}
+Диск не должен использоваться в момент экспорта. Если диск подключён к виртуальной машине, ВМ необходимо предварительно остановить.
+{{< /alert >}}
+Вы можете создать клон виртуальной машины двумя способами: либо на основании уже существующей ВМ, либо используя предварительно созданный снимок этой машины.
+
{{< alert level="warning">}}
Клонируемой ВМ будет назначен новый IP-адрес для кластерной сети и MAC-адреса для дополнительных сетевых интерфейсов (если они есть), поэтому после клонирования потребуется перенастроить сетевые параметры гостевой ОС.
{{< /alert >}}
-Клонирование создает копию существующей ВМ, поэтому ресурсы новой ВМ должны иметь уникальные имена. Для этого используются параметры `.spec.clone.nameReplacements` и/или `.spec.clone.customization`.
+Клонирование создает копию ВМ, поэтому ресурсы новой ВМ должны иметь уникальные имена. Для этого используются параметры `nameReplacements` и/или `customization`:
-- `.spec.clone.nameReplacements` — позволяет заменить имена существующих ресурсов на новые, чтобы избежать конфликтов.
-- `.spec.clone.customization` — задает префикс или суффикс для имен всех клонируемых ресурсов ВМ (дисков, IP-адресов и т. д.).
+- `nameReplacements` — позволяет заменить имена существующих ресурсов на новые, чтобы избежать конфликтов.
+- `customization` — задает префикс или суффикс для имен всех клонируемых ресурсов ВМ (дисков, IP-адресов и т. д.).
Пример конфигурации:
```yaml
-spec:
- clone:
- nameReplacements:
- - from:
- kind:
- name:
- - to:
- name:
- customization:
- namePrefix:
- nameSuffix:
+nameReplacements:
+ - from:
+ kind:
+ name:
+ to:
+ name:
+customization:
+ namePrefix:
+ nameSuffix:
```
-В результате будет создана ВМ с именем <префикс><новое имя><суффикс>.
+В результате будет создана ВМ с именем .
Для операции клонирования возможно использовать один из трех режимов:
-- `DryRun` — тестовый запуск для проверки возможных конфликтов. Результаты отображаются в поле `status.resources` ресурса VirtualMachineOperation.
+- `DryRun` — тестовый запуск для проверки возможных конфликтов. Результаты отображаются в поле `status.resources` соответствующего ресурса операции.
- `Strict` — строгий режим, требующий наличия всех ресурсов с новыми именами и их зависимостей (например, образов) в клонируемой ВМ.
- `BestEffort` — режим, при котором отсутствующие внешние зависимости (например, ClusterVirtualImage, VirtualImage) автоматически удаляются из конфигурации клонируемой ВМ.
-Информацию о конфликтах, возникших при клонировании, можно просмотреть в статусе ресурса:
+Информацию о конфликтах, возникших при клонировании, можно просмотреть в статусе ресурса операции:
```bash
+# Для клонирования из существующей ВМ.
d8 k get vmop -o json | jq '.status.resources'
+# Для клонирования из снимка ВМ.
+d8 k get vmsop -o json | jq '.status.resources'
```
-## Экспорт данных
-
-DVP позволяет экспортировать диски и снимки дисков виртуальных машин с использованием утилиты `d8` (версия 1.17 и выше).
+## Cоздание клона существующей ВМ
+Клонирование ВМ выполняется с использованием ресурса VirtualMachineOperation с типом операции `Clone`.
Пример: экспорт диска (выполняется на узле кластера):
```bash
-d8 download -n vd/ -o file.img
+d8 data download -n vd/ -o file.img
```
Пример: экспорт снимка диска (выполняется на узле кластера):
```bash
-d8 download -n vds/ -o file.img
+d8 data download -n vds/ -o file.img
```
-Для экспорта ресурсов за пределы кластера необходимо также использовать флаг `--publish`.
+Если вы выполняете экспорт данных не с узла кластера (например, с вашей локальной машины), используйте флаг `--publish`.
+
+{{< alert level="info" >}}
+Чтобы импортировать скачанный диск обратно в кластер, загрузите его как [образ](#загрузка-образа-из-командной-строки) или как [диск](#загрузка-диска-из-командной-строки).
+{{< /alert >}}
diff --git a/docs/images/livemigration-example-autoconverge.png b/docs/images/livemigration-example-autoconverge.png
new file mode 100644
index 0000000000..6fc16ea455
Binary files /dev/null and b/docs/images/livemigration-example-autoconverge.png differ
diff --git a/docs/images/livemigration-example-autoconverge.ru.png b/docs/images/livemigration-example-autoconverge.ru.png
new file mode 100644
index 0000000000..6fc16ea455
Binary files /dev/null and b/docs/images/livemigration-example-autoconverge.ru.png differ
diff --git a/docs/images/livemigration-example.png b/docs/images/livemigration-example.png
new file mode 100644
index 0000000000..1eb1632d0a
Binary files /dev/null and b/docs/images/livemigration-example.png differ
diff --git a/docs/images/livemigration-example.ru.png b/docs/images/livemigration-example.ru.png
new file mode 100644
index 0000000000..1eb1632d0a
Binary files /dev/null and b/docs/images/livemigration-example.ru.png differ