Ovirt console vv windows

Table of Contents

  • 1. Introduction
    • 1.1. Audience
    • 1.2. Supported Virtual Machine Operating Systems
    • 1.3. Virtual Machine Performance Parameters
    • 1.4. Installing Supporting Components on Client Machines
      • 1.4.1. Installing Console Components
  • 2. Installing Enterprise Linux Virtual Machines
    • 2.1. Creating a virtual machine
    • 2.2. Starting the Virtual Machine
      • 2.2.1. Starting a Virtual Machine
      • 2.2.2. Opening a console to a virtual machine
      • 2.2.3. Opening a Serial Console to a Virtual Machine
      • 2.2.4. Automatically Connecting to a Virtual Machine
    • 2.3. Enabling the Required Repositories
    • 2.4. Installing Guest Agents and Drivers
      • 2.4.1. oVirt Guest agents, tools, and drivers
      • 2.4.2. Installing the Guest Agents and Drivers on Enterprise Linux
  • 3. Installing Windows virtual machines
    • 3.1. Creating a virtual machine
    • 3.2. Starting the virtual machine using Run Once
      • 3.2.1. Installing Windows on VirtIO-optimized hardware
      • 3.2.2. Opening a console to a virtual machine
    • 3.3. Installing guest agents and drivers
      • 3.3.1. oVirt Guest agents, tools, and drivers
      • 3.3.2. Installing the guest agents, tools, and drivers on Windows
      • 3.3.3. Values for ADDLOCAL to customize virtio-win command-line installation
  • 4. Additional Configuration
    • 4.1. Configuring Operating Systems with osinfo
    • 4.2. Configuring Single Sign-On for Virtual Machines
      • 4.2.1. Configuring Single Sign-On for Enterprise Linux Virtual Machines Using IPA (IdM)
      • 4.2.2. Configuring single sign-on for Windows virtual machines
      • 4.2.3. Disabling Single Sign-on for Virtual Machines
    • 4.3. Configuring USB Devices
      • 4.3.1. Using USB Devices on a Windows Client
      • 4.3.2. Using USB Devices on a Enterprise Linux Client
    • 4.4. Configuring Multiple Monitors
      • 4.4.1. Configuring Multiple Displays for Enterprise Linux Virtual Machines
      • 4.4.2. Configuring Multiple Displays for Windows Virtual Machines
    • 4.5. Configuring Console Options
      • 4.5.1. Console Options
      • 4.5.2. Accessing Console Options
      • 4.5.3. SPICE Console Options
      • 4.5.4. VNC Console Options
      • 4.5.5. RDP Console Options
      • 4.5.6. Remote Viewer Options
    • 4.6. Configuring a Watchdog
      • 4.6.1. Adding a Watchdog Card to a Virtual Machine
      • 4.6.2. Installing a Watchdog
      • 4.6.3. Confirming Watchdog Functionality
      • 4.6.4. Parameters for Watchdogs in watchdog.conf
    • 4.7. Configuring Virtual NUMA
    • 4.8. Configuring Satellite errata viewing for a virtual machine
    • 4.9. Configuring Headless Virtual Machines
    • 4.10. Configuring High Performance Virtual Machines, Templates, and Pools
      • 4.10.1. Creating a High Performance Virtual Machine, Template, or Pool
      • 4.10.2. Configuring the Recommended Manual Settings
    • 4.11. Configuring the time zone
  • 5. Editing Virtual Machines
    • 5.1. Editing Virtual Machine Properties
    • 5.2. Network Interfaces
      • 5.2.1. Adding a New Network Interface
      • 5.2.2. Editing a Network Interface
      • 5.2.3. Hot Plugging a Network Interface
      • 5.2.4. Removing a Network Interface
      • 5.2.5. Configuring a virtual machine to ignore NICs
    • 5.3. Virtual Disks
      • 5.3.1. Adding a New Virtual Disk
      • 5.3.2. Attaching an Existing Disk to a Virtual Machine
      • 5.3.3. Extending the Available Size of a Virtual Disk
      • 5.3.4. Hot Plugging a Virtual Disk
      • 5.3.5. Removing a Virtual Disk from a Virtual Machine
      • 5.3.6. Importing a Disk Image from an Imported Storage Domain
      • 5.3.7. Importing an Unregistered Disk Image from an Imported Storage Domain
    • 5.4. Virtual Memory
      • 5.4.1. Hot Plugging Virtual Memory
      • 5.4.2. Hot Unplugging Virtual Memory
    • 5.5. Hot Plugging vCPUs
    • 5.6. Pinning a Virtual Machine to Multiple Hosts
    • 5.7. Viewing Virtual Machines Pinned to a Host
    • 5.8. Changing the CD for a Virtual Machine
    • 5.9. Smart Card Authentication
  • 6. Administrative Tasks
    • 6.1. Shutting Down a Virtual Machine
    • 6.2. Suspending a Virtual Machine
    • 6.3. Rebooting or Resetting a Virtual Machine
    • 6.4. Removing a Virtual Machine
    • 6.5. Cloning a Virtual Machine
    • 6.6. Updating Virtual Machine Guest Agents and Drivers
      • 6.6.1. Updating the Guest Agents and Drivers on Enterprise Linux
      • 6.6.2. Updating Windows drivers with Windows Update
      • 6.6.3. Updating Windows guest agents and drivers using the command prompt
    • 6.7. Viewing Red Hat Satellite Errata for a Virtual Machine
    • 6.8. Virtual Machines and Permissions
      • 6.8.1. Managing System Permissions for a Virtual Machine
      • 6.8.2. Virtual Machine Administrator Roles Explained
      • 6.8.3. Virtual Machine User Roles Explained
      • 6.8.4. Assigning Virtual Machines to Users
      • 6.8.5. Removing Access to Virtual Machines from Users
    • 6.9. Snapshots
      • 6.9.1. Creating a Snapshot of a Virtual Machine
      • 6.9.2. Using a Snapshot to Restore a Virtual Machine
      • 6.9.3. Creating a Virtual Machine from a Snapshot
      • 6.9.4. Deleting a Snapshot
    • 6.10. Host Devices
      • 6.10.1. Adding a Host Device to a Virtual Machine
      • 6.10.2. Removing Host Devices from a Virtual Machine
      • 6.10.3. Pinning a Virtual Machine to Another Host
      • 6.10.4. NVDIMM host devices
    • 6.11. Affinity Groups
      • 6.11.1. Affinity Groups
      • 6.11.2. Creating an Affinity Group
      • 6.11.3. Editing an Affinity Group
      • 6.11.4. Removing an Affinity Group
      • 6.11.5. Affinity Groups Examples
      • 6.11.6. Affinity Groups Troubleshooting
    • 6.12. Affinity Labels
      • 6.12.1. About Affinity Labels
      • 6.12.2. Creating an Affinity Label
      • 6.12.3. Editing an Affinity Label
      • 6.12.4. Deleting an Affinity Label
    • 6.13. Exporting and Importing Virtual Machines and Templates
      • 6.13.1. Exporting a Virtual Machine to the Export Domain
      • 6.13.2. Exporting a Virtual Machine to a Data Domain
      • 6.13.3. Importing a Virtual Machine from the Export Domain
      • 6.13.4. Importing a Virtual Machine from a Data Domain
      • 6.13.5. Importing a Virtual Machine from a VMware Provider
      • 6.13.6. Exporting a Virtual Machine to a Host
      • 6.13.7. Importing a Virtual Machine from a Host
      • 6.13.8. Importing a virtual machine from a RHEL 5 Xen host
      • 6.13.9. Importing a Virtual Machine from a KVM Host
      • 6.13.10. Importing a Red Hat KVM Guest Image
    • 6.14. Migrating Virtual Machines Between Hosts
      • 6.14.1. Live Migration Prerequisites
      • 6.14.2. Configuring Virtual Machines with SR-IOV-Enabled vNICs to Reduce Network Outage during Migration
      • 6.14.3. Configuring Virtual Machines with SR-IOV-Enabled vNICs with minimal downtime
      • 6.14.4. Optimizing Live Migration
      • 6.14.5. Guest Agent Hooks
      • 6.14.6. Automatic Virtual Machine Migration
      • 6.14.7. Preventing Automatic Migration of a Virtual Machine
      • 6.14.8. Manually Migrating Virtual Machines
      • 6.14.9. Setting Migration Priority
      • 6.14.10. Canceling Ongoing Virtual Machine Migrations
      • 6.14.11. Event and Log Notification upon Automatic Migration of Highly Available Virtual Servers
    • 6.15. Improving Uptime with Virtual Machine High Availability
      • 6.15.1. What is High Availability?
      • 6.15.2. High Availability Considerations
      • 6.15.3. Configuring a Highly Available Virtual Machine
    • 6.16. Other Virtual Machine Tasks
      • 6.16.1. Enabling SAP Monitoring
      • 6.16.2. Configuring Enterprise Linux 5.4 and later Virtual Machines to use SPICE
      • 6.16.3. KVM Virtual Machine Timing Management
      • 6.16.4. Adding a Trusted Platform Module device
  • 7. Templates
    • 7.1. About Templates
    • 7.2. Sealing Virtual Machines in Preparation for Deployment as Templates
      • 7.2.1. Sealing a Linux Virtual Machine for Deployment as a Template
      • 7.2.2. Sealing a Windows Virtual Machine for Deployment as a Template
    • 7.3. Creating a Template
    • 7.4. Editing a Template
    • 7.5. Deleting a Template
    • 7.6. Exporting Templates
      • 7.6.1. Migrating Templates to the Export Domain
      • 7.6.2. Copying a Template’s Virtual Hard Disk
    • 7.7. Importing Templates
      • 7.7.1. Importing a Template into a Data Center
      • 7.7.2. Importing a Virtual Disk from an OpenStack Image Service as a Template
    • 7.8. Templates and Permissions
      • 7.8.1. Managing System Permissions for a Template
      • 7.8.2. Template Administrator Roles Explained
      • 7.8.3. Assigning an Administrator or User Role to a Resource
      • 7.8.4. Removing an Administrator or User Role from a Resource
    • 7.9. Using Cloud-Init to Automate the Configuration of Virtual Machines
      • 7.9.1. Cloud-Init Use Case Scenarios
      • 7.9.2. Installing Cloud-Init
      • 7.9.3. Using Cloud-Init to Prepare a Template
      • 7.9.4. Using Cloud-Init to Initialize a Virtual Machine
    • 7.10. Using Sysprep to Automate the Configuration of Virtual Machines
      • 7.10.1. Configuring Sysprep on a Template
      • 7.10.2. Using Sysprep to Initialize a Virtual Machine
    • 7.11. Creating a Virtual Machine Based on a Template
    • 7.12. Creating a Cloned Virtual Machine Based on a Template
  • Appendix A: Reference: Settings in Administration Portal and VM Portal Windows
    • Explanation of Settings in the New Virtual Machine and Edit Virtual Machine Windows
      • Virtual Machine General Settings Explained
      • Virtual Machine System Settings Explained
      • Virtual Machine Initial Run Settings Explained
      • Virtual Machine Console Settings Explained
      • Virtual Machine Host Settings Explained
      • Virtual Machine High Availability Settings Explained
      • Virtual Machine Resource Allocation Settings Explained
      • Virtual Machine Boot Options Settings Explained
      • Virtual Machine Random Generator Settings Explained
      • Virtual Machine Custom Properties Settings Explained
      • Virtual Machine Icon Settings Explained
      • Virtual Machine Foreman/Satellite Settings Explained
    • Explanation of settings in the Run Once window
    • Explanation of Settings in the New Network Interface and Edit Network Interface Windows
    • Explanation of settings in the New Virtual Disk and Edit Virtual Disk windows
    • Explanation of Settings in the New Template Window
  • Appendix B: virt-sysprep Operations
  • Appendix C: Legal notice

1. Introduction

A virtual machine is a software implementation of a computer. The oVirt environment enables you to create virtual desktops and virtual servers.

Virtual machines consolidate computing tasks and workloads. In traditional computing environments, workloads usually run on individually administered and upgraded servers. Virtual machines reduce the amount of hardware and administration required to run the same computing tasks and workloads.

1.1. Audience

Most virtual machine tasks in oVirt can be performed in both the VM Portal and Administration Portal. However, the user interface differs between each portal, and some administrative tasks require access to the Administration Portal. Tasks that can only be performed in the Administration Portal will be described as such in this book. Which portal you use, and which tasks you can perform in each portal, is determined by your level of permissions. Virtual machine permissions are explained in Virtual Machines and Permissions.

The Administration Portal’s user interface is described in the Administration Guide.

The creation and management of virtual machines through the oVirt REST API is documented in the REST API Guide.

1.2. Supported Virtual Machine Operating Systems

1.3. Virtual Machine Performance Parameters

1.4. Installing Supporting Components on Client Machines

1.4.1. Installing Console Components

A console is a graphical window that allows you to view the start up screen, shut down screen, and desktop of a virtual machine, and to interact with that virtual machine in a similar way to a physical machine. In oVirt, the default application for opening a console to a virtual machine is Remote Viewer, which must be installed on the client machine prior to use.

Installing Remote Viewer on Enterprise Linux

The Remote Viewer application provides users with a graphical console for connecting to virtual machines. Once installed, it is called automatically when attempting to open a SPICE session with a virtual machine. Alternatively, it can also be used as a standalone application. Remote Viewer is included in the virt-viewer package provided by the base Enterprise Linux Workstation and Enterprise Linux Server repositories.

Procedure

  1. Install the virt-viewer package:

    # dnf install virt-viewer
  2. Restart your browser for the changes to take effect.

You can now connect to your virtual machines using either the SPICE protocol or the VNC protocol.

Installing Remote Viewer on Windows

The Remote Viewer application provides users with a graphical console for connecting to virtual machines. Once installed, it is called automatically when attempting to open a SPICE session with a virtual machine. Alternatively, it can also be used as a standalone application.

Installing Remote Viewer on Windows

  1. Open a web browser and download one of the following installers according to the architecture of your system.

    • Virt Viewer download page

  2. Open the folder where the file was saved.

  3. Double-click the file.

  4. Click Run if prompted by a security warning.

  5. Click Yes if prompted by User Account Control.

Remote Viewer is installed and can be accessed via Remote Viewer in the VirtViewer folder of All Programs in the start menu.

Installing usbdk on Windows

usbdk is a driver that enables remote-viewer exclusive access to USB devices on Windows operating systems. Installing usbdk requires Administrator privileges. Note that the previously supported USB Clerk option has been deprecated and is no longer supported.

Installing usbdk on Windows

  1. Open a web browser and download one of the following installers according to the architecture of your system.

    • usbdk download page

  2. Open the folder where the file was saved.

  3. Double-click the file.

  4. Click Run if prompted by a security warning.

  5. Click Yes if prompted by User Account Control.

2. Installing Enterprise Linux Virtual Machines

Installing a Enterprise Linux virtual machine involves the following key steps:

  1. Create a virtual machine. You must add a virtual disk for storage, and a network interface to connect the virtual machine to the network.

  2. Start the virtual machine and install an operating system. See your operating system’s documentation for instructions.

    • Enterprise Linux 6: Installing Red Hat Enterprise Linux 6.9 for all architectures

    • Enterprise Linux 7: Installing Red Hat Enterprise Linux 7 on all architectures

    • Enterprise Linux Atomic Host 7: Red Hat Enterprise Linux Atomic Host 7 Installation and Configuration Guide

    • Enterprise Linux 8: Installing Red Hat Enterprise Linux 8 using the graphical user interface

  3. Enable the required repositories for your operating system.

  4. Install guest agents and drivers for additional virtual machine functionality.

2.1. Creating a virtual machine

When creating a new virtual machine, you specify its settings. You can edit some of these settings later, including the chipset and BIOS type. For more information, see UEFI and the Q35 chipset in the Administration Guide.
.Prerequisites

Before you can use this virtual machine, you must:

  • Install an operating system

    • Use a pre-installed image by Creating a Cloned Virtual Machine Based on a Template

    • Use a pre-installed image from an attached pre-installed Disk

    • Install an operating system through the PXE boot menu or from an ISO file

  • Register with the Content Delivery Network

Procedure

  1. Click .

  2. Click New. This opens the New Virtual Machine window.

  3. Select an Operating System from the drop-down list.

    If you selected Enterprise Linux CoreOS as the operating system, you may need to set the initialization method by configuring Ignition settings in the Advanced Options Initial Run tab. See Configuring Ignition.

  4. Enter a Name for the virtual machine.

  5. Add storage to the virtual machine: under Instance Images, click Attach or Create to select or create a virtual disk .

    • Click Attach and select an existing virtual disk.

      or

    • Click Create and enter a Size(GB) and Alias for a new virtual disk. You can accept the default settings for all other fields, or change them if required. See Explanation of settings in the New Virtual Disk and Edit Virtual Disk windows for more details on the fields for all disk types.

  6. Connect the virtual machine to the network. Add a network interface by selecting a vNIC profile from the nic1 drop-down list at the bottom of the General tab.

  7. Specify the virtual machine’s Memory Size on the System tab.

  8. In the Boot Options tab, choose the First Device that the virtual machine will use to boot.

  9. You can accept the default settings for all other fields, or change them if required. For more details on all fields in the New Virtual Machine window, see Explanation of settings in the New Virtual Machine and Edit Virtual Machine Windows.

  10. Click OK.

The new virtual machine is created and displays in the list of virtual machines with a status of Down.

Configuring Ignition

Ignition is the utility that is used by Enterprise Linux CoreOS to manipulate disks during initial configuration. It completes common disk tasks, including partitioning disks, formatting partitions, writing files, and configuring users. On first boot, Ignition reads its configuration from the installation media or the location that you specify and applies the configuration to the machines.

Once Ignition has been configured as the initialization method, it cannot be reversed or re-configured.

  1. In the Add Virtual Machine or Edit Virtual Machine screen, click Show Advanced Options.

  2. In the Initial Run tab, select the Ignition 2.3.0 option and enter the VM Hostname.

  3. Expand the Authorization option, enter a hashed (SHA-512) password, and enter the password again to verify.

  4. If you are using SSH keys for authorization, enter them in the space provided.

  5. You can also enter a custom Ignition script in JSON format in the Ignition Script field. This script will run on the virtual machine when it starts. The scripts you enter in this field are custom JSON sections that are added to those produced by the Engine, and allow you to use custom Ignition instructions.

    If the Enterprise Linux CoreOS image you are using contains an Ignition version different than 2.3.0, you need to use a script in the Ignition Script field to enforce the Ignition version included in your Enterprise Linux CoreOS image.

    When you use an Ignition script, the script instructions take precedence over and override any conflicting Ignition settings you configured in the UI.

2.2. Starting the Virtual Machine

2.2.1. Starting a Virtual Machine

Procedure

  1. Click and select a virtual machine with a status of Down.

  2. Click Run.

The Status of the virtual machine changes to Up, and the operating system installation begins. Open a console to the virtual machine if one does not open automatically.

A virtual machine will not start on a host with an overloaded CPU. By default, a host’s CPU is considered overloaded if it has a load of more than 80% for 5 minutes, but these values can be changed using scheduling policies. See Scheduling Policies in the Administration Guide for more information.

Troubleshooting

Scenario — the virtual machine fails to boot with the following error message:

Boot failed: not a bootable disk - No Bootable device

Possible solutions to this problem:

  • Make sure that hard disk is selected in the boot sequence, and the disk that the virtual machine is booting from must be set as Bootable.

  • Create a Cloned Virtual Machine Based on a Template.

  • Create a new virtual machine with a local boot disk managed by oVirt that contains the OS and application binaries.

  • Install the OS by booting from the Network (PXE) boot option.

Scenario — the virtual machine on IBM POWER9 fails to boot with the following error message:

qemu-kvm: Requested count cache flush assist capability level not supported by kvm, try appending -machine cap-ccf-assist=off

Default risk level protections can prevent VMs from starting on IBM POWER9. To resolve this issue:

  1. Create or edit the /var/lib/obmc/cfam_overrides on the BMC.

  2. Set the firmware risk level to 0:

    # Control speculative execution mode
    0 0x283a 0x00000000  # bits 28:31 are used for init level -- in this case 0 Kernel and User protection (safest, default)
    0 0x283F 0x20000000  # Indicate override register is valid
  3. Reboot the host system for the changes to take affect.

Overriding the risk level can cause unexpected behavior when running virtual machines.

2.2.2. Opening a console to a virtual machine

Use Remote Viewer to connect to a virtual machine.

To allow other users to connect to the VM, make sure you shutdown and restart the virtual machine when you are finished using the console. Alternatively, the administrator can Disable strict user checking to eliminate the need for reboot between users. See Virtual Machine Console Settings Explained for more information.

Procedure

  1. Install Remote Viewer if it is not already installed. See Installing Console Components.

  2. Click and select a virtual machine.

  3. Click Console. By default, the browser prompts you to download a file named console.vv. When you click to open the file, a console window opens for the virtual machine. You can configure your browser to automatically open these files, such that clicking Console simply opens the console.

console.vv expires after 120 seconds. If more than 120 seconds elapse between the time the file is downloaded and the time that you open the file, click Console again.

2.2.3. Opening a Serial Console to a Virtual Machine

You can access a virtual machine’s serial console from the command line instead of opening a console from the Administration Portal or the VM Portal. The serial console is emulated through VirtIO channels, using SSH and key pairs. The Engine acts as a proxy for the connection, provides information about virtual machine placement, and stores the authentication keys. You can add public keys for each user from either the Administration Portal or the VM Portal. You can access serial consoles for only those virtual machines for which you have appropriate permissions.

To access the serial console of a virtual machine, the user must have UserVmManager, SuperUser, or UserInstanceManager permission on that virtual machine. These permissions must be explicitly defined for each user. It is not enough to assign these permissions to Everyone.

The serial console is accessed through TCP port 2222 on the Engine. This port is opened during engine-setup on new installations. To change the port, see ovirt-vmconsole/README.md.

You must configure the following firewall rules to allow a serial console:

  • Rule «M3» for the Engine firewall

  • Rule «H2» for the host firewall

The serial console relies on the ovirt-vmconsole package and the ovirt-vmconsole-proxy on the Engine and the ovirt-vmconsole package and the ovirt-vmconsole-host package on the hosts.

These packages are installed by default on new installations. To install the packages on existing installations, reinstall the hosts.

Enabling a Virtual Machine’s Serial Console

  1. On the virtual machine whose serial console you are accessing, add the following lines to /etc/default/grub:

    GRUB_CMDLINE_LINUX_DEFAULT="console=tty0 console=ttyS0,115200n8"
    GRUB_TERMINAL="console serial"
    GRUB_SERIAL_COMMAND="serial --speed=115200 --unit=0 --word=8 --parity=no --stop=1"

    GRUB_CMDLINE_LINUX_DEFAULT applies this configuration only to the default menu entry. Use GRUB_CMDLINE_LINUX to apply the configuration to all the menu entries.

    If these lines already exist in /etc/default/grub, update them. Do not duplicate them.

  2. Rebuild /boot/grub2/grub.cfg:

    • BIOS-based machines:

      # grub2-mkconfig -o /boot/grub2/grub.cfg
    • UEFI-based machines:

      # grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg
  3. On the client machine from which you are accessing the virtual machine serial console, generate an SSH key pair. The Engine supports standard SSH key types, for example, an RSA key:

    # ssh-keygen -t rsa -b 2048 -f .ssh/serialconsolekey

    This command generates a public key and a private key.

  4. In the Administration Portal, click or click the user icon on the header bar and click Account Settings to open the Account Settings screen.

    OR

    In the VM Portal, click the Settings icon on the header bar to open the Account Settings screen.

  5. In the User’s Public Key text field (Administration Portal) or SSH Key field (VM Portal), paste the public key of the client machine that will be used to access the serial console.

  6. Click and select a virtual machine.

  7. Click Edit.

  8. In the Console tab of the Edit Virtual Machine window, select the Enable VirtIO serial console check box.

Connecting to a Virtual Machine’s Serial Console

On the client machine, connect to the virtual machine’s serial console:

  • If a single virtual machine is available, this command connects the user to that virtual machine:

    # ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN -i .ssh/serialconsolekey
    Enterprise Linux Server release 6.7 (Santiago)
    Kernel 2.6.32-573.3.1.el6.x86_64 on an x86_64
    USER login:
  • If more than one virtual machine is available, this command lists the available virtual machines and their IDs:

    # ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN -i .ssh/serialconsolekey list
    1. vm1 [vmid1]
    2. vm2 [vmid2]
    3. vm3 [vmid3]
    > 2
    Enterprise Linux Server release 6.7 (Santiago)
    Kernel 2.6.32-573.3.1.el6.x86_64 on an x86_64
    USER login:

    Enter the number of the machine to which you want to connect, and press Enter.

  • Alternatively, connect directly to a virtual machine using its unique identifier or its name:

    # ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN connect --vm-id vmid1
    # ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN connect --vm-name vm1

Disconnecting from a Virtual Machine’s Serial Console

Press any key followed by ~ . to close a serial console session.

If the serial console session is disconnected abnormally, a TCP timeout occurs. You will be unable to reconnect to the virtual machine’s serial console until the timeout period expires.

2.2.4. Automatically Connecting to a Virtual Machine

Once you have logged in, you can automatically connect to a single running virtual machine. This can be configured in the VM Portal.

Procedure

  1. In the Virtual Machines page, click the name of the virtual machine to go to the details view.

  2. Click the pencil icon beside Console and set Connect automatically to ON.

The next time you log into the VM Portal, if you have only one running virtual machine, you will automatically connect to that machine.

2.3. Enabling the Required Repositories

To install packages signed by Red Hat you must register the target system to the Content Delivery Network. Then, use an entitlement from your subscription pool and enable the required repositories.

Enabling the Required Repositories Using Subscription Engine

  1. Register your system with the Content Delivery Network, entering your Customer Portal user name and password when prompted:

    # subscription-manager register
  2. Locate the relevant subscription pools and note down the pool identifiers:

    # subscription-manager list --available
  3. Use the pool identifiers to attach the required subscriptions:

    # subscription-manager attach --pool=pool_id
  4. When a system is attached to a subscription pool with multiple repositories, only the main repository is enabled by default. Others are available, but disabled. Enable any additional repositories:

    # subscription-manager repos --enable=repository
  5. Ensure that all packages currently installed are up to date:

2.4. Installing Guest Agents and Drivers

2.4.1. oVirt Guest agents, tools, and drivers

The oVirt guest agents, tools, and drivers provide additional functionality for virtual machines, such as gracefully shutting down or rebooting virtual machines from the VM Portal and Administration Portal. The tools and agents also provide information for virtual machines, including:

  • Resource usage

  • IP addresses

The guest agents, tools and drivers are distributed as an ISO file that you can attach to virtual machines. This ISO file is packaged as an RPM file that you can install and upgrade from the Engine machine.

You need to install the guest agents and drivers on a virtual machine to enable this functionality for that machine.

Table 1. oVirt Guest drivers

Driver Description Works on

virtio-net

Paravirtualized network driver provides enhanced performance over emulated devices like rtl.

Server and Desktop.

virtio-block

Paravirtualized HDD driver offers increased I/O performance over emulated devices like IDE by optimizing the coordination and communication between the virtual machine and the hypervisor. The driver complements the software implementation of the virtio-device used by the host to play the role of a hardware device.

Server and Desktop.

virtio-scsi

Paravirtualized iSCSI HDD driver offers similar functionality to the virtio-block device, with some additional enhancements. In particular, this driver supports adding hundreds of devices, and names devices using the standard SCSI device naming scheme.

Server and Desktop.

virtio-serial

Virtio-serial provides support for multiple serial ports. The improved performance is used for fast communication between the virtual machine and the host that avoids network complications. This fast communication is required for the guest agents and for other features such as clipboard copy-paste between the virtual machine and the host and logging.

Server and Desktop.

virtio-balloon

Virtio-balloon is used to control the amount of memory a virtual machine actually accesses. It offers improved memory overcommitment.

Server and Desktop.

qxl

A paravirtualized display driver reduces CPU usage on the host and provides better performance through reduced network bandwidth on most workloads.

Server and Desktop.

Table 2. oVirt Guest agents and tools

Guest agent/tool Description Works on

qemu-guest-agent

Used instead of ovirt-guest-agent-common on Enterprise Linux 8 virtual machines. It is installed and enabled by default.

Server and Desktop.

spice-agent

The SPICE agent supports multiple monitors and is responsible for client-mouse-mode support to provide a better user experience and improved responsiveness than the QEMU emulation. Cursor capture is not needed in client-mouse-mode. The SPICE agent reduces bandwidth usage when used over a wide area network by reducing the display level, including color depth, disabling wallpaper, font smoothing, and animation. The SPICE agent enables clipboard support allowing cut and paste operations for both text and images between client and virtual machine, and automatic guest display setting according to client-side settings. On Windows-based virtual machines, the SPICE agent consists of vdservice and vdagent.

Server and Desktop.

2.4.2. Installing the Guest Agents and Drivers on Enterprise Linux

The oVirt guest agents and drivers are provided by the oVirt Agent repository.

Enterprise Linux 8 virtual machines use the qemu-guest-agent service, which is installed and enabled by default, instead of the ovirt-guest-agent service. If you need to manually install the guest agent on RHEL 8, follow the procedure below.

Procedure

  1. Log in to the Enterprise Linux virtual machine.

  2. Enable the oVirt Agent repository:

    • For Enterprise Linux 6

    • For CentOS Linux 7

      # yum install -y centos-release-ovirt43
    • For Red Hat Enterprise Linux 7

      # subscription-manager repos --enable=rhel-7-server-rh-common-rpms
    • For Enterprise Linux 8 and 9 the AppStream repository is enabled by default

  3. Install the guest agent and dependencies:

    • For Enterprise Linux 6 or 7, install the ovirt guest agent:

      # yum install ovirt-guest-agent-common
    • For Enterprise Linux 8 and 9, install the qemu guest agent:

      # yum install qemu-guest-agent
  4. Start and enable the ovirt-guest-agent service:

    • For Enterprise Linux 6

      # service ovirt-guest-agent start
      # chkconfig ovirt-guest-agent on
    • For Enterprise Linux 7

      # systemctl start ovirt-guest-agent
      # systemctl enable ovirt-guest-agent
  5. Start and enable the qemu-guest-agent service:

    • For Enterprise Linux 6

      # service qemu-ga start
      # chkconfig qemu-ga on
    • For Enterprise Linux 7, 8 or 9

      # systemctl start qemu-guest-agent
      # systemctl enable qemu-guest-agent

The guest agent now passes usage information to the oVirt Engine. You can configure the oVirt guest agent in the /etc/ovirt-guest-agent.conf file.

3. Installing Windows virtual machines

Installing a Windows virtual machine involves the following key steps:

  1. Create a blank virtual machine on which to install an operating system.

  2. Add a virtual disk for storage.

  3. Add a network interface to connect the virtual machine to the network.

  4. Attach the Windows guest tools CD to the virtual machine so that VirtIO-optimized device drivers can be installed during the operating system installation.

  5. Install a Windows operating system on the virtual machine. See your operating system’s documentation for instructions.

  6. During the installation, install guest agents and drivers for additional virtual machine functionality.

When all of these steps are complete, the new virtual machine is functional and ready to perform tasks.

3.1. Creating a virtual machine

When creating a new virtual machine, you specify its settings. You can edit some of these settings later, including the chipset and BIOS type. For more information, see UEFI and the Q35 chipset in the Administration Guide.
.Prerequisites

Before you can use this virtual machine, you must:

  • Install an operating system

  • Install a VirtIO-optimized disk and network drivers

Procedure

  1. You can change the default virtual machine name length with the engine-config tool. Run the following command on the Engine machine:

    # engine-config --set MaxVmNameLength=integer
  2. Click .

  3. Click New. This opens the New Virtual Machine window.

  4. Select an Operating System from the drop-down list.

  5. Enter a Name for the virtual machine.

  6. Add storage to the virtual machine: under Instance Images, click Attach or Create to select or create a virtual disk .

    • Click Attach and select an existing virtual disk.

      or

    • Click Create and enter a Size(GB) and Alias for a new virtual disk. You can accept the default settings for all other fields, or change them if required. See Explanation of settings in the New Virtual Disk and Edit Virtual Disk windows for more details on the fields for all disk types.

  7. Connect the virtual machine to the network. Add a network interface by selecting a vNIC profile from the nic1 drop-down list at the bottom of the General tab.

  8. Specify the virtual machine’s Memory Size on the System tab.

  9. In the Boot Options tab, choose the First Device that the virtual machine will use to boot.

  10. You can accept the default settings for all other fields, or change them if required. For more details on all fields in the New Virtual Machine window, see Explanation of settings in the New Virtual Machine and Edit Virtual Machine Windows.

  11. Click OK.

The new virtual machine is created and displays in the list of virtual machines with a status of Down.

3.2. Starting the virtual machine using Run Once

3.2.1. Installing Windows on VirtIO-optimized hardware

Install VirtIO-optimized disk and network device drivers during your Windows installation by attaching the virtio-win_version.iso file to your virtual machine. These drivers provide a performance improvement over emulated device drivers.

Use the Run Once option to attach the virtio-win_version.iso file in a one-off boot different from the Boot Options defined in the New Virtual Machine window.

Prerequisites

The following items were added to the virtual machine:

  • A Red Hat VirtIO network interface

  • A disk that uses the VirtIO interface

You can upload virtio-win_version.iso to a data storage domain.

oVirt recommends uploading ISO images to the data domain with the Administration Portal or with the REST API. For more information, see Uploading Images to a Data Storage Domain in the Administration Guide.

If necessary, you can upload the virtio-win ISO file to an ISO storage domain that is hosted on the Engine. The ISO storage domain type is deprecated. For more information, see Uploading images to an ISO domain in the Administration Guide.

Procedure

To install the virtio-win drivers when installing Windows, complete the following steps:

  1. Click and select a virtual machine.

  2. Click .

  3. Expand the Boot Options menu.

  4. Select the Attach CD check box, and select a Windows ISO from the drop-down list.

  5. Select the Attach Windows guest tools CD check box.

  6. Move CD-ROM to the top of the Boot Sequence field.

  7. Configure other Run Once options as required. See Virtual Machine Run Once settings explained for more details.

  8. Click OK. The status of the virtual machine changes to Up, and the operating system installation begins.

    Open a console to the virtual machine if one does not open automatically during the Windows installation.

  9. When prompted to select a drive onto which you want to install Windows, click Load driver and OK.

  10. Under Select the driver to install, select the appropriate driver for the version of Windows. For example, for Windows Server 2019, select Red Hat VirtIO SCSI controller (E:\amd64\2k19\viostor.inf)

  11. Click Next.

The rest of the installation proceeds as normal.

3.2.2. Opening a console to a virtual machine

Use Remote Viewer to connect to a virtual machine.

To allow other users to connect to the VM, make sure you shutdown and restart the virtual machine when you are finished using the console. Alternatively, the administrator can Disable strict user checking to eliminate the need for reboot between users. See Virtual Machine Console Settings Explained for more information.

Procedure

  1. Install Remote Viewer if it is not already installed. See Installing Console Components.

  2. Click and select a virtual machine.

  3. Click Console. By default, the browser prompts you to download a file named console.vv. When you click to open the file, a console window opens for the virtual machine. You can configure your browser to automatically open these files, such that clicking Console simply opens the console.

console.vv expires after 120 seconds. If more than 120 seconds elapse between the time the file is downloaded and the time that you open the file, click Console again.

3.3. Installing guest agents and drivers

3.3.1. oVirt Guest agents, tools, and drivers

The oVirt guest agents, tools, and drivers provide additional functionality for virtual machines, such as gracefully shutting down or rebooting virtual machines from the VM Portal and Administration Portal. The tools and agents also provide information for virtual machines, including:

  • Resource usage

  • IP addresses

The guest agents, tools and drivers are distributed as an ISO file that you can attach to virtual machines. This ISO file is packaged as an RPM file that you can install and upgrade from the Engine machine.

You need to install the guest agents and drivers on a virtual machine to enable this functionality for that machine.

Table 3. oVirt Guest drivers

Driver Description Works on

virtio-net

Paravirtualized network driver provides enhanced performance over emulated devices like rtl.

Server and Desktop.

virtio-block

Paravirtualized HDD driver offers increased I/O performance over emulated devices like IDE by optimizing the coordination and communication between the virtual machine and the hypervisor. The driver complements the software implementation of the virtio-device used by the host to play the role of a hardware device.

Server and Desktop.

virtio-scsi

Paravirtualized iSCSI HDD driver offers similar functionality to the virtio-block device, with some additional enhancements. In particular, this driver supports adding hundreds of devices, and names devices using the standard SCSI device naming scheme.

Server and Desktop.

virtio-serial

Virtio-serial provides support for multiple serial ports. The improved performance is used for fast communication between the virtual machine and the host that avoids network complications. This fast communication is required for the guest agents and for other features such as clipboard copy-paste between the virtual machine and the host and logging.

Server and Desktop.

virtio-balloon

Virtio-balloon is used to control the amount of memory a virtual machine actually accesses. It offers improved memory overcommitment.

Server and Desktop.

qxl

A paravirtualized display driver reduces CPU usage on the host and provides better performance through reduced network bandwidth on most workloads.

Server and Desktop.

Table 4. oVirt Guest agents and tools

Guest agent/tool Description Works on

qemu-guest-agent

Used instead of ovirt-guest-agent-common on Enterprise Linux 8 virtual machines. It is installed and enabled by default.

Server and Desktop.

spice-agent

The SPICE agent supports multiple monitors and is responsible for client-mouse-mode support to provide a better user experience and improved responsiveness than the QEMU emulation. Cursor capture is not needed in client-mouse-mode. The SPICE agent reduces bandwidth usage when used over a wide area network by reducing the display level, including color depth, disabling wallpaper, font smoothing, and animation. The SPICE agent enables clipboard support allowing cut and paste operations for both text and images between client and virtual machine, and automatic guest display setting according to client-side settings. On Windows-based virtual machines, the SPICE agent consists of vdservice and vdagent.

Server and Desktop.

3.3.2. Installing the guest agents, tools, and drivers on Windows

Procedure

To install the guest agents, tools, and drivers on a Windows virtual machine, complete the following steps:

  1. On the Engine machine, install the virtio-win package:

    # dnf install virtio-win*

    After you install the package, the ISO file is located in /usr/share/virtio-win/virtio-win_version.iso on the Engine machine.

  2. Upload virtio-win_version.iso to a data storage domain. See Uploading Images to a Data Storage Domain in the Administration Guide for details.

  3. In the Administration or VM Portal, if the virtual machine is running, use the Change CD button to attach the virtio-win_version.iso file to each of your virtual machines. If the virtual machine is powered off, click the Run Once button and attach the ISO as a CD.

  4. Log in to the virtual machine.

  5. Select the CD Drive containing the virtio-win_version.iso file. You can complete the installation with either the GUI or the command line.

  6. Run the installer.

    To install with the GUI, complete the following steps
    1. Double-click virtio-win-guest-tools.exe.

    2. Click Next at the welcome screen.

    3. Follow the prompts in the installation wizard.

    4. When installation is complete, select Yes, I want to restart my computer now and click Finish to apply the changes.

    To install silently with the command line, complete the following steps
    1. Open a command prompt with Administrator privileges.

    2. Enter the msiexec command:

      D:\ msiexec /i "_PATH_TO_MSI_" /qn [/l*v "_PATH_TO_LOG_"][/norestart] ADDLOCAL=ALL

      Other possible values for ADDLOCAL are listed below.

      For example, to run the installation when virtio-win-gt-x64.msi is on the D:\ drive, without saving the log, and then immediately restart the virtual machine, enter the following command:

      D:\ msiexec /i "virtio-win-gt-x64.msi" /qn ADDLOCAL=ALL

After installation completes, the guest agents and drivers pass usage information to the oVirt Engine and enable you to access USB devices and other functionality.

3.3.3. Values for ADDLOCAL to customize virtio-win command-line installation

When installing virtio-win-gt-x64.msi or virtio-win-gt-x32.msi with the command line, you can install any one driver, or any combination of drivers.

You can also install specific agents, but you must also install each agent’s corresponding drivers.

The ADDLOCAL parameter of the msiexec command enables you to specify which drivers or agents to install. ADDLOCAL=ALL installs all drivers and agents. Other values are listed in the following tables.

Table 5. Possible values for ADDLOCAL to install drivers

Value for ADDLOCAL Driver Name Description

FE_network_driver

virtio-net

Paravirtualized network driver provides enhanced performance over emulated devices like rtl.

FE_balloon_driver

virtio-balloon

Controls the amount of memory a virtual machine actually accesses. It offers improved memory overcommitment.

FE_pvpanic_driver

pvpanic

QEMU pvpanic device driver.

FE_qemufwcfg_driver

qemufwcfg

QEMU FWCfg device driver.

FE_qemupciserial_driver

qemupciserial

QEMU PCI serial device driver.

FE_spice_driver

Spice Driver

A paravirtualized display driver reduces CPU usage on the host and provides better performance through reduced network bandwidth on most workloads.

FE_vioinput_driver

vioinput

VirtIO Input Driver.

FE_viorng_driver

viorng

VirtIO RNG device driver.

FE_vioscsi_driver

vioscsi

VirtIO SCSI pass-through controller.

FE_vioserial_driver

vioserial

VirtIO Serial device driver.

FE_viostor_driver

viostor

VirtIO Block driver.

Table 6. Possible values for ADDLOCAL to install agents and required corresponding drivers

Agent Description Corresponding driver(s) Value for ADDLOCAL

Spice Agent

Supports multiple monitors, responsible for client-mouse-mode support, reduces bandwidth usage, enables clipboard support between client and virtual machine, provide a better user experience and improved responsiveness.

vioserial and Spice driver

FE_spice_Agent,FE_vioserial_driver,FE_spice_driver

Examples

The following command installs only the VirtIO SCSI pass-through controller, the VirtIO Serial device driver, and the VirtIO Block driver:

D:\ msiexec /i "virtio-win-gt-x64.msi" /qn ADDLOCAL=`FE_vioscsi_driver,FE_vioserial_driver,FE_viostor_driver

The following command installs only the Spice Agent and its required corresponding drivers:

D:\ msiexec /i "virtio-win-gt-x64.msi" /qn ADDLOCAL = FE_spice_Agent,FE_vioserial_driver,FE_spice_driver

The Microsoft Developer website:

  • Windows Installer

  • Command-Line Options for the Windows installer

  • Property Reference for the Windows installer

4. Additional Configuration

4.1. Configuring Operating Systems with osinfo

oVirt stores operating system configurations for virtual machines in /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties. This file contains default values such as os.other.devices.display.protocols.value = spice/qxl,vnc/vga,vnc/qxl.

There are only a limited number of scenarios in which you would change these values:

  • Adding an operating system that does not appear in the list of supported guest operating systems

  • Adding a product key (for example, os.windows_10x64.productKey.value =)

  • Configuring the sysprep path for a Windows virtual machine (for example, os.windows_10x64.sysprepPath.value = ${ENGINE_USR}/conf/sysprep/sysprep.w10x64)

Do not edit the actual 00-defaults.properties file. Changes will be overwritten if you upgrade or restore the Engine.

Do not change values that come directly from the operating system or the Engine, such as maximum memory size.

To change the operating system configurations, create an override file in /etc/ovirt-engine/osinfo.conf.d/. The file name must begin with a value greater than 00, so that the file appears after /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties, and ends with the extension, .properties.

For example, 10-productkeys.properties overrides the default file, 00-defaults.properties. The last file in the file list has precedence over earlier files.

For virtual machines with Windows Server 2016,
on each oVirt host, modify the /etc/modprobe.d/kvm.conf configuration file by adding the line: options kvm ignore_msrs=1

4.2. Configuring Single Sign-On for Virtual Machines

Configuring single sign-on, also known as password delegation, allows you to automatically log in to a virtual machine using the credentials you use to log in to the VM Portal. Single sign-on can be used on both Enterprise Linux and Windows virtual machines.

Single sign-on is not supported for virtual machines running Enterprise Linux 8.0.

If single sign-on to the VM Portal is enabled, single sign-on to virtual machines will not be possible. With single sign-on to the VM Portal enabled, the VM Portal does not need to accept a password, thus the password cannot be delegated to sign in to virtual machines.

4.2.1. Configuring Single Sign-On for Enterprise Linux Virtual Machines Using IPA (IdM)

To configure single sign-on for Enterprise Linux virtual machines using GNOME and KDE graphical desktop environments and IPA (IdM) servers, you must install the ovirt-guest-agent package on the virtual machine and install the packages associated with your window manager.

The following procedure assumes that you have a working IPA configuration and that the IPA domain is already joined to the Engine. You must also ensure that the clocks on the Engine, the virtual machine and the system on which IPA (IdM) is hosted are synchronized using NTP.

Single sign-on with IPA (IdM) is deprecated for virtual machines running Enterprise Linux version 7 or earlier and unsupported for virtual machines running Enterprise Linux 8 or Windows operating systems.

Configuring Single Sign-On for Enterprise Linux Virtual Machines

  1. Log in to the Enterprise Linux virtual machine.

  2. Enable the repository:

    • For Enterprise Linux 6:

      # subscription-manager repos --enable=rhel-6-server-rhv-4-agent-rpms
    • For Enterprise Linux 7:

      # subscription-manager repos --enable=rhel-7-server-rh-common-rpms
  3. Download and install the guest agent, single sign-on, and IPA packages:

    # yum install ovirt-guest-agent-common ovirt-guest-agent-pam-module ovirt-guest-agent-gdm-plugin ipa-client
  4. Run the following command and follow the prompts to configure ipa-client and join the virtual machine to the domain:

    # ipa-client-install --permit --mkhomedir

    In environments that use DNS obfuscation, this command should be:

    # ipa-client-install --domain=FQDN --server=FQDN
  5. For Enterprise Linux 7.2 and later:

    # authconfig --enablenis --update

    Enterprise Linux 7.2 has a new version of the System Security Services Daemon (SSSD), which introduces configuration that is incompatible with the oVirt Engine guest agent single sign-on implementation. This command ensures that single sign-on works.

  6. Fetch the details of an IPA user:

  7. Record the IPA user’s UID and GID:

    ipa-user:*:936600010:936600001::/home/ipa-user:/bin/sh
  8. Create a home directory for the IPA user:

  9. Assign ownership of the directory to the IPA user:

    # chown 936600010:936600001 /home/ipa-user

Log in to the VM Portal using the user name and password of a user configured to use single sign-on and connect to the console of the virtual machine. You will be logged in automatically.

4.2.2. Configuring single sign-on for Windows virtual machines

To configure single sign-on for Windows virtual machines, the Windows guest agent must be installed on the guest virtual machine. The virtio-win ISO image provides this agent. If the virtio-win_version.iso image is not available in your storage domain, contact your system administrator.

Procedure

  1. Select the Windows virtual machine. Ensure the machine is powered up.

  2. On the virtual machine, locate the CD drive and open the CD.

  3. Launch virtio-win-guest-tools.

  4. Click Options

  5. Select Install oVirt Guest Agent.

  6. Click OK.

  7. Click Install.

  8. When the installation completes, you are prompted to restart the machine to apply the changes.

Log in to the VM Portal using the user name and password of a user configured to use single sign-on and connect to the console of the virtual machine. You will be logged in automatically.

4.2.3. Disabling Single Sign-on for Virtual Machines

The following procedure explains how to disable single sign-on for a virtual machine.

Disabling Single Sign-On for Virtual Machines

  1. Select a virtual machine and click Edit.

  2. Click the Console tab.

  3. Select the Disable Single Sign On check box.

  4. Click OK.

4.3. Configuring USB Devices

A virtual machine connected with the SPICE protocol can be configured to connect directly to USB devices.

The USB device will only be redirected if the virtual machine is active, in focus and is run from the VM Portal. USB redirection can be manually enabled each time a device is plugged in or set to automatically redirect to active virtual machines in the Console Options window.

Note the distinction between the client machine and guest machine. The client is the hardware from which you access a guest. The guest is the virtual desktop or virtual server which is accessed through the VM Portal or Administration Portal.

USB redirection Enabled mode allows KVM/SPICE USB redirection for Linux and Windows virtual machines. Virtual (guest) machines require no guest-installed agents or drivers for native USB. On Enterprise Linux clients, all packages required for USB redirection are provided by the virt-viewer package. On Windows clients, you must also install the usbdk package. Enabled USB mode is supported on the following clients and guests:

If you have a 64-bit architecture PC, you must use the 64-bit version of Internet Explorer to install the 64-bit version of the USB driver. The USB redirection will not work if you install the 32-bit version on a 64-bit architecture. As long as you initially install the correct USB type, you can access USB redirection from both 32- and 64-bit browsers.

4.3.1. Using USB Devices on a Windows Client

The usbdk driver must be installed on the Windows client for the USB device to be redirected to the guest. Ensure the version of usbdk matches the architecture of the client machine. For example, the 64-bit version of usbdk must be installed on 64-bit Windows machines.

USB redirection is only supported when you open the virtual machine from the VM Portal.

Procedure

  1. When the usbdk driver is installed, click and select a virtual machine that is configured to use the SPICE protocol.

  2. Click the Console tab.

  3. Select the USB enabled checkbox and click OK.

  4. Click .

  5. Select the Enable USB Auto-Share check box and click OK.

  6. Start the virtual machine from the VM Portal and click Console to connect to that virtual machine.

  7. Plug your USB device into the client machine to make it appear automatically on the guest machine.

4.3.2. Using USB Devices on a Enterprise Linux Client

The usbredir package enables USB redirection from Enterprise Linux clients to virtual machines. usbredir is a dependency of the virt-viewer package, and is automatically installed together with that package.

USB redirection is only supported when you open the virtual machine from the VM Portal.

Procedure

  1. Click .

  2. Select a virtual machine that has been configured to use the SPICE protocol and click Edit. This opens the Edit Virtual Machine window.

  3. Click the Console tab.

  4. Select the USB enabled checkbox and click OK.

  5. Click .

  6. Select the Enable USB Auto-Share check box and click OK.

  7. Start the virtual machine from the VM Portal and click Console to connect to that virtual machine.

  8. Plug your USB device into the client machine to make it appear automatically on the guest machine.

4.4. Configuring Multiple Monitors

4.4.1. Configuring Multiple Displays for Enterprise Linux Virtual Machines

A maximum of four displays can be configured for a single Enterprise Linux virtual machine when connecting to the virtual machine using the SPICE protocol.

  1. Start a SPICE session with the virtual machine.

  2. Open the View drop-down menu at the top of the SPICE client window.

  3. Open the Display menu.

  4. Click the name of a display to enable or disable that display.

By default, Display 1 is the only display that is enabled on starting a SPICE session with a virtual machine. If no other displays are enabled, disabling this display will close the session.

4.4.2. Configuring Multiple Displays for Windows Virtual Machines

A maximum of four displays can be configured for a single Windows virtual machine when connecting to the virtual machine using the SPICE protocol.

  1. Click and select a virtual machine.

  2. With the virtual machine in a powered-down state, click Edit.

  3. Click the Console tab.

  4. Select the number of displays from the Monitors drop-down list.

    This setting controls the maximum number of displays that can be enabled for the virtual machine. While the virtual machine is running, additional displays can be enabled up to this number.

  5. Click OK.

  6. Start a SPICE session with the virtual machine.

  7. Open the View drop-down menu at the top of the SPICE client window.

  8. Open the Display menu.

  9. Click the name of a display to enable or disable that display.

    By default, Display 1 is the only display that is enabled on starting a SPICE session with a virtual machine. If no other displays are enabled, disabling this display will close the session.

4.5. Configuring Console Options

4.5.1. Console Options

Connection protocols are the underlying technology used to provide graphical consoles for virtual machines and allow users to work with virtual machines in a similar way as they would with physical machines. oVirt currently supports the following connection protocols:

SPICE

Simple Protocol for Independent Computing Environments (SPICE) is the recommended connection protocol for both Linux virtual machines and Windows virtual machines. To open a console to a virtual machine using SPICE, use Remote Viewer.

VNC

Virtual Network Computing (VNC) can be used to open consoles to both Linux virtual machines and Windows virtual machines. To open a console to a virtual machine using VNC, use Remote Viewer or a VNC client.

RDP

Remote Desktop Protocol (RDP) can only be used to open consoles to Windows virtual machines, and is only available when you access a virtual machines from a Windows machine on which Remote Desktop has been installed. Before you can connect to a Windows virtual machine using RDP, you must set up remote sharing on the virtual machine and configure the firewall to allow remote desktop connections.

SPICE is not supported on virtual machines running Windows 8 or Windows 8.1. If a virtual machine running one of these operating systems is configured to use the SPICE protocol, it detects the absence of the required SPICE drivers and runs in VGA compatibility mode.

4.5.2. Accessing Console Options

You can configure several options for opening graphical consoles for virtual machines in the Administration Portal.

Procedure

  1. Click and select a running virtual machine.

  2. Click .

You can configure the connection protocols and video type in the Console tab of the Edit Virtual Machine window in the Administration Portal. Additional options specific to each of the connection protocols, such as the keyboard layout when using the VNC connection protocol, can be configured. See Virtual Machine Console settings explained for more information.

4.5.3. SPICE Console Options

When the SPICE connection protocol is selected, the following options are available in the Console Options window.

SPICE Options

  • Map control-alt-del shortcut to ctrl+alt+end: Select this check box to map the Ctrl + Alt + Del key combination to Ctrl + Alt + End inside the virtual machine.

  • Enable USB Auto-Share: Select this check box to automatically redirect USB devices to the virtual machine. If this option is not selected, USB devices will connect to the client machine instead of the guest virtual machine. To use the USB device on the guest machine, manually enable it in the SPICE client menu.

  • Open in Full Screen: Select this check box for the virtual machine console to automatically open in full screen when you connect to the virtual machine. Press SHIFT + F11 to toggle full screen mode on or off.

  • Enable SPICE Proxy: Select this check box to enable the SPICE proxy.

4.5.4. VNC Console Options

When the VNC connection protocol is selected, the following options are available in the Console Options window.

Console Invocation

  • Native Client: When you connect to the console of the virtual machine, a file download dialog provides you with a file that opens a console to the virtual machine via Remote Viewer.

  • noVNC: When you connect to the console of the virtual machine, a browser tab is opened that acts as the console.

VNC Options

  • Map control-alt-delete shortcut to ctrl+alt+end: Select this check box to map the Ctrl + Alt + Del key combination to Ctrl + Alt + End inside the virtual machine.

4.5.5. RDP Console Options

When the RDP connection protocol is selected, the following options are available in the Console Options window.

Console Invocation

  • Auto: The Engine automatically selects the method for invoking the console.

  • Native client: When you connect to the console of the virtual machine, a file download dialog provides you with a file that opens a console to the virtual machine via Remote Desktop.

RDP Options

  • Use Local Drives: Select this check box to make the drives on the client machine accessible on the guest virtual machine.

4.5.6. Remote Viewer Options

Remote Viewer Options

When you specify the Native client console invocation option, you will connect to virtual machines using Remote Viewer. The Remote Viewer window provides a number of options for interacting with the virtual machine to which it is connected.

Table 7. Remote Viewer Options

Option Hotkey

File

  • Screenshot: Takes a screen capture of the active window and saves it in a location of your specification.

  • USB device selection: If USB redirection has been enabled on your virtual machine, the USB device plugged into your client machine can be accessed from this menu.

  • Quit: Closes the console. The hot key for this option is Shift + Ctrl + Q.

View

  • Full screen: Toggles full screen mode on or off. When enabled, full screen mode expands the virtual machine to fill the entire screen. When disabled, the virtual machine is displayed as a window. The hot key for enabling or disabling full screen is SHIFT + F11.

  • Zoom: Zooms in and out of the console window. Ctrl + + zooms in, Ctrl + - zooms out, and Ctrl + 0 returns the screen to its original size.

  • Automatically resize: Select to enable the guest resolution to automatically scale according to the size of the console window.

  • Displays: Allows users to enable and disable displays for the guest virtual machine.

Send key

  • Ctrl + Alt + Del: On a Enterprise Linux virtual machine, it displays a dialog with options to suspend, shut down or restart the virtual machine. On a Windows virtual machine, it displays the task manager or Windows Security dialog.

  • Ctrl + Alt + Backspace: On a Enterprise Linux virtual machine, it restarts the X sever. On a Windows virtual machine, it does nothing.

  • Ctrl + Alt + F1

  • Ctrl + Alt + F2

  • Ctrl + Alt + F3

  • Ctrl + Alt + F4

  • Ctrl + Alt + F5

  • Ctrl + Alt + F6

  • Ctrl + Alt + F7

  • Ctrl + Alt + F8

  • Ctrl + Alt + F9

  • Ctrl + Alt + F10

  • Ctrl + Alt + F11

  • Ctrl + Alt + F12

  • Printscreen: Passes the Printscreen keyboard option to the virtual machine.

Help

The About entry displays the version details of Virtual Machine Viewer that you are using.

Release Cursor from Virtual Machine

SHIFT + F12

Remote Viewer Hotkeys

You can access the hotkeys for a virtual machine in both full screen mode and windowed mode. If you are using full screen mode, you can display the menu containing the button for hotkeys by moving the mouse pointer to the middle of the top of the screen. If you are using windowed mode, you can access the hotkeys via the Send key menu on the virtual machine window title bar.

If vdagent is not running on the client machine, the mouse can become captured in a virtual machine window if it is used inside a virtual machine and the virtual machine is not in full screen. To unlock the mouse, press Shift + F12.

Manually Associating console.vv Files with Remote Viewer

If you are prompted to download a console.vv file when attempting to open a console to a virtual machine using the native client console option, and Remote Viewer is already installed, then you can manually associate console.vv files with Remote Viewer so that Remote Viewer can automatically use those files to open consoles.

Manually Associating console.vv Files with Remote Viewer

  1. Start the virtual machine.

  2. Open the Console Options window:

    • In the Administration Portal, click .

    • In the VM Portal, click the virtual machine name and click the pencil icon beside Console.

  3. Change the console invocation method to Native client and click OK.

  4. Attempt to open a console to the virtual machine, then click Save when prompted to open or save the console.vv file.

  5. Click the location on your local machine where you saved the file.

  6. Double-click the console.vv file and select Select a program from a list of installed programs when prompted.

  7. In the Open with window, select Always use the selected program to open this kind of file and click the Browse button.

  8. Click the C:\Users_[user name]_\AppData\Local\virt-viewer\bin directory and select remote-viewer.exe.

  9. Click Open and then click OK.

When you use the native client console invocation option to open a console to a virtual machine, Remote Viewer will automatically use the console.vv file that the oVirt Engine provides to open a console to that virtual machine without prompting you to select the application to use.

4.6. Configuring a Watchdog

4.6.1. Adding a Watchdog Card to a Virtual Machine

You can add a watchdog card to a virtual machine to monitor the operating system’s responsiveness.

Procedure

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the High Availability tab.

  4. Select the watchdog model to use from the Watchdog Model drop-down list.

  5. Select an action from the Watchdog Action drop-down list. This is the action that the virtual machine takes when the watchdog is triggered.

  6. Click OK.

4.6.2. Installing a Watchdog

To activate a watchdog card attached to a virtual machine, you must install the watchdog package on that virtual machine and start the watchdog service.

Installing Watchdogs

  1. Log in to the virtual machine on which the watchdog card is attached.

  2. Install the watchdog package and dependencies:

  3. Edit the /etc/watchdog.conf file and uncomment the following line:

    watchdog-device = /dev/watchdog
  4. Save the changes.

  5. Start the watchdog service and ensure this service starts on boot:

    • Enterprise Linux 6:

      # service watchdog start
      # chkconfig watchdog on
    • Enterprise Linux 7:

      # systemctl start watchdog.service
      # systemctl enable watchdog.service

4.6.3. Confirming Watchdog Functionality

Confirm that a watchdog card has been attached to a virtual machine and that the watchdog service is active.

This procedure is provided for testing the functionality of watchdogs only and must not be run on production machines.

Confirming Watchdog Functionality

  1. Log in to the virtual machine on which the watchdog card is attached.

  2. Confirm that the watchdog card has been identified by the virtual machine:

    # lspci | grep watchdog -i
  3. Run one of the following commands to confirm that the watchdog is active:

    • Trigger a kernel panic:

      # echo c > /proc/sysrq-trigger
    • Terminate the watchdog service:

The watchdog timer can no longer be reset, so the watchdog counter reaches zero after a short period of time. When the watchdog counter reaches zero, the action specified in the Watchdog Action drop-down menu for that virtual machine is performed.

4.6.4. Parameters for Watchdogs in watchdog.conf

The following is a list of options for configuring the watchdog service available in the /etc/watchdog.conf file. To configure an option, you must uncomment that option and restart the watchdog service after saving the changes.

For a more detailed explanation of options for configuring the watchdog service and using the watchdog command, see the watchdog man page.

Table 8. watchdog.conf variables

Variable name Default Value Remarks

ping

N/A

An IP address that the watchdog attempts to ping to verify whether that address is reachable. You can specify multiple IP addresses by adding additional ping lines.

interface

N/A

A network interface that the watchdog will monitor to verify the presence of network traffic. You can specify multiple network interfaces by adding additional interface lines.

file

/var/log/messages

A file on the local system that the watchdog will monitor for changes. You can specify multiple files by adding additional file lines.

change

1407

The number of watchdog intervals after which the watchdog checks for changes to files. A change line must be specified on the line directly after each file line, and applies to the file line directly above that change line.

max-load-1

24

The maximum average load that the virtual machine can sustain over a one-minute period. If this average is exceeded, then the watchdog is triggered. A value of 0 disables this feature.

max-load-5

18

The maximum average load that the virtual machine can sustain over a five-minute period. If this average is exceeded, then the watchdog is triggered. A value of 0 disables this feature. By default, the value of this variable is set to a value approximately three quarters that of max-load-1.

max-load-15

12

The maximum average load that the virtual machine can sustain over a fifteen-minute period. If this average is exceeded, then the watchdog is triggered. A value of 0 disables this feature. By default, the value of this variable is set to a value approximately one half that of max-load-1.

min-memory

1

The minimum amount of virtual memory that must remain free on the virtual machine. This value is measured in pages. A value of 0 disables this feature.

repair-binary

/usr/sbin/repair

The path and file name of a binary file on the local system that will be run when the watchdog is triggered. If the specified file resolves the issues preventing the watchdog from resetting the watchdog counter, then the watchdog action is not triggered.

test-binary

N/A

The path and file name of a binary file on the local system that the watchdog will attempt to run during each interval. A test binary allows you to specify a file for running user-defined tests.

test-timeout

N/A

The time limit, in seconds, for which user-defined tests can run. A value of 0 allows user-defined tests to continue for an unlimited duration.

temperature-device

N/A

The path to and name of a device for checking the temperature of the machine on which the watchdog service is running.

max-temperature

120

The maximum allowed temperature for the machine on which the watchdog service is running. The machine will be halted if this temperature is reached. Unit conversion is not taken into account, so you must specify a value that matches the watchdog card being used.

admin

root

The email address to which email notifications are sent.

interval

10

The interval, in seconds, between updates to the watchdog device. The watchdog device expects an update at least once every minute, and if there are no updates over a one-minute period, then the watchdog is triggered. This one-minute period is hard-coded into the drivers for the watchdog device, and cannot be configured.

logtick

1

When verbose logging is enabled for the watchdog service, the watchdog service periodically writes log messages to the local system. The logtick value represents the number of watchdog intervals after which a message is written.

realtime

yes

Specifies whether the watchdog is locked in memory. A value of yes locks the watchdog in memory so that it is not swapped out of memory, while a value of no allows the watchdog to be swapped out of memory. If the watchdog is swapped out of memory and is not swapped back in before the watchdog counter reaches zero, then the watchdog is triggered.

priority

1

The schedule priority when the value of realtime is set to yes.

pidfile

/var/run/syslogd.pid

The path and file name of a PID file that the watchdog monitors to see if the corresponding process is still active. If the corresponding process is not active, then the watchdog is triggered.

4.7. Configuring Virtual NUMA

In the Administration Portal, you can configure virtual NUMA nodes on a virtual machine and pin them to physical NUMA nodes on one or more hosts. The host’s default policy is to schedule and run virtual machines on any available resources on the host. As a result, the resources backing a large virtual machine that cannot fit within a single host socket could be spread out across multiple NUMA nodes. Over time these resources may be moved around, leading to poor and unpredictable performance. Configure and pin virtual NUMA nodes to avoid this outcome and improve performance.

Configuring virtual NUMA requires a NUMA-enabled host. To confirm whether NUMA is enabled on a host, log in to the host and run numactl --hardware. The output of this command should show at least two NUMA nodes. You can also view the host’s NUMA topology in the Administration Portal by selecting the host from the Hosts tab and clicking NUMA Support. This button is only available when the selected host has at least two NUMA nodes.

If you define NUMA Pinning, the default migration mode is Allow manual migration only by default.

Configuring Virtual NUMA

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click Show Advanced Options.

  4. Click the Host tab.

  5. Select the Specific Host(s) radio button and select the host(s) from the list. The selected host(s) must have at least two NUMA nodes.

  6. Click NUMA Pinning.

  7. In the NUMA Topology window, click and drag virtual NUMA nodes from the box on the right to host NUMA nodes on the left as required, and click OK.

  8. Select Strict, Preferred, or Interleave from the Tune Mode drop-down list in each NUMA node. If the selected mode is Preferred, the NUMA Node Count must be set to 1.

  9. You can also set the NUMA pinning policy automatically by selecting Resize and Pin NUMA from the CPU Pinning Polcy drop-down list under the CPU Allocation settings in the Resource Allocation tab:

    • None — Runs without any CPU pinning.

    • Manual — Runs a manually specified virtual CPU on a specific physical CPU and a specific host. Available only when the virtual machine is pinned to a Host.

    • Resize and Pin NUMA — Resizes the virtual CPU and NUMA topology of the virtual machine according to the Host, and pins them to the Host resources.

    • Dedicated — Exclusively pins virtual CPUs to host physical CPUs. Available for cluster compatibility level 4.7 or later. If the virtual machine has NUMA enabled, all nodes must be unpinned.

    • Isolate Threads — Exclusively pins virtual CPUs to host physical CPUs. Each virtual CPU gets a physical core. Available for cluster compatibility level 4.7 or later. If the virtual machine has NUMA enabled, all nodes must be unpinned.

  10. Click OK.

If you do not pin the virtual NUMA node to a host NUMA node, the system defaults to the NUMA node that contains the host device’s memory-mapped I/O (MMIO), provided that there are one or more host devices and all of those devices are from a single NUMA node.

4.8. Configuring Satellite errata viewing for a virtual machine

In the Administration Portal, you can configure a virtual machine to display the available errata. The virtual machine needs to be associated with a Red Hat Satellite server to show available errata.

oVirt 4.4 supports viewing errata with Red Hat Satellite 6.6.

Prerequisites

  • The Satellite server must be added as an external provider.

  • The Engine and any virtual machines on which you want to view errata must all be registered in the Satellite server by their respective FQDNs. This ensures that external content host IDs do not need to be maintained in oVirt.

    Virtual machines added using an IP address cannot report errata.

  • The host that the virtual machine runs on also needs to be configured to receive errata information from Satellite.

  • The virtual machine must have the ovirt-guest-agent package installed. This package enables the virtual machine to report its host name to the oVirt Engine, which enables the Red Hat Satellite server to identify the virtual machine as a content host and report the applicable errata.

  • The virtual machine must be registered to the Red Hat Satellite server as a content host.

  • Use Red Hat Satellite remote execution to manage packages on hosts.

The Katello agent is deprecated and will be removed in a future Satellite version. Migrate your processes to use the remote execution feature to update clients remotely.

Procedure

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the Foreman/Satellite tab.

  4. Select the required Satellite server from the Provider drop-down list.

  5. Click OK.

Additional resources

  • Setting up Satellite errata viewing for a host in the Administration Guide

  • Installing the Guest Agents, Tools, and Drivers on Linux in the Virtual Machine Management Guide for Enterprise Linux virtual machines.

  • Installing the Guest Agents, Tools, and Drivers on Windows in the Virtual Machine Management Guide for Windows virtual machines.

4.9. Configuring Headless Virtual Machines

You can configure a headless virtual machine when it is not necessary to access the machine via a graphical console. This headless machine will run without graphical and video devices. This can be useful in situations where the host has limited resources, or to comply with virtual machine usage requirements such as real-time virtual machines.

Headless virtual machines can be administered via a Serial Console, SSH, or any other service for command line access. Headless mode is applied via the Console tab when creating or editing virtual machines and machine pools, and when editing templates. It is also available when creating or editing instance types.

If you are creating a new headless virtual machine, you can use the Run Once window to access the virtual machine via a graphical console for the first run only. See Virtual Machine Run Once settings explained for more details.

Prerequisites

  • If you are editing an existing virtual machine, and the oVirt guest agent has not been installed, note the machine’s IP prior to selecting Headless Mode.

  • Before running a virtual machine in headless mode, the GRUB configuration for this machine must be set to console mode otherwise the guest operating system’s boot process will hang. To set console mode, comment out the spashimage flag in the GRUB menu configuration file:

     #splashimage=(hd0,0)/grub/splash.xpm.gz serial --unit=0 --speed=9600 --parity=no --stop=1 terminal --timeout=2 serial

Restart the virtual machine if it is running when selecting the Headless Mode option.

Configuring a Headless Virtual Machine

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the Console tab.

  4. Select Headless Mode. All other fields in the Graphical Console section are disabled.

  5. Optionally, select Enable VirtIO serial console to enable communicating with the virtual machine via serial console. This is highly recommended.

  6. Reboot the virtual machine if it is running. See Rebooting a Virtual Machine.

4.10. Configuring High Performance Virtual Machines, Templates, and Pools

You can configure a virtual machine for high performance, so that it runs with performance metrics as close to bare metal as possible. When you choose high performance optimization, the virtual machine is configured with a set of automatic, and recommended manual, settings for maximum efficiency.

The high performance option is only accessible in the Administration Portal, by selecting High Performance from the Optimized for dropdown list in the Edit or New virtual machine, template, or pool window. This option is not available in the VM Portal.

The high performance option is supported by oVirt 4.2 and later. It is not available for earlier versions.

Virtual Machines

If you change the optimization mode of a running virtual machine to high performance, some configuration changes require restarting the virtual machine.

To change the optimization mode of a new or existing virtual machine to high performance, you may need to make manual changes to the cluster and to the pinned host configuration first.

A high performance virtual machine has certain limitations, because enhanced performance has a trade-off in decreased flexibility:

  • If pinning is set for CPU threads, I/O threads, emulator threads, or NUMA nodes, according to the recommended settings, only a subset of cluster hosts can be assigned to the high performance virtual machine.

  • Many devices are automatically disabled, which limits the virtual machine’s usability.

Templates and Pools

High performance templates and pools are created and edited in the same way as virtual machines. If a high performance template or pool is used to create new virtual machines, those virtual machines inherits this property and its configurations. Certain settings, however, are not inherited and must be set manually:

  • CPU pinning

  • Virtual NUMA and NUMA pinning topology

  • I/O and emulator threads pinning topology

  • Pass-through Host CPU

4.10.1. Creating a High Performance Virtual Machine, Template, or Pool

To create a high performance virtual machine, template, or pool:

  1. In the New or Edit window, select High Performance from the Optimized for drop-down menu.

    Selecting this option automatically performs certain configuration changes to this virtual machine, which you can view by clicking different tabs. You can change them back to their original settings or override them. (See Automatic High Performance Configuration Settings for details.) If you change a setting, its latest value is saved.

  2. Click OK.

    If you have not set any manual configurations, the High Performance Virtual Machine/Pool Settings screen describing the recommended manual configurations appears.

    If you have set some of the manual configurations, the High Performance Virtual Machine/Pool Settings screen displays the settings you have not made.

    If you have set all the recommended manual configurations, the High Performance Virtual Machine/Pool Settings screen does not appear.

  3. If the High Performance Virtual Machine/Pool Settings screen appears, click Cancel to return to the New or Edit window to perform the manual configurations. See Configuring the Recommended Manual Settings for details.

    Alternatively, click OK to ignore the recommendations. The result may be a drop in the level of performance.

  4. Click OK.

    You can view the optimization type in the General tab of the details view of the virtual machine, pool, or template.

Certain configurations can override the high performance settings. For example, if you select an instance type for a virtual machine before selecting High Performance from the Optimized for drop-down menu and performing the manual configuration, the instance type configuration will not affect the high performance configuration. If, however, you select the instance type after the high performance configurations, you should verify the final configuration in the different tabs to ensure that the high performance configurations have not been overridden by the instance type.

The last-saved configuration usually takes priority.

Support for instance types is now deprecated, and will be removed in a future release.
Automatic High Performance Configuration Settings

The following table summarizes the automatic settings. The Enabled (Y/N) column indicates configurations that are enabled or disabled. The Applies to column indicates the relevant resources:

  • VM — Virtual machine

  • T — Template

  • P — Pool

  • C — Cluster

Table 9. Automatic High Performance Configuration Settings

Setting Enabled (Y/N) Applies to

Headless Mode (Console tab)

Y

VM, T, P

USB Enabled (Console tab)

N

VM, T, P

Smartcard Enabled (Console tab)

N

VM, T, P

Soundcard Enabled (Console tab)

N

VM, T, P

Enable VirtIO serial console (Console tab)

Y

VM, T, P

Allow manual migration only (Host tab)

Y

VM, T, P

Pass-Through Host CPU (Host tab)

Y

VM, T, P

Highly Available [1] (High Availability tab)

N

VM, T, P

No-Watchdog (High Availability tab)

N

VM, T, P

Memory Balloon Device (Resource Allocation tab)

N

VM, T, P

I/O Threads Enabled [2] (Resource Allocation tab)

Y

VM, T, P

Paravirtualized Random Number Generator PCI (virtio-rng) device (Random Generator tab)

Y

VM, T, P

I/O and emulator threads pinning topology

Y

VM, T

CPU cache layer 3

Y

VM, T, P

  1. Highly Available is not automatically enabled. If you select it manually, high availability should be enabled for pinned hosts only.

  2. Number of I/O threads = 1.

I/O and Emulator Threads Pinning Topology (Automatic Settings)

The I/O and emulator threads pinning topology is a new configuration setting for oVirt 4.2. It requires that I/O threads, NUMA nodes, and NUMA pinning be enabled and set for the virtual machine. Otherwise, a warning will appear in the engine log.

Pinning topology:

  • The first two CPUs of each NUMA node are pinned.

  • If all vCPUs fit into one NUMA node of the host:

    • The first two vCPUs are automatically reserved/pinned

    • The remaining vCPUs are available for manual vCPU pinning

  • If the virtual machine spans more than one NUMA node:

    • The first two CPUs of the NUMA node with the most pins are reserved/pinned

    • The remaining pinned NUMA node(s) are for vCPU pinning only

Pools do not support I/O and emulator threads pinning.

If a host CPU is pinned to both a vCPU and I/O and emulator threads, a warning will appear in the log and you will be asked to consider changing the CPU pinning topology to avoid this situation.

High Performance Icons

The following icons indicate the states of a high performance virtual machine in the screen.

Table 10. High Performance Icons

Icon Description

High performance virtual machine

High performance virtual machine with Next Run configuration

Stateless, high performance virtual machine

Stateless, high performance virtual machine with Next Run configuration

Virtual machine in a high performance pool

Virtual machine in a high performance pool with Next Run configuration

4.10.2. Configuring the Recommended Manual Settings

You can configure the recommended manual settings in either the New or the Edit windows.

If a recommended setting is not performed, the High Performance Virtual Machine/Pool Settings screen displays the recommended setting when you save the resource.

The recommended manual settings are:

  • Pinning CPUs

  • Setting the NUMA Pinning Policy

  • Configuring Huge Pages

  • Disabling KSM

Manual High Performance Configuration Settings

The following table summarizes the recommended manual settings. The Enabled (Y/N) column indicates configurations that should be enabled or disabled. The Applies to column indicates the relevant resources:

  • VM — Virtual machine

  • T — Template

  • P — Pool

  • C — Cluster

Table 11. Manual High Performance Configuration Settings

Setting Enabled (Y/N) Applies to

NUMA Node Count (Host tab)

Y

VM

Tune Mode (NUMA Pinning screen)

Y

VM

NUMA Pinning (Host tab)

Y

VM

CPU Pinning topology (Resource Allocation tab)

Y

VM, P

hugepages (Custom Properties tab)

Y

VM, T, P

KSM (Optimization tab)

N

C

Pinning CPUs

To pin vCPUs to a specific host’s physical CPU:

  1. In the Host tab, select the Specific Host(s) radio button.

  2. In the Resource Allocation tab, enter the CPU Pinning Topology, verifying that the configuration fits the pinned host’s configuration. See Virtual Machine Resource Allocation settings explained for information about the syntax of this field.

    This field is populated automatically and the CPU topology is updated when automatic NUMA pinning is activated.

  3. Verify that the virtual machine configuration is compatible with the host configuration:

    • A virtual machine’s number of sockets must not be greater than the host’s number of sockets.

    • A virtual machine’s number of cores per virtual socket must not be greater than the host’s number of cores.

    • CPU-intensive workloads perform best when the host and virtual machine expect the same cache usage. To achieve the best performance, a virtual machine’s number of threads per core must not be greater than that of the host.

CPU pinning has the following requirements:

  • If the host is NUMA-enabled, the host’s NUMA settings (memory and CPUs) must be considered because the virtual machine has to fit the host’s NUMA configuration.

  • The I/O and emulator threads pinning topology must be considered.

  • CPU pinning can only be set for virtual machines and pools, but not for templates. Therefore, you must set CPU pinning manually whenever you create a high performance virtual machine or pool, even if they are based on a high performance template.

Setting the NUMA Pinning Policy

To set the NUMA Pinning Policy, you need a NUMA-enabled pinned host with at least two NUMA nodes.

To set the NUMA pinning policy manually:

  1. Click NUMA Pinning.

  2. In the NUMA Topology window, click and drag virtual NUMA nodes from the box on the right to the host’s physical NUMA nodes on the left as required.

  3. Select Strict, Preferred, or Interleave from the Tune Mode drop-down list in each NUMA node. If the selected mode is Preferred, the NUMA Node Count must be set to 1.

  4. Click OK.

To set the NUMA pinning policy automatically:

  1. In the Resource Allocation tab, under CPU Allocation, select Resize and Pin NUMA from the CPU Pinning Policy drop-down list.

  2. Click OK.

The number of declared virtual NUMA nodes and the NUMA pinning policy must take into account:

  • The host’s NUMA settings (memory and CPUs)

  • The NUMA node in which the host devices are declared

  • The CPU pinning topology

  • The IO and emulator threads pinning topology

  • Huge page sizes

  • NUMA pinning can only be set for virtual machines, not for pools or templates. You must set NUMA pinning manually when you create a high performance virtual machine based on a template.

Configuring Huge Pages

Huge pages are pre-allocated when a virtual machine starts to run (dynamic allocation is disabled by default).

To configure huge pages:

  1. In the Custom Properties tab, select hugepages from the custom properties list, which displays Please select a key…​ by default.

  2. Enter the huge page size in KB.

    You should set the huge page size to the largest size supported by the pinned host. The recommended size for x86_64 is 1 GiB.

    The huge page size has the following requirements:

    • The virtual machine’s huge page size must be the same size as the pinned host’s huge page size.

    • The virtual machine’s memory size must fit into the selected size of the pinned host’s free huge pages.

    • The NUMA node size must be a multiple of the huge page’s selected size.

To enable dynamic allocation of huge pages:

  1. Disable the HugePages filter in the scheduler.

  2. In the [performance] section in /etc/vdsm/vdsm.conf set the following:

    use_dynamic_hugepages = true

Comparison between dynamic and static hugepages

The following table outlines advantages and disadvantages of dynamic and static hugepages.

Table 12. Dynamic vs static hugepages

Setting Advantages Disadvantages Recommendations

dynamic hugepages

  • Less configuration required

  • Less wasted memory (i.e. hugepages free on a host waiting for possible incoming migrations)

Failure to allocate due to fragmentation

Use 2MB hugepages

static hugepages

Predictable results

  • Requires a kernel command line in the Edit Host configuration in the Administraion Portal. See Custom kernel command line

  • Requires a host reboot.

The following limitations apply:

  • Memory hotplug/unplug is disabled

  • The host’s memory resource is limited

Disabling KSM

To disable Kernel Same-page Merging (KSM) for the cluster:

  1. Click and select the cluster.

  2. Click Edit.

  3. In the Optimization tab, clear the Enable KSM check box.

4.11. Configuring the time zone

oVirt stores time zone configurations for virtual machines in /etc/ovirt-engine/conf/00-timezone.properties. This file contains default time zone values such as Etc/GMT=Greenwich Standard Time. It features mappings that are valid for Windows and non-Windows time zones.

Do not edit the actual 00-timezone.properties file. Changes will be overwritten if you upgrade or restore the Engine.

Do not change values that come directly from the operating system or the Engine.

Procedure

  1. Create an override file in /etc/ovirt-engine/conf/. The file name must begin with a value greater than 00, so that the file appears after /etc/ovirt-engine/conf/00-timezone.properties, and ends with the extension, .properties.

    For example, 10-timezone.properties overrides the default file, 00-timezone.properties. The last file in the file list has precedence over earlier files.

  2. Add new time zones to that file. Be sure each key is a valid General time zone from the time zone database and the value is a valid Windows time zone:

    General

    Time zones used for non-Windows operating system types, must follow the standard time zone format for example, Etc/GMT or Asia/Jerusalem.

    Windows

    Time zones specifically supported on Windows for example, GMT Standard Time or Israel Standard Time.

  3. Restart the ovirt-engine service:

    # systemctl restart ovirt-engine

5. Editing Virtual Machines

5.1. Editing Virtual Machine Properties

Changes to storage, operating system, or networking parameters can adversely affect the virtual machine. Ensure that you have the correct details before attempting to make any changes. Virtual machines can be edited while running, and some changes (listed in the procedure below) will be applied immediately. To apply all other changes, the virtual machine must be shut down and restarted.

External virtual machines (marked with the prefix external) cannot be edited through the oVirt Engine.

Editing Virtual Machines

  1. Click .

  2. Select the virtual machine to be edited.

  3. Click Edit.

  4. Change settings as required.

    Changes to the following settings are applied immediately:

    • Name

    • Description

    • Comment

    • Optimized for (Desktop/Server/High Performance)

    • Delete Protection

    • Network Interfaces

    • Memory Size (Edit this field to hot plug virtual memory. See Hot Plugging Virtual Memory.)

    • Virtual Sockets (Edit this field to hot plug CPUs. See CPU hot plug.)

    • Highly Available

    • Priority for Run/Migration queue

    • Disable strict user checking

    • Icon

  5. Click OK.

  6. If the Next Start Configuration pop-up window appears, click OK.

Some changes are applied immediately. All other changes are applied when you shut down and restart your virtual machine. Until then, the pending changes icon () appears as a reminder to restart the virtual machine.

5.2. Network Interfaces

5.2.1. Adding a New Network Interface

You can add multiple network interfaces to virtual machines. Doing so allows you to put your virtual machine on multiple logical networks.

You can create an overlay network for your virtual machines, isolated from the hosts, by defining a logical network that is not attached to the physical interfaces of the host. For example, you can create a DMZ environment, in which the virtual machines communicate among themselves over the bridge created in the host.

The overlay network uses OVN, which must be installed as an external network provider. See the Administration Guide for more information

Procedure

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Network Interfaces tab.

  4. Click New.

  5. Enter the Name of the network interface.

  6. Select the Profile and the Type of network interface from the drop-down lists. The Profile and Type drop-down lists are populated in accordance with the profiles and network types available to the cluster and the network interface cards available to the virtual machine.

  7. Select the Custom MAC address check box and enter a MAC address for the network interface card as required.

  8. Click OK.

The new network interface is listed in the Network Interfaces tab in the details view of the virtual machine. The Link State is set to Up by default when the network interface card is defined on the virtual machine and connected to the network.

For more details on the fields in the New Network Interface window, see Virtual Machine Network Interface dialogue entries.

5.2.2. Editing a Network Interface

In order to change any network settings, you must edit the network interface. This procedure can be performed on virtual machines that are running, but some actions can be performed only on virtual machines that are not running.

Editing Network Interfaces

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Network Interfaces tab and select the network interface to edit.

  4. Click Edit.

  5. Change settings as required. You can specify the Name, Profile, Type, and Custom MAC address. See Adding a Network Interface.

  6. Click OK.

5.2.3. Hot Plugging a Network Interface

You can hot plug network interfaces. Hot plugging means enabling and disabling devices while a virtual machine is running.

The guest operating system must support hot plugging network interfaces.

Hot Plugging Network Interfaces

  1. Click and select a virtual machine.

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Network Interfaces tab and select the network interface to hot plug.

  4. Click Edit.

  5. Set the Card Status to Plugged to enable the network interface, or set it to Unplugged to disable the network interface.

  6. Click OK.

5.2.4. Removing a Network Interface

Removing Network Interfaces

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Network Interfaces tab and select the network interface to remove.

  4. Click Remove.

  5. Click OK.

5.2.5. Configuring a virtual machine to ignore NICs

You can configure the ovirt-guest-agent on a virtual machine to ignore certain NICs. This prevents IP addresses associated with network interfaces created by certain software from appearing in reports. You must specify the name and number of the network interface you want to ignore (for example, eth0, docker0).

Procedure

  1. In the /etc/ovirt-guest-agent.conf configuration file on the virtual machine, insert the following line, with the NICs to be ignored separated by spaces:

    ignored_nics = first_NIC_to_ignore second_NIC_to_ignore
  2. Start the agent:

    # systemctl start ovirt-guest-agent

Some virtual machine operating systems automatically start the guest agent during installation.

If your virtual machine’s operating system automatically starts the guest agent or if you need to configure the denylist on many virtual machines, use the configured virtual machine as a template for creating additional virtual machines. See Creating a template from an existing virtual machine for details.

5.3. Virtual Disks

5.3.1. Adding a New Virtual Disk

You can add multiple virtual disks to a virtual machine.

Image is the default type of disk. You can also add a Direct LUN disk. Image disk creation is managed entirely by the Engine. Direct LUN disks require externally prepared targets that already exist. Existing disks are either floating disks or shareable disks attached to virtual machines.

Adding Disks to Virtual Machines

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Disks tab.

  4. Click New.

  5. Use the appropriate radio buttons to switch between Image and Direct LUN.

  6. Enter a Size(GB), Alias, and Description for the new disk.

  7. Use the drop-down lists and check boxes to configure the disk. See Add Virtual Disk dialogue entries for more details on the fields for all disk types.

  8. Click OK.

The new disk appears in the details view after a short time.

5.3.2. Attaching an Existing Disk to a Virtual Machine

Floating disks are disks that are not associated with any virtual machine.

Floating disks can minimize the amount of time required to set up virtual machines. Designating a floating disk as storage for a virtual machine makes it unnecessary to wait for disk preallocation at the time of a virtual machine’s creation.

Floating disks can be attached to a single virtual machine, or to multiple virtual machines if the disk is shareable. Each virtual machine that uses the shared disk can use a different disk interface type.

Once a floating disk is attached to a virtual machine, the virtual machine can access it.

Procedure

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Disks tab.

  4. Click Attach.

  5. Select one or more virtual disks from the list of available disks and select the required interface from the Interface drop-down.

  6. Click OK.

No Quota resources are consumed by attaching virtual disks to, or detaching virtual disks from, virtual machines.

5.3.3. Extending the Available Size of a Virtual Disk

You can extend the available size of a virtual disk while the virtual disk is attached to a virtual machine. Resizing a virtual disk does not resize the underlying partitions or file systems on that virtual disk. Use the fdisk utility to resize the partitions and file systems as required. See How to Resize a Partition using fdisk for more information.

Extending the Available Size of Virtual Disks

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Disks tab and select the disk to edit.

  4. Click Edit.

  5. Enter a value in the Extend size by(GB) field.

  6. Click OK.

The target disk’s status becomes locked for a short time, during which the drive is resized. When the resizing of the drive is complete, the status of the drive becomes OK.

5.3.4. Hot Plugging a Virtual Disk

You can hot plug virtual disks. Hot plugging means enabling or disabling devices while a virtual machine is running.

The guest operating system must support hot plugging virtual disks.

Hot Plugging Virtual Disks

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Disks tab and select the virtual disk to hot plug.

  4. Click More Actions (), then click Activate to enable the disk, or Deactivate to disable the disk.

  5. Click OK.

5.3.5. Removing a Virtual Disk from a Virtual Machine

Removing Virtual Disks From Virtual Machines

  1. Click .

  2. Click a virtual machine name to go to the details view.

  3. Click the Disks tab and select the virtual disk to remove.

  4. Click More Actions (), then click Deactivate.

  5. Click OK.

  6. Click Remove.

  7. Optionally, select the Remove Permanently check box to completely remove the virtual disk from the environment. If you do not select this option — for example, because the disk is a shared disk — the virtual disk will remain in .

  8. Click OK.

If the disk was created as block storage, for example iSCSI, and the Wipe After Delete check box was selected when creating the disk, you can view the log file on the host to confirm that the data has been wiped after permanently removing the disk. See Settings to Wipe Virtual Disks After Deletion in the Administration Guide.

If the disk was created as block storage, for example iSCSI, and the Discard After Delete check box was selected on the storage domain before the disk was removed, a blkdiscard command is called on the logical volume when it is removed and the underlying storage is notified that the blocks are free. See Setting Discard After Delete for a Storage Domain in the Administration Guide. A blkdiscard is also called on the logical volume when a virtual disk is removed if the virtual disk is attached to at least one virtual machine with the Enable Discard check box selected.

5.3.6. Importing a Disk Image from an Imported Storage Domain

You can import floating virtual disks from an imported storage domain.

This procedure requires access to the Administration Portal.

Only QEMU-compatible disks can be imported into the Engine.

Importing a Disk Image

  1. Click .

  2. Click an imported storage domain to go to the details view.

  3. Click Disk Import.

  4. Select one or more disk images and click Import. This opens the Import Disk(s) window.

  5. Select the appropriate Disk Profile for each disk.

  6. Click OK to import the selected disks.

5.3.7. Importing an Unregistered Disk Image from an Imported Storage Domain

You can import floating virtual disks from a storage domain. Floating disks created outside of a oVirt environment are not registered with the Engine. Scan the storage domain to identify unregistered floating disks to be imported.

This procedure requires access to the Administration Portal.

Only QEMU-compatible disks can be imported into the Engine.

Importing a Disk Image

  1. Click .

  2. Click More Actions (), then click Scan Disks so that the Engine can identify unregistered disks.

  3. Select an unregistered disk name and click Disk Import.

  4. Select one or more disk images and click Import. This opens the Import Disk(s) window.

  5. Select the appropriate Disk Profile for each disk.

  6. Click OK to import the selected disks.

5.4. Virtual Memory

5.4.1. Hot Plugging Virtual Memory

You can hot plug virtual memory. Hot plugging means enabling or disabling devices while a virtual machine is running. Each time memory is hot plugged, it appears as a new memory device in the Vm Devices tab in the details view of the virtual machine, up to a maximum of 16 available slots. When the virtual machine is restarted, these devices are cleared from the Vm Devices tab without reducing the virtual machine’s memory, allowing you to hot plug more memory devices. If the hot plug fails (for example, if there are no more available slots), the memory increase will be applied when the virtual machine is restarted.

This feature is currently not supported for the self-hosted engine Engine virtual machine.

Procedure

  1. Click and select a running virtual machine.

  2. Click Edit.

  3. Click the System tab.

  4. Increase the Memory Size by entering the total amount required. Memory can be added in multiples of 256 MB. By default, the maximum memory allowed for the virtual machine is set to 4x the memory size specified. Though the value is changed in the user interface, the maximum value is not hot plugged, and you will see the pending changes icon (). To avoid that, you can change the maximum memory back to the original value.

  5. Click OK.

    This action opens the Pending Virtual Machine changes window, as some values such as maxMemorySizeMb and minAllocatedMem will not change until the virtual machine is restarted. However, the hot plug action is triggered by the change to the Memory Size value, which can be applied immediately.

  6. Click OK.

The virtual machine’s Defined Memory is updated in the General tab in the details view. You can see the newly added memory device in the Vm Devices tab in the details view.

5.4.2. Hot Unplugging Virtual Memory

You can hot unplug virtual memory. Hot unplugging disables devices while a virtual machine is running.

Prerequisites

  • Only memory added with hot plugging can be hot unplugged.

  • The virtual machine’s operating system must support memory hot unplugging.

  • The virtual machine must not have a memory balloon device enabled. This feature is disabled by default.

  • All blocks of the hot-plugged memory must be set to online_movable in the virtual machine’s device management rules. In virtual machines running up-to-date versions of Enterprise Linux or CoreOS, this rule is set by default. For information on device management rules, consult the documentation for the virtual machine’s operating system.

  • To ensure that hot plugged memory can be hot unplugged later, add the movable_node option to the kernel command line of the virtual machine as follows and reboot the virtual machine:

    # grubby --update-kernel=ALL --args="movable_node"

Procedure

  1. Click and select a running virtual machine.

  2. Click the Vm Devices tab.

  3. In the Hot Unplug column, click Hot Unplug beside the memory device to be removed.

  4. Click OK in the Memory Hot Unplug window.

    The Physical Memory Guaranteed value for the virtual machine is decremented automatically if necessary.

5.5. Hot Plugging vCPUs

You can hot plug vCPUs. Hot plugging means enabling or disabling devices while a virtual machine is running.

Hot unplugging a vCPU is only supported if the vCPU was previously hot plugged. A virtual machine’s vCPUs cannot be hot unplugged to less vCPUs than it was originally created with.

The following prerequisites apply:

  • The virtual machine’s Operating System must be explicitly set in the New Virtual Machine or Edit Virtual Machine window.

  • The virtual machine’s operating system must support CPU hot plug. See the table below for support details.

  • Windows virtual machines must have the guest agents installed. See Installing the Guest Agents and Drivers on Windows.

Hot Plugging vCPUs

  1. Click and select a running virtual machine.

  2. Click Edit.

  3. Click the System tab.

  4. Change the value of Virtual Sockets as required.

  5. Click OK.

Table 13. Operating System Support Matrix for vCPU Hot Plug

Operating System Version Architecture Hot Plug Supported Hot Unplug Supported

Enterprise Linux Atomic Host 7

x86

Yes

Yes

Enterprise Linux 6.3+

x86

Yes

Yes

Enterprise Linux 7.0+

x86

Yes

Yes

Enterprise Linux 7.3+

PPC64

Yes

Yes

Enterprise Linux 8.0+

x86

Yes

Yes

Microsoft Windows Server 2012 R2

All

x64

Yes

No

Microsoft Windows Server 2016

Standard, Datacenter

x64

Yes

No

Microsoft Windows Server 2019

Standard, Datacenter

x64

Yes

No

Microsoft Windows 8.x

All

x86

Yes

No

Microsoft Windows 8.x

All

x64

Yes

No

Microsoft Windows 10

All

x86

Yes

No

Microsoft Windows 10

All

x64

Yes

No

5.6. Pinning a Virtual Machine to Multiple Hosts

Virtual machines can be pinned to multiple hosts. Multi-host pinning allows a virtual machine to run on a specific subset of hosts within a cluster, instead of one specific host or all hosts in the cluster. The virtual machine cannot run on any other hosts in the cluster even if all of the specified hosts are unavailable. Multi-host pinning can be used to limit virtual machines to hosts with, for example, the same physical hardware configuration.

If a host fails, a highly available virtual machine is automatically restarted on one of the other hosts to which the virtual machine is pinned.

Pinning Virtual Machines to Multiple Hosts

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the Host tab.

  4. Select the Specific Host(s) radio button under Start Running On and select two or more hosts from the list.

  5. Click the High Availability tab.

  6. Select the Highly Available check box.

  7. Select Low, Medium, or High from the Priority drop-down list. When migration is triggered, a queue is created in which the high priority virtual machines are migrated first. If a cluster is running low on resources, only the high priority virtual machines are migrated.

  8. Click OK.

5.7. Viewing Virtual Machines Pinned to a Host

You can view virtual machines pinned to a host even while the virtual machines are offline. Use the Pinned to Host list to see which virtual machines will be affected and which virtual machines will require a manual restart after the host becomes active again.

Viewing Virtual Machines Pinned to a Host

  1. Click .

  2. Click a host name to go to the details view.

  3. Click the Virtual Machines tab.

  4. Click Pinned to Host.

5.8. Changing the CD for a Virtual Machine

You can change the CD accessible to a virtual machine while that virtual machine is running, using ISO images that have been uploaded to the data domain of the virtual machine’s cluster. See Uploading Images to a Data Storage Domain in the Administration Guide for details.

Procedure

  1. Click and select a running virtual machine.

  2. Click More Actions (), then click Change CD.

  3. Select an option from the drop-down list:

    • Select an ISO file from the list to eject the CD currently accessible to the virtual machine and mount that ISO file as a CD.
      .Procedure from the list to eject the CD currently accessible to the virtual machine.

  4. Click OK.

5.9. Smart Card Authentication

Smart cards are an external hardware security feature, most commonly seen in credit cards, but also used by many businesses as authentication tokens. Smart cards can be used to protect oVirt virtual machines.

Enabling Smart Cards

  1. Ensure that the smart card hardware is plugged into the client machine and is installed according to manufacturer’s directions.

  2. Click and select a virtual machine.

  3. Click Edit.

  4. Click the Console tab and select the Smartcard enabled check box.

  5. Click OK.

  6. Connect to the running virtual machine by clicking the Console button. Smart card authentication is now passed from the client hardware to the virtual machine.

If the Smart card hardware is not correctly installed, enabling the Smart card feature will result in the virtual machine failing to load properly.

Disabling Smart Cards

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the Console tab, and clear the Smartcard enabled check box.

  4. Click OK.

Configuring Client Systems for Smart Card Sharing

  • Smart cards may require certain libraries in order to access their certificates. These libraries must be visible to the NSS library, which spice-gtk uses to provide the smart card to the guest. NSS expects the libraries to provide the PKCS #11 interface.

  • Make sure that the module architecture matches the spice-gtk / remote-viewer architecture. For instance, if you have only the 32b PKCS #11 library available, you must install the 32b build of virt-viewer in order for smart cards to work.

Configuring RHEL Clients for Smart Card support

Enterprise Linux provides support for Smart cards. Install the Smart card support group. If the Smart Card Support group is installed on a Enterprise Linux system, smart cards are redirected to the guest when Smart Cards are enabled.

  1. To install the Smart card support group, run the following command:

    # dnf groupinstall "Smart card support"

Configuring RHEL Clients with Other Smart Card Middleware

Enterprise Linux provides a system-wide registry of pkcs11 modules in the p11-kit, and these are accessible to all applications.

  1. To register the third party PKCS#11 library in the p11-kit database, run the following command as root:

    # echo "module: /path/to/library.so" > /etc/pkcs11/modules/my.module
  2. To verify the Smart card is visible for p11-kit through this library run the following command:

Configuring Windows Clients

Red Hat does not provide PKCS #11 support to Windows clients. Libraries that provide PKCS #11 support must be obtained from third parties.

  1. When such libraries are obtained, register them by running the following command as a user with elevated privileges:

    modutil -dbdir %PROGRAMDATA%\pki\nssdb -add "_module name_" -libfile C:_\Path\to\module_.dll

6. Administrative Tasks

6.1. Shutting Down a Virtual Machine

You can turn off a virtual machine using Shutdown or Power Off. Shutdown gracefully shuts down a virtual machine. Power Off executes a hard shutdown. A graceful shutdown is usually preferable to a hard shutdown.

If an exclamation point appears next to the virtual machine, a snapshot deletion process has failed, and you may not be able to restart the machine after shutting it down. Try to delete the snapshot again and ensure that the explanation mark disappears before shutting down the virtual machine. See Deleting a snapshot for more information.

Procedure

  1. Click and select a running virtual machine.

  2. Click Shutdown or right-click the virtual machine and select Shutdown from the pop-up menu.

  3. Optionally in the Administration Portal, enter a Reason for shutting down the virtual machine in the Shut down Virtual Machine(s) confirmation window. This allows you to provide an explanation for the shutdown, which will appear in the logs and when the virtual machine is powered on again.

  4. Click OK in the Shut down Virtual Machine(s) confirmation window.

If the virtual machine gracefully shuts down, the Status of the virtual machine changes to Down. If the virtual machine does not gracefully shut down, click the down arrow next to Shutdown and then click Power Off to execute a hard shutdown, or right-click the virtual machine and select Power Off from the pop-up menu.

6.2. Suspending a Virtual Machine

Suspending a virtual machine is equal to placing that virtual machine into Hibernate mode.

Suspending a Virtual Machine

  1. Click and select a running virtual machine.

  2. Click Suspend or right-click the virtual machine and select Suspend from the pop-up menu.

The Status of the virtual machine changes to Suspended.

6.3. Rebooting or Resetting a Virtual Machine

You can restart your virtual machines in two different ways; either using reboot or reset.

Several situations can occur where you need to reboot the virtual machine, such as after an update or configuration change. When you reboot, the virtual machine’s console remains open while the guest operating system is restarted.

If a guest operating system can not be loaded or has become unresponsive, you need to reset the virtual machine. When you reset, the virtual machine’s console remains open while the guest operating system is restarted.

The reset reset operation can only be performed from the Administration Portal.

Rebooting a Virtual Machine

To reboot a virtual machine:

  1. Click and select a running virtual machine.

  2. Click Reboot or right-click the virtual machine and select Reboot from the pop-up menu.

  3. Click OK in the Reboot Virtual Machine(s) confirmation window.

Resetting a Virtual Machine

To reset a virtual machine:

  1. Click and select a running virtual machine.

  2. Click the down arrow next to Reboot, then click Reset, or right-click the virtual machine and select Reset from the pop-up menu.

  3. Click OK in the Reset Virtual Machine(s) confirmation window.

During reboot and reset operations, the Status of the virtual machine changes to Reboot In Progress before returning to Up.

6.4. Removing a Virtual Machine

The Remove button is disabled while virtual machines are running; you must shut down a virtual machine before you can remove it.

Removing Virtual Machines

  1. Click and select the virtual machine to remove.

  2. Click Remove.

  3. Optionally, select the Remove Disk(s) check box to remove the virtual disks attached to the virtual machine together with the virtual machine. If the Remove Disk(s) check box is cleared, then the virtual disks remain in the environment as floating disks.

  4. Click OK.

6.5. Cloning a Virtual Machine

You can clone virtual machines without having to create a template or a snapshot first.

Procedure

  1. Click and select the virtual machine to clone.

  2. Click More Actions (), then click Clone VM.

  3. Enter a Clone Name for the new virtual machine.

  4. Click OK.

6.6. Updating Virtual Machine Guest Agents and Drivers

The oVirt guest agents, tools, and drivers provide additional functionality for virtual machines, such as gracefully shutting down or rebooting virtual machines from the VM Portal and Administration Portal. The tools and agents also provide information for virtual machines, including:

  • Resource usage

  • IP addresses

  • Installed applications

The guest tools are distributed as an ISO file that you can attach to virtual machines. This ISO file is packaged as an RPM file that you can install and update from the Engine machine.

6.6.1. Updating the Guest Agents and Drivers on Enterprise Linux

Update the guest agents and drivers on your Enterprise Linux virtual machines to use the latest version.

Updating the Guest Agents and Drivers on Enterprise Linux

  1. Log in to the Enterprise Linux virtual machine.

  2. Update the ovirt-guest-agent-common package:

    # yum update ovirt-guest-agent-common
  3. Restart the service:

    • For Enterprise Linux 6

      # service ovirt-guest-agent restart
    • For Enterprise Linux 7

      # systemctl restart ovirt-guest-agent.service

6.6.2. Updating Windows drivers with Windows Update

When you need to update the drivers for a Windows virtual machine, the simplest method is to use Windows Update.

Procedure

  1. Log in to the virtual machine.

  2. Ensure that Windows Update is enabled so you can get updates.

  3. Check Windows Update for updates from Red Hat, Inc.

  4. Manually install any updates that have not been automatically installed.

Additional resources

  • Updating Windows guest agents and drivers using the command prompt

  • See the Microsoft documentation for details on using Windows Update.

6.6.3. Updating Windows guest agents and drivers using the command prompt

When you do not have access to Windows Update to update Windows drivers, or when you need to update the oVirt guest agents, you can do so from the virtio-win package by using the virtual machine’s command prompt. During this procedure, you must remove and reinstall the drivers, which can lead to network disruption. This procedure restores your settings after reinstalling the drivers.

Procedure

  1. If you are updating the drivers, on the Windows virtual machine, use the netsh utility to save TCP settings before uninstalling the netkvm driver:

    C:\WINDOWS\system32>netsh dump > filename.txt
  2. On the Engine machine, update the virtio-win package to the latest version:

    # dnf upgrade -y virtio-win

    The virtio-win_version.iso file is located in /usr/share/virtio-win/ on the Engine machine.

  3. Upload the ISO file to a data domain. For more information, see Uploading Images to a Data Storage Domain in the Administration Guide.

  4. In the Administration or VM Portal, if the virtual machine is running, use the Change CD drop-down list to attach the virtio-win_version.iso file to each of your virtual machines. If the virtual machine is powered off, click the Run Once button and attach the ISO as a CD.

  5. Log in to the virtual machine.

  6. Select the CD Drive (D:\ for this example) containing the virtio-win_version.iso file.

  7. Reinstall the guest agents or drivers:

    • To reinstall only the guest agents, use qemu-ga-x86_64.msi:

      C:\WINDOWS\system32>msiexec.exe /i D:\guest-agent\qemu-ga-x86_64.msi /passive /norestart
    • To reinstall the drivers, use virtio-win-gt-x64.msi:

      C:\WINDOWS\system32>msiexec.exe /i D:\virtio-win-gt-x64.msi /passive /norestart
  8. If you are updating the drivers, restore the settings you saved using netsh:

    C:\WINDOWS\system32>netsh -f filename.txt

6.7. Viewing Red Hat Satellite Errata for a Virtual Machine

Errata for each virtual machine can be viewed after the oVirt virtual machine has been configured to receive errata information from the Red Hat Satellite server.

For more information on configuring a virtual machine to display available errata see Configuring Satellite Errata

Viewing Red Hat Satellite Errata

  1. Click .

  2. Click the virtual machine’s name to go to the details view.

  3. Click Errata.

6.8. Virtual Machines and Permissions

6.8.1. Managing System Permissions for a Virtual Machine

As the SuperUser, the system administrator manages all aspects of the Administration Portal. More specific administrative roles can be assigned to other users. These restricted administrator roles are useful for granting a user administrative privileges that limit them to a specific resource. For example, a DataCenterAdmin role has administrator privileges only for the assigned data center with the exception of the storage for that data center, and a ClusterAdmin has administrator privileges only for the assigned cluster.

A UserVmManager is a system administration role for virtual machines in a data center. This role can be applied to specific virtual machines, to a data center, or to the whole virtualized environment; this is useful to allow different users to manage certain virtual resources.

The user virtual machine administrator role permits the following actions:

  • Create, edit, and remove virtual machines.

  • Run, suspend, shutdown, and stop virtual machines.

You can only assign roles and permissions to existing users.

Many end users are concerned solely with the virtual machine resources of the virtualized environment. As a result, oVirt provides several user roles which enable the user to manage virtual machines specifically, but not other resources in the data center.

6.8.2. Virtual Machine Administrator Roles Explained

The table below describes the administrator roles and privileges applicable to virtual machine administration.

Table 14. oVirt System Administrator Roles

Role Privileges Notes

DataCenterAdmin

Data Center Administrator

Possesses administrative permissions for all objects underneath a specific data center except for storage.

ClusterAdmin

Cluster Administrator

Possesses administrative permissions for all objects underneath a specific cluster.

NetworkAdmin

Network Administrator

Possesses administrative permissions for all operations on a specific logical network. Can configure and manage networks attached to virtual machines. To configure port mirroring on a virtual machine network, apply the NetworkAdmin role on the network and the UserVmManager role on the virtual machine.

6.8.3. Virtual Machine User Roles Explained

The table below describes the user roles and privileges applicable to virtual machine users. These roles allow access to the VM Portal for managing and accessing virtual machines, but they do not confer any permissions for the Administration Portal.

Table 15. oVirt System User Roles

Role Privileges Notes

UserRole

Can access and use virtual machines and pools.

Can log in to the VM Portal and use virtual machines and pools.

PowerUserRole

Can create and manage virtual machines and templates.

Apply this role to a user for the whole environment with the Configure window, or for specific data centers or clusters. For example, if a PowerUserRole is applied on a data center level, the PowerUser can create virtual machines and templates in the data center. Having a PowerUserRole is equivalent to having the VmCreator, DiskCreator, and TemplateCreator roles.

UserVmManager

System administrator of a virtual machine.

Can manage virtual machines and create and use snapshots. A user who creates a virtual machine in the VM Portal is automatically assigned the UserVmManager role on the machine.

UserTemplateBasedVm

Limited privileges to only use Templates.

Level of privilege to create a virtual machine by means of a template.

VmCreator

Can create virtual machines in the VM Portal.

This role is not applied to a specific virtual machine; apply this role to a user for the whole environment with the Configure window. When applying this role to a cluster, you must also apply the DiskCreator role on an entire data center, or on specific storage domains.

VnicProfileUser

Logical network and network interface user for virtual machines.

If the Allow all users to use this Network option was selected when a logical network is created, VnicProfileUser permissions are assigned to all users for the logical network. Users can then attach or detach virtual machine network interfaces to or from the logical network.

6.8.4. Assigning Virtual Machines to Users

If you are creating virtual machines for users other than yourself, you have to assign roles to the users before they can use the virtual machines. Note that permissions can only be assigned to existing users. See Users and Roles in the Administration Guide for details on creating user accounts.

The VM Portal supports three default roles: User, PowerUser and UserVmManager. However, customized roles can be configured via the Administration Portal. The default roles are described below.

  • A User can connect to and use virtual machines. This role is suitable for desktop end users performing day-to-day tasks.

  • A PowerUser can create virtual machines and view virtual resources. This role is suitable if you are an administrator or manager who needs to provide virtual resources for your employees.

  • A UserVmManager can edit and remove virtual machines, assign user permissions, use snapshots and use templates. It is suitable if you need to make configuration changes to your virtual environment.

When you create a virtual machine, you automatically inherit UserVmManager privileges. This enables you to make changes to the virtual machine and assign permissions to the users you manage, or users who are in your Identity Management (IdM) or RHDS group. See the Administration Guide for more information.

Procedure

  1. Click and select a virtual machine.

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Permissions tab.

  4. Click Add.

  5. Enter a name, or user name, or part thereof in the Search text box, and click Go. A list of possible matches display in the results list.

  6. Select the check box of the user to be assigned the permissions.

  7. Select UserRole from the Role to Assign drop-down list.

  8. Click OK.

The user’s name and role display in the list of users permitted to access this virtual machine.

If a user is assigned permissions to only one virtual machine, single sign-on (SSO) can be configured for the virtual machine. With single sign-on enabled, when a user logs in to the VM Portal, and then connects to a virtual machine through, for example, a SPICE console, users are automatically logged in to the virtual machine and do not need to type in the user name and password again. Single sign-on can be enabled or disabled on a per virtual machine basis. See Configuring Single Sign-On for Virtual Machines for more information on how to enable and disable single sign-on for virtual machines.

6.8.5. Removing Access to Virtual Machines from Users

Removing Access to Virtual Machines from Users

  1. Click .

  2. Click the virtual machine’s name to go to the details view.

  3. Click Permissions.

  4. Click Remove. A warning message displays, asking you to confirm removal of the selected permissions.

  5. To proceed, click OK. To abort, click Cancel.

6.9. Snapshots

6.9.1. Creating a Snapshot of a Virtual Machine

A snapshot is a view of a virtual machine’s operating system and applications on any or all available disks at a given point in time. Take a snapshot of a virtual machine before you make a change to it that may have unintended consequences. You can use a snapshot to restore a virtual machine to a previous state.

Creating a Snapshot of a Virtual Machine

In the VM Portal:

  1. Open a virtual machine.

  2. In the Snapshots panel, click +Create Snapshot.

    A snapshot is added to the panel, including all attached disks.

In the Administration Portal:

  1. Click .

  2. Click a virtual machine’s name to go to the details view.

  3. Click the Snapshots tab and click Create.

  4. Enter a description for the snapshot.

  5. Select Disks to include using the check boxes.

    If no disks are selected, a partial snapshot of the virtual machine, without a disk, is created. You can preview this snapshot to view the configuration of the virtual machine. Note that committing a partial snapshot will result in a virtual machine without a disk.

  6. Select Save Memory to include a running virtual machine’s memory in the snapshot.

  7. Click OK.

The virtual machine’s operating system and applications on the selected disk(s) are stored in a snapshot that can be previewed or restored. The snapshot is created with a status of Locked, which changes to Ok. When you click the snapshot, its details are shown on the General, Disks, Network Interfaces, and Installed Applications drop-down views in the Snapshots tab.

6.9.2. Using a Snapshot to Restore a Virtual Machine

A snapshot can be used to restore a virtual machine to its previous state.

Using Snapshots to Restore Virtual Machines

In the VM Portal:

  1. Shutdown the virtual machine.

  2. In the Snapshots panel, click the Restore Snapshot icon for the snapshot you want to restore.

    The snapshot is loaded.

In the Administration Portal:

  1. Click and select a virtual machine.

  2. Click the name of the virtual machine to go to the details view.

  3. Shut down the virtual machine.

  4. Click the Snapshots tab to list the available snapshots.

  5. Select a snapshot to restore in the upper pane. The snapshot details display in the lower pane.

  6. Click the Preview drop-down menu button and select Custom.

  7. Use the check boxes to select the VM Configuration, Memory, and disk(s) you want to restore, then click OK. This allows you to create and restore from a customized snapshot using the configuration and disk(s) from multiple snapshots.

    The status of the snapshot changes to Preview Mode. The status of the virtual machine briefly changes to Image Locked before returning to Down.

  8. Start the virtual machine; it runs using the disk image of the snapshot.

  9. Click Commit to permanently restore the virtual machine to the condition of the snapshot. Any subsequent snapshots are erased.

    Alternatively, click the Undo button to deactivate the snapshot and return the virtual machine to its previous state.

6.9.3. Creating a Virtual Machine from a Snapshot

You can use a snapshot to create another virtual machine.

Creating a Virtual Machine from a Snapshot

  1. Click and select a virtual machine.

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Snapshots tab to list the available snapshots.

  4. Select a snapshot in the list displayed and click Clone.

  5. Enter the Name of the virtual machine.

  6. Click OK.

After a short time, the cloned virtual machine appears in the Virtual Machines tab in the navigation pane with a status of Image Locked. The virtual machine remains in this state until oVirt completes the creation of the virtual machine. A virtual machine with a preallocated 20 GB hard drive takes about fifteen minutes to create. Sparsely-allocated virtual disks take less time to create than do preallocated virtual disks.

When the virtual machine is ready to use, its status changes from Image Locked to Down in .

6.9.4. Deleting a Snapshot

You can delete a virtual machine snapshot and permanently remove it from your oVirt environment.

Deleting a Snapshot

In the VM Portal:

  1. Open a virtual machine.

  2. In the Snapshots panel, click the Delete Snapshot icon of the snapshot you want to delete.

In the Administration Portal:

  1. Click .

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Snapshots tab to list the snapshots for that virtual machine.

  4. Select the snapshot to delete.

  5. Click Delete.

  6. Click OK.

If the deletion fails, fix the underlying problem (for example, a failed host, an inaccessible storage device, or a temporary network issue) and try again.

6.10. Host Devices

6.10.1. Adding a Host Device to a Virtual Machine

To improve performance, you can attach a host device to a virtual machine.

Host devices are physical devices connected to a particular host machine, such as:

  • SCSI tape drives, disks, and changers

  • PCI NICs, GPUs, and HBAs

  • USB mice, cameras, and disks

To add a host device to a virtual machine, you use the virtual machine’s Host Devices properties. First, you select one of the cluster hosts and a device type. Then, you choose and attach one or more of the host devices on that host.

When you change the Pinned Host setting, it removes the current host devices. When you save these changes, in the virtual machine’s Host settings, it sets Start Running On to Specific Host(s) and specifies the host you selected earlier using the Pinned Host setting.

When you finish attaching one or more host devices, you run the virtual machine to apply the changes. The virtual machine starts on the host that has the attached host devices.

If the virtual machine cannot start on the specified host or access the host device, it cancels the start operation and produces an error message with information about the cause.

Prerequisites

  • The state of the host is Up.

  • The host is configured for direct device assignment.

Procedure

  1. In the Administration Portal, click .

  2. Shut down the virtual machine.

  3. Click the name of the virtual machine to go to the details view.

  4. Click the Host Devices tab.

  5. Click Add device. This opens the Add Host Devices pane.

  6. Use Pinned Host to select the host where the virtual machine runs.

  7. Use Capability to list pci, scsi, nvdimm, or usb_device devices.

    The nvdimm option is a technical preview feature. For more information, see nvdimm host devices.

  8. Use Available Host Devices to select devices.

  9. Click the down arrow to move devices to Host Devices to be attached.

  10. Click OK to attach these devices to the virtual machine and close the window.

  11. Optional: If you attach a SCSI host device, configure the optimal driver.

    1. Click the Edit button. This opens the Edit Virtual Machine pane.

    2. Click the Custom Properties tab.

    3. Click the Please select a key and select scsi_hostdev from the bottom of the drop-down list.

    4. In most cases, select scsi-hd. Otherwise, for tape or CD changer devices, select the scsi_generic option. For more details, see Virtual Machine Custom Properties Settings Explained.

    5. Click the OK button.

  12. Run the virtual machine.

  13. While the virtual machine starts running, watch for Operation Canceled error messages.

Troubleshooting

If you cannot add a host device to a virtual machine, or a virtual machine cannot start running with the attached host devices, it generates Operation Canceled error messages. For example:

Operation Canceled
Error while executing action:

<vm name>:
* Cannot run VM. There is no host that satisfies current scheduling constraints. See below for details:
* The host <first_hostname> did not satisfy internal filter HostDevice because it does not support host device passthrough.
* The host <second_hostname> did not satisfy internal filter HostDevice because the host does not provide requested host devices.

You can fix the error by removing the host device from the virtual machine or correcting the issues the error message describes. For example:

  • Respond to a The host <hostname> did not satisfy internal filter HostDevice because it does not support host device passthrough message by configuring the host for device passthrough and restarting the virtual machine.

  • Respond to the The host <hostname> did not satisfy internal filter HostDevice because the host does not provide requested host devices message by adding the host device to the host.

  • Respond to a Cannot add Host devices because the VM is in Up status message by shutting down the virtual machine before adding a host device.

  • Verify that the state of the host is Up.

Additional resources

  • Host Devices in the Virtual Machine Management Guide.

  • Pinning a Virtual Machine to Multiple Hosts

  • Configuring a Host for PCI Passthrough

  • Additional Hardware Considerations for Using Device Assignment in Hardware Considerations for Implementing SR-IOV.

  • nvdimm host devices

6.10.2. Removing Host Devices from a Virtual Machine

If you are removing all host devices directly attached to the virtual machine in order to add devices from a different host, you can instead add the devices from the desired host, which will automatically remove all of the devices already attached to the virtual machine.

Procedure

  1. Click .

  2. Select a virtual machine to go to the details view.

  3. Click the Host Devices tab to list the host devices attached to the virtual machine.

  4. Select the host device to detach from the virtual machine, or hold Ctrl to select multiple devices, and click Remove device. This opens the Remove Host Device(s) window.

  5. Click OK to confirm and detach these devices from the virtual machine.

6.10.3. Pinning a Virtual Machine to Another Host

You can use the Host Devices tab in the details view of a virtual machine to pin it to a specific host.

If the virtual machine has any host devices attached to it, pinning it to another host automatically removes the host devices from the virtual machine.

Pinning a Virtual Machine to a Host

  1. Click a virtual machine name and click the Host Devices tab.

  2. Click Pin to another host. This opens the Pin VM to Host window.

  3. Use the Host drop-down menu to select a host.

  4. Click OK to pin the virtual machine to the selected host.

6.10.4. NVDIMM host devices

NVDIMM devices are Technology Preview features only. Technology Preview features are not supported with Red Hat production service-level agreements (SLAs) and might not be functionally complete, and Red Hat does not recommend using them for production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process. For more information, see Red Hat Technology Preview Features Support Scope.

You can add emulated NVDIMM devices to virtual machines. Elsewhere, this type of memory is also known as virtual NVDIMM or vNVDIMM.

The emulated NVDIMM you can attach to a virtual machine is backed by real NVDIMM on the host machine where the virtual machine runs. Therefore, when you attach NVDIMM to a virtual machine, you also pin the virtual machine to a specific host.

You can reconfigure the mode, partitioning, and other properties of the emulated NVDIMM device in the virtual machine without affecting the settings of the physical NVDIMM on the host device.

To add emulated NVDIMM to a virtual machine, see Adding Host Devices to a Virtual Machine

Limitations

  • Memory snapshots are disabled when an NVDIMM device is present in a virtual machine. There is no way to make a snapshot of NVDIMM content, and a memory snapshot cannot work correctly without having the corresponding NVDIMM data.

  • In oVirt, each NVDIMM device passed to a virtual machine has an automatically-assigned label area with a fixed size of 128 KB. IBM POWER hardware, and 128 KB is the minimum label size allowed by QEMU.

  • By default, the virtual machine uses the whole NVDIMM device. You cannot configure the size of the NVDIMM from the virtual machine. To configure its size, partition the NVDIMM device on the host and add the partition to the virtual machine.

  • The size of the NVDIMM device on the virtual machine may be slightly lower than on the host to comply with libvirt and QEMU alignment and size adjustments. Precise sizing is also needed to make memory hotplug work.

  • libvirt and QEMU adjust their size and label placement. If those internal arrangements change, it can cause data loss.

  • NVDIMM hotplug is not supported by the platform.

  • Virtual machines with NVDIMM devices cannot migrate because they are pinned to a host.

  • SELinux currently prevents access to NVDIMM devices in devdax mode. As a result, data persistence cannot be guaranteed if the host fails. See BZ1855336.

Avoid using NVDIMM on IBM POWER hardware. This combination is currently not expected to be stable until further work is completed.

6.11. Affinity Groups

6.11.1. Affinity Groups

You can create Affinity Groups to help determine where selected virtual machines run in relation to each other and to specified hosts. This capability helps manage workload scenarios such as licensing requirements, high-availability workloads, and disaster recovery.

The VM Affinity Rule

When you create an Affinity Group, you select the virtual machines that belong to the group. To define where these virtual machines can run in relation to each other, you enable a VM Affinity Rule: A Positive affinity rule tries to run the virtual machines together on a single host; a Negative affinity rule tries to run the virtual machines on separate hosts. If the rule cannot be fulfilled, the outcome depends on whether the weight or filter module is enabled.

The Host Affinity Rule

Optionally, you can add hosts to the Affinity Group. To define where virtual machines in the group can run in relation to hosts in the group, you enable a Host Affinity Rule: A Positive affinity rule tries to run the virtual machines on hosts in the affinity group; a Negative affinity rule tries to run the virtual machines on hosts that are not in the affinity group. If the rule cannot be fulfilled, the outcome depends on whether the weight or filter module is enabled.

The Default Weight Module

By default, both rules apply the weight module in the cluster’s scheduling policy. With the weight module, the scheduler attempts to fulfill a rule, but allows the virtual machines in the affinity group to run anyway if the rule cannot be fulfilled.

For example, with a positive VM Affinity Rule and the weight module enabled, the scheduler tries to run all of the affinity group’s virtual machines on a single host. However, if a single host does not have sufficient resources for this, the scheduler runs the virtual machines on multiple hosts.

For this module to work, the weight module section of the scheduling policies must contain the VmAffinityGroups and VmToHostsAffinityGroups keywords.

The Enforcing Option and Filter Module

Both rules have an Enforcing option which applies the filter module in the cluster’s scheduling policy. The filter module overrides the weight module. With the filter module enabled, the scheduler requires that a rule be fulfilled. If a rule cannot be fulfilled, the filter module prevents the virtual machines in the affinity group from running.

For example, with a Positive Host Affinity Rule and Enforcing enabled (the filter module enabled), the scheduler requires the virtual machines in the affinity group to run on hosts that are part of the affinity group. However, if those hosts are down, the scheduler does not run the virtual machines at all.

For this module to work, the filter module section of the scheduling policies must contain the VmAffinityGroups and VmToHostsAffinityGroups keywords.

Examples

To see how these rules and options can be used with one another, see Affinity group examples.

  • For affinity labels to work, the filter module section of the scheduling policies must contain Label.

  • If an affinity group and affinity label conflict with each other, the affected virtual machines do not run. To help prevent, troubleshoot, and resolve conflicts, see Affinity group troubleshooting.

Each rule is affected by the weight and filter modules in the cluster’s scheduling policy.

  • For the VM Affinity Rule rule to work, the scheduling policy must have the VmAffinityGroups keyword in its Weight module and Filter module sections.

  • For the Host Affinity Rule to work, the scheduling policy must have the VmToHostsAffinityGroups keyword in its Weight module and Filter module sections.

  • Affinity groups apply to virtual machines in a cluster. Moving a virtual machine from one cluster to another removes it from the affinity groups in the original cluster.

  • Virtual machines do not have to restart for the affinity group rules to take effect.

6.11.2. Creating an Affinity Group

You can create new affinity groups in the Administration Portal.

Creating Affinity Groups

  1. Click and select a virtual machine.

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Affinity Groups tab.

  4. Click New.

  5. Enter a Name and Description for the affinity group.

  6. From the VM Affinity Rule drop-down, select Positive to apply positive affinity or Negative to apply negative affinity. Select Disable to disable the affinity rule.

  7. Select the Enforcing check box to apply hard enforcement, or ensure this check box is cleared to apply soft enforcement.

  8. Use the drop-down list to select the virtual machines to be added to the affinity group. Use the + and buttons to add or remove additional virtual machines.

  9. Click OK.

6.11.3. Editing an Affinity Group

Editing Affinity Groups

  1. Click and select a virtual machine.

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Affinity Groups tab.

  4. Click Edit.

  5. Change the VM Affinity Rule drop-down and Enforcing check box to the preferred values and use the + and buttons to add or remove virtual machines to or from the affinity group.

  6. Click OK.

6.11.4. Removing an Affinity Group

Removing Affinity Groups

  1. Click and select a virtual machine.

  2. Click the virtual machine’s name to go to the details view.

  3. Click the Affinity Groups tab.

  4. Click Remove.

  5. Click OK.

The affinity policy that applied to the virtual machines that were members of that affinity group no longer applies.

6.11.5. Affinity Groups Examples

The following examples illustrate how to apply affinity rules for various scenarios, using the different features of the affinity group capability described in this chapter.

Example 1. High Availability

Dalia is the DevOps engineer for a startup. For high availability, a particular system’s two virtual machines should run on separate hosts anywhere in the cluster.

Dalia creates an affinity group named «high availability» and does the following:

  • Adds the two virtual machines, VM01 and VM02, to the affinity group.

  • Sets VM Affinity to Negative so the virtual machines try to run on separate hosts.

  • Leaves Enforcing cleared (disabled) so that both virtual machines can continue running in case only one host is available during an outage.

  • Leaves the Hosts list empty so the virtual machines run on any host in the cluster.

Example 2. Performance

Sohni is a software developer who uses two virtual machines to build and test his software many times each day. There is heavy network traffic between these two virtual machines. Running the machines on the same host reduces both network traffic and the effects of network latency on the build and test process. Using high-specification hosts (faster CPUs, SSDs, and more memory) further accelerates this process.

Sohni creates an affinity group called «build and test» and does the following:

  • Adds VM01 and VM02, the build and test virtual machines, to the affinity group.

  • Adds the high-specification hosts, host03, host04, and host05, to the affinity group.

  • Sets VM affinity to Positive so the virtual machines try to run on the same host, reducing network traffic and latency effects.

  • Sets Host affinity to Positive so the virtual machines try to run on the high specification hosts, accelerating the process.

  • Leaves Enforcing cleared (disabled) for both rules so the virtual machines can run if the high-specification hosts are not available.

Example 3. Licensing

Bandile, a software asset manager, helps his organization comply with the restrictive licensing requirements of a 3D imaging software vendor. These terms require the virtual machines for its licensing server, VM-LS, and imaging workstations, VM-WS#, to run on the same host. Additionally, the physical CPU-based licensing model requires that the workstations run on either of two GPU-equipped hosts, host-gpu-primary or host-gpu-backup.

To meet these requirements, Bandile creates an affinity group called «3D seismic imaging» and does the following:

  • Adds the previously mentioned virtual machines and hosts to the affinity group.

  • Sets VM affinity to Positive and selects Enforcing so the licensing server and workstations must run together on one of the hosts, not on multiple hosts.

  • Sets Host affinity to Positive and selects Enforcing so the virtual machines must run on either of the GPU-equipped the hosts, not other hosts in the cluster.

6.11.6. Affinity Groups Troubleshooting

To help prevent problems with affinity groups

  • Plan and document the scenarios and outcomes you expect when using affinity groups.

  • Verify and test the outcomes under a range of conditions.

  • Follow change management best practices.

  • Only use the Enforcing option if it is required.

For possible conflicts between affinity labels and affinity groups

  • If an affinity label and affinity group conflict with each other, the intersecting set of virtual machines do not run.

  • To determine whether a conflict is possible:

    • Inspect the filter module section of the cluster’s scheduling policies. These must contain both a Label keyword and a VmAffinityGroups OR VmToHostsAffinityGroups keyword. Otherwise, a conflict is not possible. (The presence of VmAffinityGroups and VmToHostsAffinityGroups in the weight module section does not matter because Label in a filter module section would override them.)

    • Inspect the affinity groups. They must contain a rule that has Enforcing enabled. Otherwise, a conflict is not possible.

  • If a conflict is possible, identify the set of virtual machines that might be involved:

    • Inspect the affinity labels and groups. Make a list of virtual machines that are members of both an affinity label and an affinity group with an Enforcing option enabled.

    • For each host and virtual machine in this intersecting set, analyze the conditions under which a potential conflict occurs.

  • Determine whether the actual non-running virtual machines match the ones in the analysis.

  • Restructure the affinity groups and affinity labels to help avoid unintended conflicts.

  • Verify that any changes produce the expected results under a range of conditions.

  • If you have overlapping affinity groups and affinity labels, it can be easier to view them in one place as affinity groups. Consider converting an affinity label into an equivalent affinity group, which has a Host affinity rule with Positive selected and Enforcing enabled.

6.12. Affinity Labels

6.12.1. About Affinity Labels

You can create and modify Affinity Labels in the Administration Portal.

Affinity Labels are used together with Affinity Groups to set any kind of affinity between virtual machines and hosts (hard, soft, positive, negative). See the Affinity Groups section for more information about affinity hardness and polarity.

Affinity labels are a subset of affinity groups and can conflict with them. If there is a conflict, the virtual machine will not start.

6.12.2. Creating an Affinity Label

You can create affinity labels from the details view of a virtual machine, host, or cluster. This procedure uses the cluster details view.

Creating an Affinity Label

  1. Click and select the appropriate cluster.

  2. Click the cluster’s name to go to the details view.

  3. Click the Affinity Labels tab.

  4. Click New.

  5. Enter a Name for the affinity label.

  6. Use the drop-down lists to select the virtual machines and hosts to be associated with the label. Use the + button to add additional virtual machines and hosts.

  7. Click OK.

6.12.3. Editing an Affinity Label

You can edit affinity labels from the details view of a virtual machine, host, or cluster. This procedure uses the cluster details view.

Editing an Affinity Label

  1. Click and select the appropriate cluster.

  2. Click the cluster’s name to go to the details view.

  3. Click the Affinity Labels tab.

  4. Select the label you want to edit.

  5. Click Edit.

  6. Use the + and buttons to add or remove virtual machines and hosts to or from the affinity label.

  7. Click OK.

6.12.4. Deleting an Affinity Label

You can only remove an Affinity Label from the details view of a cluster after it is deleted from each entity.

Deleting an Affinity Label

  1. Click and select the appropriate cluster.

  2. Click the cluster’s name to go to the details view.

  3. Click the Affinity Labels tab.

  4. Select the label you want to remove.

  5. Click Edit.

  6. Use the buttons to remove all virtual machines and hosts from the label.

  7. Click OK.

  8. Click Delete.

  9. Click OK.

6.13. Exporting and Importing Virtual Machines and Templates

The export storage domain is deprecated. Storage data domains can be unattached from a data center and imported to another data center in the same environment, or in a different environment. Virtual machines, floating virtual disks, and templates can then be uploaded from the imported storage domain to the attached data center. See the Importing Existing Storage Domains section in the oVirt Administration Guide for information on importing storage domains.

You can export virtual machines and templates from, and import them to, data centers in the same or different Red Hat Virtualization environment. You can export or import virtual machines by using an export domain, a data domain, or by using a Red Hat Virtualization host.

When you export or import a virtual machine or template, properties including basic details such as the name and description, resource allocation, and high availability settings of that virtual machine or template are preserved.

The permissions and user roles of virtual machines and templates are included in the OVF files, so that when a storage domain is detached from one data center and attached to another, the virtual machines and templates can be imported with their original permissions and user roles. In order for permissions to be registered successfully, the users and roles related to the permissions of the virtual machines or templates must exist in the data center before the registration process.

You can also use the V2V feature to import virtual machines from other virtualization providers, such as RHEL 5 Xen or VMware, or import Windows virtual machines. V2V converts virtual machines so that they can be hosted by oVirt. For more information on installing and using V2V, see Converting Virtual Machines from Other Hypervisors to KVM with virt-v2v.

Virtual machines must be shut down before being imported.

6.13.1. Exporting a Virtual Machine to the Export Domain

Export a virtual machine to the export domain so that it can be imported into a different data center. Before you begin, the export domain must be attached to the data center that contains the virtual machine to be exported.

Exporting a Virtual Machine to the Export Domain

  1. Click and select a virtual machine.

  2. Click More Actions (), then click Export to Export Domain.

  3. Optionally, select the following check boxes in the Export Virtual Machine window:

    • Force Override: overrides existing images of the virtual machine on the export domain.

    • Collapse Snapshots: creates a single export volume per disk. This option removes snapshot restore points and includes the template in a template-based virtual machine, and removes any dependencies a virtual machine has on a template. For a virtual machine that is dependent on a template, either select this option, export the template with the virtual machine, or make sure the template exists in the destination data center.

      When you create a virtual machine from a template by clicking and clicking New VM, you wll see two storage allocation options in the Storage Allocation section in the Resource Allocation tab:

      • If Clone is selected, the virtual machine is not dependent on the template. The template does not have to exist in the destination data center.

      • If Thin is selected, the virtual machine is dependent on the template, so the template must exist in the destination data center or be exported with the virtual machine. Alternatively, select the Collapse Snapshots check box to collapse the template disk and virtual disk into a single disk.

      To check which option was selected, click a virtual machine’s name and click the General tab in the details view.

  4. Click OK.

The export of the virtual machine begins. The virtual machine displays in with an Image Locked status while it is exported. Depending on the size of your virtual machine hard disk images, and your storage hardware, this can take up to an hour. Click the Events tab to view progress. When complete, the virtual machine has been exported to the export domain and displays in the VM Import tab of the export domain’s details view.

6.13.2. Exporting a Virtual Machine to a Data Domain

You can export a virtual machine to a data domain to store a clone of the virtual machine as a backup.

When you export a virtual machine that is dependent on a template, the target storage domain should include that template.

When you create a virtual machine from a template, you can choose from either of two storage allocation options:

  • Clone: The virtual machine is not dependent on the template. The template does not have to exist in the destination storage domain.

  • Thin: The virtual machine is dependent on the template, so the template must exist in the destination storage domain.

To check which option is selected, click a virtual machine’s name and click the General tab in the details view.

Prerequisites

  • The data domain is attached to a data center.

  • The virtual machine is powered off.

    Procedure

    1. Click and select a virtual machine.

    2. Click Export.

    3. Specify a name for the exported virtual machine.

    4. Select a target storage domain from the Storage domain pop-up menu.

    5. (Optional) Check Collapse snapshots to export the virtual machine without any snapshots.

    6. Click OK.

The Engine clones the virtual machine, including all its disks, to the target domain.

When you move a disk from one type of data domain another, the disk format changes accordingly. For example, if the disk is on an NFS data domain, and it is in sparse format, then if you move the disk to an iSCSI domain its format changes to preallocated. This is different from using an export domain, because an export domain is NFS.

The virtual machine appears with an Image Locked status while it is exported. Depending on the size of your virtual machine hard disk images, and your storage hardware, this can take up to an hour. Click the Events tab to view progress. When complete, the virtual machine has been exported to the data domain and appears in the list of virtual machines.

6.13.3. Importing a Virtual Machine from the Export Domain

You have a virtual machine on an export domain. Before the virtual machine can be imported to a new data center, the export domain must be attached to the destination data center.

Importing a Virtual Machine into the Destination Data Center

  1. Click and select the export domain. The export domain must have a status of Active.

  2. Click the export domain’s name to go to the details view.

  3. Click the VM Import tab to list the available virtual machines to import.

  4. Select one or more virtual machines to import and click Import.

  5. Select the Target Cluster.

  6. Select the Collapse Snapshots check box to remove snapshot restore points and include templates in template-based virtual machines.

  7. Click the virtual machine to be imported and click the Disks sub-tab. From this tab, you can use the Allocation Policy and Storage Domain drop-down lists to select whether the disk used by the virtual machine will be thinly provisioned or preallocated, and can also select the storage domain on which the disk will be stored. An icon is also displayed to indicate which of the disks to be imported acts as the boot disk for that virtual machine.

  8. Click OK to import the virtual machines.

    The Import Virtual Machine Conflict window opens if the virtual machine exists in the virtualized environment.

    Choose one of the following radio buttons:

    • Don’t import

    • Import as cloned and enter a unique name for the virtual machine in the New Name field.

  9. Optionally select the Apply to all check box to import all duplicated virtual machines with the same suffix, and then enter a suffix in the Suffix to add to the cloned VMs field.

  10. Click OK.

During a single import operation, you can only import virtual machines that share the same architecture. If any of the virtual machines to be imported have a different architecture to that of the other virtual machines to be imported, a warning will display and you will be prompted to change your selection so that only virtual machines with the same architecture will be imported.

6.13.4. Importing a Virtual Machine from a Data Domain

You can import a virtual machine into one or more clusters from a data storage domain.

Prerequisite

  • If you are importing a virtual machine from an imported data storage domain, the imported storage domain must be attached to a data center and activated.

Procedure

  1. Click .

  2. Click the imported storage domain’s name. This opens the details view.

  3. Click the VM Import tab.

  4. Select one or more virtual machines to import.

  5. Click Import.

  6. For each virtual machine in the Import Virtual Machine(s) window, ensure the correct target cluster is selected in the Cluster list.

  7. Map external virtual machine vNIC profiles to profiles that are present on the target cluster(s):

    1. Click vNic Profiles Mapping.

    2. Select the vNIC profile to use from the Target vNic Profile drop-down list.

    3. If multiple target clusters are selected in the Import Virtual Machine(s) window, select each target cluster in the Target Cluster drop-down list and ensure the mappings are correct.

    4. Click OK.

  8. If a MAC address conflict is detected, an exclamation mark appears next to the name of the virtual machine. Mouse over the icon to view a tooltip displaying the type of error that occurred.

    Select the Reassign Bad MACs check box to reassign new MAC addresses to all problematic virtual machines. Alternatively, you can select the Reassign check box per virtual machine.

    If there are no available addresses to assign, the import operation will fail. However, in the case of MAC addresses that are outside the cluster’s MAC address pool range, it is possible to import the virtual machine without reassigning a new MAC address.

  9. Click OK.

The imported virtual machines no longer appear in the list under the VM Import tab.

6.13.5. Importing a Virtual Machine from a VMware Provider

Import virtual machines from a VMware vCenter provider to your oVirt environment. You can import from a VMware provider by entering its details in the Import Virtual Machine(s) window during each import operation, or you can add the VMware provider as an external provider, and select the preconfigured provider during import operations. To add an external provider, see Adding a VMware Instance as a Virtual Machine Provider.

oVirt uses V2V to import VMware virtual machines. For OVA files, the only disk format oVirt supports is VMDK.

The virt-v2v package is not available on the ppc64le architecture and these hosts cannot be used as proxy hosts.

If the import fails, refer to the relevant log file in /var/log/vdsm/import/ and to /var/log/vdsm/vdsm.log on the proxy host for details.

Prerequisites

  • The virt-v2v package must be installed on at least one host, referred to in this procedure as the proxy host. The virt-v2v package is available by default on oVirt Nodes and is installed on Enterprise Linux hosts as a dependency of VDSM when added to the oVirt environment.

  • Enterprise Linux hosts must be Enterprise Linux 7.2 or later.

  • At least one data and one ISO storage domain are connected to the data center.

    You can only migrate to shared storage, such as NFS, iSCSI, or FCP. Local storage is not supported.

    Although the ISO storage domain has been deprecated, it is required for migration.

  • The virtio-win_version.iso image file for Windows virtual machines is uploaded to the ISO storage domain. This image includes the guest tools that are required for migrating Windows virtual machines.

  • The virtual machine must be shut down before being imported. Starting the virtual machine through VMware during the import process can result in data corruption.

  • An import operation can only include virtual machines that share the same architecture. If any virtual machine to be imported has a different architecture, a warning appears and you are prompted to change your selection to include only virtual machines with the same architecture.

Procedure

  1. Click .

  2. Click More Actions () and select Import. This opens the Import Virtual Machine(s) window.

  3. Select VMware from the Source list.

  4. If you have configured a VMware provider as an external provider, select it from the External Provider list. Verify that the provider credentials are correct. If you did not specify a destination data center or proxy host when configuring the external provider, select those options now.

  5. If you have not configured a VMware provider, or want to import from a new VMware provider, provide the following details:

    1. Select from the list the Data Center in which the virtual machine will be available.

    2. Enter the IP address or fully qualified domain name of the VMware vCenter instance in the vCenter field.

    3. Enter the IP address or fully qualified domain name of the host from which the virtual machines will be imported in the ESXi field.

    4. Enter the name of the data center and the cluster in which the specified ESXi host resides in the Data Center field.

    5. If you have exchanged the SSL certificate between the ESXi host and the Engine, leave Verify server’s SSL certificate checked to verify the ESXi host’s certificate. If not, clear the option.

    6. Enter the Username and Password for the VMware vCenter instance. The user must have access to the VMware data center and ESXi host on which the virtual machines reside.

    7. Select a host in the chosen data center with virt-v2v installed to serve as the Proxy Host during virtual machine import operations. This host must also be able to connect to the network of the VMware vCenter external provider.

  6. Click Load to list the virtual machines on the VMware provider that can be imported.

  7. Select one or more virtual machines from the Virtual Machines on Source list, and use the arrows to move them to the Virtual Machines to Import list. Click Next.

    If a virtual machine’s network device uses the driver type e1000 or rtl8139, the virtual machine will use the same driver type after it has been imported to oVirt.

    If required, you can change the driver type to VirtIO manually after the import. To change the driver type after a virtual machine has been imported, see Editing network interfaces. If the network device uses driver types other than e1000 or rtl8139, the driver type is changed to VirtIO automatically during the import. The Attach VirtIO-drivers option allows the VirtIO drivers to be injected to the imported virtual machine files so that when the driver is changed to VirtIO, the device will be properly detected by the operating system.

  8. Select the Cluster in which the virtual machines will reside.

  9. Select a CPU Profile for the virtual machines.

  10. Select the Collapse Snapshots check box to remove snapshot restore points and include templates in template-based virtual machines.

  11. Select the Clone check box to change the virtual machine name and MAC addresses, and clone all disks, removing all snapshots. If a virtual machine appears with a warning symbol beside its name or has a tick in the VM in System column, you must clone the virtual machine and change its name.

  12. Click each virtual machine to be imported and click the Disks sub-tab. Use the Allocation Policy and Storage Domain lists to select whether the disk used by the virtual machine will be thinly provisioned or preallocated, and select the storage domain on which the disk will be stored. An icon is also displayed to indicate which of the disks to be imported acts as the boot disk for that virtual machine.

  13. If you selected the Clone check box, change the name of the virtual machine in the General sub-tab.

  14. Click OK to import the virtual machines.

The CPU type of the virtual machine must be the same as the CPU type of the cluster into which it is being imported. To view the cluster’s CPU Type in the Administration Portal:

  1. Click .

  2. Select a cluster.

  3. Click Edit.

  4. Click the General tab.

If the CPU type of the virtual machine is different, configure the imported virtual machine’s CPU type:

  1. Click .

  2. Select the virtual machine.

  3. Click Edit.

  4. Click the System tab.

  5. Click the Advanced Parameters arrow.

  6. Specify the Custom CPU Type and click OK.

6.13.6. Exporting a Virtual Machine to a Host

You can export a virtual machine to a specific path or mounted NFS shared storage on a host in the oVirt data center. The export will produce an Open Virtual Appliance (OVA) package.

Exporting a Virtual Machine to a Host

  1. Click and select a virtual machine.

  2. Click More Actions (), then click Export to OVA.

  3. Select the host from the Host drop-down list.

  4. Enter the absolute path to the export directory in the Directory field, including the trailing slash. For example: /images2/ova/

  5. Optionally change the default name of the file in the Name field.

  6. Click OK

The status of the export can be viewed in the Events tab.

6.13.7. Importing a Virtual Machine from a Host

Import an Open Virtual Appliance (OVA) file into your oVirt environment. You can import the file from any oVirt Node in the data center.

Importing an OVA File

  1. Copy the OVA file to a host in your cluster, in a file system location such as /var/tmp.

    The location can be a local directory or a remote NFS mount, as long as it is not in the`/root` directory or subdirectories. Ensure that it has sufficient space.

  2. Ensure that the OVA file has permissions allowing read/write access to the qemu user (UID 36) and the kvm group (GID 36):

    # chown 36:36 path_to_OVA_file/file.OVA
  3. Click .

  4. Click More Actions () and select Import. This opens the Import Virtual Machine(s) window.

    1. Select Virtual Appliance (OVA) from the Source list.

    2. Select a host from the Host list.

    3. In the Path field, specify the absolute path of the OVA file.

    4. Click Load to list the virtual machine to be imported.

    5. Select the virtual machine from the Virtual Machines on Source list, and use the arrows to move it to the Virtual Machines to Import list.

  5. Click Next.

    1. Select the Storage Domain for the virtual machine.

    2. Select the Target Cluster where the virtual machines will reside.

    3. Select the CPU Profile for the virtual machines.

    4. Select the Allocation Policy for the virtual machines.

    5. Optionally, select the Attach VirtIO-Drivers check box and select the appropriate image on the list to add VirtIO drivers.

    6. Select the Allocation Policy for the virtual machines.

    7. Select the virtual machine, and on the General tab select the Operating System.

    8. On the Network Interfaces tab, select the Network Name and Profile Name.

    9. Click the Disks tab to view the Alias, Virtual Size, and Actual Size of the virtual machine.

  6. Click OK to import the virtual machines.

6.13.8. Importing a virtual machine from a RHEL 5 Xen host

Import virtual machines from Xen on Enterprise Linux 5 to your oVirt environment. oVirt uses V2V to import QCOW2 or raw virtual machine disk formats.

The virt-v2v package must be installed on at least one host (referred to in this procedure as the proxy host). The virt-v2v package is available by default on oVirt Nodes (oVirt Node) and is installed on Enterprise Linux hosts as a dependency of VDSM when added to the oVirt environment. Enterprise Linux hosts must be Enterprise Linux 7.2 or later.

If you are importing a Windows virtual machine from a RHEL 5 Xen host and you are using VirtIO devices, install the VirtIO drivers before importing the virtual machine. If the drivers are not installed, the virtual machine may not boot after import.

The VirtIO drivers can be installed from the virtio-win_version.iso or the RHV-toolsSetup_version.iso. See Installing the Guest Agents and Drivers on Windows for details.

If you are not using VirtIO drivers, review the configuration of the virutal machine before first boot to ensure that VirtIO devices are not being used.

The virt-v2v package is not available on the ppc64le architecture and these hosts cannot be used as proxy hosts.

An import operation can only include virtual machines that share the same architecture. If any virtual machine to be imported has a different architecture, a warning appears and you are prompted to change your selection to include only virtual machines with the same architecture.

If the import fails, refer to the relevant log file in /var/log/vdsm/import/ and to /var/log/vdsm/vdsm.log on the proxy host for details.

Procedure

To import a virtual machine from RHEL 5 Xen, follow these steps:

  1. Shut down the virtual machine. Starting the virtual machine through Xen during the import process can result in data corruption.

  2. Enable public key authentication between the proxy host and the RHEL 5 Xen host:

    1. Log in to the proxy host and generate SSH keys for the vdsm user.

      # sudo -u vdsm ssh-keygen
    2. Copy the vdsm user’s public key to the RHEL 5 Xen host.

      # sudo -u vdsm ssh-copy-id root@xenhost.example.com
    3. Log in to the RHEL 5 Xen host to verify that the login works correctly.

      # sudo -u vdsm ssh root@xenhost.example.com
  3. Log in to the Administration Portal.

  4. Click .

  5. Click More Actions () and select Import. This opens the Import Virtual Machine(s) window.

  6. Select the Data Center that contains the proxy host.

  7. Select XEN (via RHEL) from the Source drop-down list.

  8. Optionally, select a RHEL 5 Xen External Provider from the drop-down list. The URI will be pre-filled with the correct URI. See Adding a RHEL 5 Xen Host as a Virtual Machine Provider in the Administration Guide for more information.

  9. Enter the URI of the RHEL 5 Xen host. The required format is pre-filled; you must replace <hostname> with the host name of the RHEL 5 Xen host.

  10. Select the proxy host from the Proxy Host drop-down list.

  11. Click Load to list the virtual machines on the RHEL 5 Xen host that can be imported.

  12. Select one or more virtual machines from the Virtual Machines on Source list, and use the arrows to move them to the Virtual Machines to Import list.

    Due to current limitations, Xen virtual machines with block devices do not appear in the Virtual Machines on Source list. They must be imported manually. See Importing Block Based Virtual Machine from Xen host.

  13. Click Next.

  14. Select the Cluster in which the virtual machines will reside.

  15. Select a CPU Profile for the virtual machines.

  16. Use the Allocation Policy and Storage Domain lists to select whether the disk used by the virtual machine will be thinly provisioned or preallocated, and select the storage domain on which the disk will be stored.

    The target storage domain must be a file-based domain. Due to current limitations, specifying a block-based domain causes the V2V operation to fail.

  17. If a virtual machine appears with a warning symbol beside its name, or has a tick in the VM in System column, select the Clone check box to clone the virtual machine.

    Cloning a virtual machine changes its name and MAC addresses and clones all of its disks, removing all snapshots.

  18. Click OK to import the virtual machines.

The CPU type of the virtual machine must be the same as the CPU type of the cluster into which it is being imported. To view the cluster’s CPU Type in the Administration Portal:

  1. Click .

  2. Select a cluster.

  3. Click Edit.

  4. Click the General tab.

If the CPU type of the virtual machine is different, configure the imported virtual machine’s CPU type:

  1. Click .

  2. Select the virtual machine.

  3. Click Edit.

  4. Click the System tab.

  5. Click the Advanced Parameters arrow.

  6. Specify the Custom CPU Type and click OK.

Importing a Block-Based Virtual Machine from a RHEL 5 Xen Host

  1. Enable public key authentication between the proxy host and the RHEL 5 Xen host:

    1. Log in to the proxy host and generate SSH keys for the vdsm user.

      # sudo -u vdsm ssh-keygen
    2. Copy the vdsm user’s public key to the RHEL 5 Xen host.

      # sudo -u vdsm ssh-copy-id root@xenhost.example.com
    3. Log in to the RHEL 5 Xen host to verify that the login works correctly.

      # sudo -u vdsm ssh root@xenhost.example.com
  2. Attach an export domain. See Attaching an Existing Export Domain to a Data Center in the Administration Guide for details.

  3. On the proxy host, copy the virtual machine from the RHEL 5 Xen host:

    # virt-v2v-copy-to-local -ic xen+ssh://root@xenhost.example.com vmname
  4. Convert the virtual machine to libvirt XML and move the file to your export domain:

    # virt-v2v -i libvirtxml vmname.xml -o rhev -of raw -os storage.example.com:/exportdomain
  5. In the Administration Portal, click , click the export domain’s name, and click the VM Import tab in the details view to verify that the virtual machine is in your export domain.

  6. Import the virtual machine into the destination data domain. See Importing the virtual machine from the export domain for details.

6.13.9. Importing a Virtual Machine from a KVM Host

Import virtual machines from KVM to your oVirt environment. oVirt converts KVM virtual machines to the correct format before they are imported. You must enable public key authentication between the KVM host and at least one host in the destination data center (this host is referred to in the following procedure as the proxy host).

The virtual machine must be shut down before being imported. Starting the virtual machine through KVM during the import process can result in data corruption.

An import operation can only include virtual machines that share the same architecture. If any virtual machine to be imported has a different architecture, a warning appears and you are prompted to change your selection to include only virtual machines with the same architecture.

If the import fails, refer to the relevant log file in /var/log/vdsm/import/ and to /var/log/vdsm/vdsm.log on the proxy host for details.

Importing a Virtual Machine from KVM

  1. Enable public key authentication between the proxy host and the KVM host:

    1. Log in to the proxy host and generate SSH keys for the vdsm user.

      # sudo -u vdsm ssh-keygen
    2. Copy the vdsm user’s public key to the KVM host. The proxy host’s known_hosts file will also be updated to include the host key of the KVM host.

      # sudo -u vdsm ssh-copy-id root@kvmhost.example.com
    3. Log in to the KVM host to verify that the login works correctly.

      # sudo -u vdsm ssh root@kvmhost.example.com
  2. Log in to the Administration Portal.

  3. Click .

  4. Click More Actions () and select Import. This opens the Import Virtual Machine(s) window.

  5. Select the Data Center that contains the proxy host.

  6. Select KVM (via Libvirt) from the Source drop-down list.

  7. Optionally, select a KVM provider External Provider from the drop-down list. The URI will be pre-filled with the correct URI. See Adding a KVM Host as a Virtual Machine Provider in the Administration Guide for more information.

  8. Enter the URI of the KVM host in the following format:

    qemu+ssh://root@kvmhost.example.com/system
  9. Keep the Requires Authentication check box selected.

  10. Enter root in the Username field.

  11. Enter the Password of the KVM host’s root user.

  12. Select the Proxy Host from the drop-down list.

  13. Click Load to list the virtual machines on the KVM host that can be imported.

  14. Select one or more virtual machines from the Virtual Machines on Source list, and use the arrows to move them to the Virtual Machines to Import list.

  15. Click Next.

  16. Select the Cluster in which the virtual machines will reside.

  17. Select a CPU Profile for the virtual machines.

  18. Optionally, select the Collapse Snapshots check box to remove snapshot restore points and include templates in template-based virtual machines.

  19. Optionally, select the Clone check box to change the virtual machine name and MAC addresses, and clone all disks, removing all snapshots. If a virtual machine appears with a warning symbol beside its name or has a tick in the VM in System column, you must clone the virtual machine and change its name.

  20. Click each virtual machine to be imported and click the Disks sub-tab. Use the Allocation Policy and Storage Domain lists to select whether the disk used by the virtual machine will be thin provisioned or preallocated, and select the storage domain on which the disk will be stored. An icon is also displayed to indicate which of the disks to be imported acts as the boot disk for that virtual machine. See Virtual Disk Storage Allocation Policies in the Technical Reference for more information.

  21. If you selected the Clone check box, change the name of the virtual machine in the General tab.

  22. Click OK to import the virtual machines.

The CPU type of the virtual machine must be the same as the CPU type of the cluster into which it is being imported. To view the cluster’s CPU Type in the Administration Portal:

  1. Click .

  2. Select a cluster.

  3. Click Edit.

  4. Click the General tab.

If the CPU type of the virtual machine is different, configure the imported virtual machine’s CPU type:

  1. Click .

  2. Select the virtual machine.

  3. Click Edit.

  4. Click the System tab.

  5. Click the Advanced Parameters arrow.

  6. Specify the Custom CPU Type and click OK.

6.13.10. Importing a Red Hat KVM Guest Image

You can import a Red Hat-provided KVM virtual machine image. This image is a virtual machine snapshot with a preconfigured instance of Enterprise Linux installed.

You can configure this image with the cloud-init tool, and use it to provision new virtual machines. This eliminates the need to install and configure the operating system and provides virtual machines that are ready for use.

Procedure

  1. Download the most recent KVM virtual machine image from the Download Enterprise Linux list, in the Product Software tab.

  2. Upload the virtual machine image using the Engine or the REST API. See Uploading Images to a Data Storage Domain in the Administration Guide.

  3. Create a new virtual machine and attach the uploaded disk image to it. See Creating a Linux virtual machine.

  4. Optionally, use cloud-init to configure the virtual machine. See Using Cloud-Init to Automate the Configuration of Virtual Machines for details.

  5. Optionally, create a template from the virtual machine. You can generate new virtual machines from this template. See Templates for information about creating templates and generating virtual machines from templates.

6.14. Migrating Virtual Machines Between Hosts

Live migration provides the ability to move a running virtual machine between physical hosts with no interruption to service. The virtual machine remains powered on and user applications continue to run while the virtual machine is relocated to a new physical host. In the background, the virtual machine’s RAM is copied from the source host to the destination host. Storage and network connectivity are not altered.

A virtual machine that is using a vGPU cannot be migrated to a different host.

6.14.1. Live Migration Prerequisites

You can use live migration to seamlessly move virtual machines to support a number of common maintenance tasks. Your oVirt environment must be correctly configured to support live migration well in advance of using it.

At a minimum, the following prerequisites must be met to enable successful live migration of virtual machines:

  • The source and destination hosts are members of the same cluster, ensuring CPU compatibility between them.

Live migrating virtual machines between different clusters is generally not recommended.

  • The source and destination hosts’ status is Up.

  • The source and destination hosts have access to the same virtual networks and VLANs.

  • The source and destination hosts have access to the data storage domain on which the virtual machine resides.

  • The destination host has sufficient CPU capacity to support the virtual machine’s requirements.

  • The destination host has sufficient unused RAM to support the virtual machine’s requirements.

  • The migrating virtual machine does not have the cache!=none custom property set.

Live migration is performed using the management network and involves transferring large amounts of data between hosts. Concurrent migrations have the potential to saturate the management network. For best performance, create separate logical networks for management, storage, display, and virtual machine data to minimize the risk of network saturation.

6.14.2. Configuring Virtual Machines with SR-IOV-Enabled vNICs to Reduce Network Outage during Migration

Virtual machines with vNICs that are directly connected to a virtual function (VF) of an SR-IOV-enabled host NIC can be further configured to reduce network outage during live migration:

  1. Ensure that the destination host has an available VF.

  2. Set the Passthrough and Migratable options in the passthrough vNIC’s profile. See Enabling Passthrough on a vNIC Profile in the Administration Guide.

  3. Enable hotplugging for the virtual machine’s network interface.

  4. Ensure that the virtual machine has a backup VirtIO vNIC, in addition to the passthrough vNIC, to maintain the virtual machine’s network connection during migration.

  5. Set the VirtIO vNIC’s No Network Filter option before configuring the bond. See Explanation of Settings in the VM Interface Profile Window in the Administration Guide.

  6. Add both vNICs as slaves under an active-backup bond on the virtual machine, with the passthrough vNIC as the primary interface.

    The bond and vNIC profiles can be configured in one of the following ways:

    • The bond is not configured with fail_over_mac=active and the VF vNIC is the primary slave (recommended).

      Disable the VirtIO vNIC profile’s MAC-spoofing filter to ensure that traffic passing through the VirtIO vNIC is not dropped because it uses the VF vNIC MAC address.

    • The bond is configured with fail_over_mac=active.

      This failover policy ensures that the MAC address of the bond is always the MAC address of the active slave. During failover, the virtual machine’s MAC address changes, with a slight disruption in traffic.

6.14.3. Configuring Virtual Machines with SR-IOV-Enabled vNICs with minimal downtime

To configure virtual machines for migration with SR-IOV enabled vNICs and minimal downtime follow the procedure described below.

  1. Create a vNIC profile with SR-IOV enabled vNICS.
    See Creating a vNIC profile and Setting up and configuring SR-IOV.

  2. In the Administration Portal, go to , select the vNIC profile, click Edit and select a Failover vNIC profile from the drop down list.

  3. Click OK to save the profile settings.

  4. Hotplug a network interface with the failover vNIC profile you created into the virtual machine, or start a virtual machine with this network interface plugged in.

    The virtual machine has three network interfaces: a controller interface and two secondary interfaces. The controller interface must be active and connected in order for migration to succeed.

  5. For automatic deployment of virtual machines with this configuration, use the following udev rule:

      UBSYSTEM=="net",
      ACTION=="add|change",
      ENV{ID_NET_DRIVER}!="net_failover",
      ENV{NM_UNMANAGED}="1",
      RUN+="/bin/sh -c '/sbin/ip link set up $INTERFACE'"

    This udev rule works only on systems that manage interfaces with NetworkManager. This rule ensures that only the controller interface is activated.

6.14.4. Optimizing Live Migration

Live virtual machine migration can be a resource-intensive operation. To optimize live migration, you can set the following two options globally for every virtual machine in an environment, for every virtual machine in a cluster, or for an individual virtual machine.

The Auto Converge migrations and Enable migration compression options are available for cluster levels 4.2 or earlier.

For cluster levels 4.3 or later, auto converge is enabled by default for all built-in migration policies, and migration compression is enabled by default for only the Suspend workload if needed migration policy. You can change these parameters when adding a new migration policy, or by modifying the MigrationPolicies configuration value.

The Auto Converge migrations option allows you to set whether auto-convergence is used during live migration of virtual machines. Large virtual machines with high workloads can dirty memory more quickly than the transfer rate achieved during live migration, and prevent the migration from converging. Auto-convergence capabilities in QEMU allow you to force convergence of virtual machine migrations. QEMU automatically detects a lack of convergence and triggers a throttle-down of the vCPUs on the virtual machine.

The Enable migration compression option allows you to set whether migration compression is used during live migration of the virtual machine. This feature uses Xor Binary Zero Run-Length-Encoding to reduce virtual machine downtime and total live migration time for virtual machines running memory write-intensive workloads or for any application with a sparse memory update pattern.

Both options are disabled globally by default.

Procedure

  1. Enable auto-convergence at the global level:

    # engine-config -s DefaultAutoConvergence=True
    1. Enable migration compression at the global level:

      # engine-config -s DefaultMigrationCompression=True
    2. Restart the ovirt-engine service to apply the changes:

      # systemctl restart ovirt-engine.service
  2. Configure the optimization settings for a cluster:

    1. Click and select a cluster.

    2. Click Edit.

    3. Click the Migration Policy tab.

    4. From the Auto Converge migrations list, select Inherit from global setting, Auto Converge, or Don’t Auto Converge.

    5. From the Enable migration compression list, select Inherit from global setting, Compress, or Don’t Compress.

    6. Click OK.

  3. Configure the optimization settings at the virtual machine level:

    1. Click and select a virtual machine.

    2. Click Edit.

    3. Click the Host tab.

    4. From the Auto Converge migrations list, select Inherit from cluster setting, Auto Converge, or Don’t Auto Converge.

    5. From the Enable migration compression list, select Inherit from cluster setting, Compress, or Don’t Compress.

    6. Click OK.

6.14.5. Guest Agent Hooks

Hooks are scripts that trigger activity within a virtual machine when key events occur:

  • Before migration

  • After migration

  • Before hibernation

  • After hibernation

The hooks configuration base directory is /etc/ovirt-guest-agent/hooks.d on Linux systems.

Each event has a corresponding subdirectory: before_migration and after_migration, before_hibernation and after_hibernation. All files or symbolic links in that directory will be executed.

The executing user on Linux systems is ovirtagent. If the script needs root permissions, the elevation must be executed by the creator of the hook script.

6.14.6. Automatic Virtual Machine Migration

oVirt Engine automatically initiates live migration of all virtual machines running on a host when the host is moved into maintenance mode. The destination host for each virtual machine is assessed as the virtual machine is migrated, in order to spread the load across the cluster.

From version 4.3, all virtual machines defined with manual or automatic migration modes are migrated when the host is moved into maintenance mode. However, for high performance and/or pinned virtual machines, a Maintenance Host window is displayed, asking you to confirm the action because the performance on the target host may be less than the performance on the current host.

The Engine automatically initiates live migration of virtual machines in order to maintain load-balancing or power-saving levels in line with scheduling policy. Specify the scheduling policy that best suits the needs of your environment. You can also disable automatic, or even manual, live migration of specific virtual machines where required.

If your virtual machines are configured for high performance, and/or if they have been pinned (by setting Passthrough Host CPU, CPU Pinning, or NUMA Pinning), the migration mode is set to Allow manual migration only. However, this can be changed to Allow Manual and Automatic mode if required. Special care should be taken when changing the default migration setting so that it does not result in a virtual machine migrating to a host that does not support high performance or pinning.

6.14.7. Preventing Automatic Migration of a Virtual Machine

oVirt Engine allows you to disable automatic migration of virtual machines. You can also disable manual migration of virtual machines by setting the virtual machine to run only on a specific host.

The ability to disable automatic migration and require a virtual machine to run on a particular host is useful when using application high availability products, such as Red Hat High Availability or Cluster Suite.

Preventing Automatic Migration of Virtual Machines

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the Host tab.

  4. In the Start Running On section, select Any Host in Cluster or Specific Host(s), which enables you to select multiple hosts.

    Explicitly assigning a virtual machine to a specific host and disabling migration are mutually exclusive with oVirt high availability.

    If the virtual machine has host devices directly attached to it, and a different host is specified, the host devices from the previous host will be automatically removed from the virtual machine.

  5. Select Allow manual migration only or Do not allow migration from the Migration Options drop-down list.

  6. Click OK.

6.14.8. Manually Migrating Virtual Machines

A running virtual machine can be live migrated to any host within its designated host cluster. Live migration of virtual machines does not cause any service interruption. Migrating virtual machines to a different host is especially useful if the load on a particular host is too high. For live migration prerequisites, see Live migration prerequisites.

For high performance virtual machines and/or virtual machines defined with Pass-Through Host CPU, CPU Pinning, or NUMA Pinning, the default migration mode is Manual. Select Select Host Automatically so that the virtual machine migrates to the host that offers the best performance.

When you place a host into maintenance mode, the virtual machines running on that host are automatically migrated to other hosts in the same cluster. You do not need to manually migrate these virtual machines.

Live migrating virtual machines between different clusters is generally not recommended.

Procedure

  1. Click and select a running virtual machine.

  2. Click Migrate.

  3. Use the radio buttons to select whether to Select Host Automatically or to Select Destination Host, specifying the host using the drop-down list.

    When the Select Host Automatically option is selected, the system determines the host to which the virtual machine is migrated according to the load balancing and power management rules set up in the scheduling policy.

  4. Click OK.

During migration, progress is shown in the Migration progress bar. Once migration is complete the Host column will update to display the host the virtual machine has been migrated to.

6.14.9. Setting Migration Priority

oVirt Engine queues concurrent requests for migration of virtual machines off of a given host. The load balancing process runs every minute. Hosts already involved in a migration event are not included in the migration cycle until their migration event has completed. When there is a migration request in the queue and available hosts in the cluster to action it, a migration event is triggered in line with the load balancing policy for the cluster.

You can influence the ordering of the migration queue by setting the priority of each virtual machine; for example, setting mission critical virtual machines to migrate before others. Migrations will be ordered by priority; virtual machines with the highest priority will be migrated first.

Setting Migration Priority

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Select the High Availability tab.

  4. Select Low, Medium, or High from the Priority drop-down list.

  5. Click OK.

6.14.10. Canceling Ongoing Virtual Machine Migrations

A virtual machine migration is taking longer than you expected. You’d like to be sure where all virtual machines are running before you make any changes to your environment.

Procedure

  1. Select the migrating virtual machine. It is displayed in with a status of Migrating from.

  2. Click More Actions (), then click Cancel Migration.

The virtual machine status returns from Migrating from to Up.

6.14.11. Event and Log Notification upon Automatic Migration of Highly Available Virtual Servers

When a virtual server is automatically migrated because of the high availability function, the details of an automatic migration are documented in the Events tab and in the engine log to aid in troubleshooting, as illustrated in the following examples:

Example 4. Notification in the Events Tab of the Administration Portal

Highly Available Virtual_Machine_Name failed. It will be restarted automatically.

Virtual_Machine_Name was restarted on Host Host_Name

Example 5. Notification in the Engine engine.log

This log can be found on the oVirt Engine at /var/log/ovirt-engine/engine.log:

Failed to start Highly Available VM. Attempting to restart. VM Name: Virtual_Machine_Name, VM Id:_Virtual_Machine_ID_Number_

6.15. Improving Uptime with Virtual Machine High Availability

6.15.1. What is High Availability?

High availability is recommended for virtual machines running critical workloads. A highly available virtual machine is automatically restarted, either on its original host or another host in the cluster, if its process is interrupted, such as in the following scenarios:

  • A host becomes non-operational due to hardware failure.

  • A host is put into maintenance mode for scheduled downtime.

  • A host becomes unavailable because it has lost communication with an external storage resource.

A highly available virtual machine is not restarted if it is shut down cleanly, such as in the following scenarios:

  • The virtual machine is shut down from within the guest.

  • The virtual machine is shut down from the Engine.

  • The host is shut down by an administrator without being put in maintenance mode first.

With storage domains V4 or later, virtual machines have the additional capability to acquire a lease on a special volume on the storage, enabling a virtual machine to start on another host even if the original host loses power. The functionality also prevents the virtual machine from being started on two different hosts, which may lead to corruption of the virtual machine disks.

With high availability, interruption to service is minimal because virtual machines are restarted within seconds with no user intervention required. High availability keeps your resources balanced by restarting guests on a host with low current resource utilization, or based on any workload balancing or power saving policies that you configure. This ensures that there is sufficient capacity to restart virtual machines at all times.

High Availability and Storage I/O Errors

If a storage I/O error occurs, the virtual machine is paused. You can define how the host handles highly available virtual machines after the connection with the storage domain is reestablished; they can either be resumed, ungracefully shut down, or remain paused. For more information about these options, see Virtual Machine High Availability settings explained.

6.15.2. High Availability Considerations

A highly available host requires a power management device and fencing parameters. In addition, for a virtual machine to be highly available when its host becomes non-operational, it needs to be started on another available host in the cluster. To enable the migration of highly available virtual machines:

  • Power management must be configured for the hosts running the highly available virtual machines.

  • The host running the highly available virtual machine must be part of a cluster which has other available hosts.

  • The destination host must be running.

  • The source and destination host must have access to the data domain on which the virtual machine resides.

  • The source and destination host must have access to the same virtual networks and VLANs.

  • There must be enough CPUs on the destination host that are not in use to support the virtual machine’s requirements.

  • There must be enough RAM on the destination host that is not in use to support the virtual machine’s requirements.

6.15.3. Configuring a Highly Available Virtual Machine

High availability must be configured individually for each virtual machine.

Procedure

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the High Availability tab.

  4. Select the Highly Available check box to enable high availability for the virtual machine.

  5. Select the storage domain to hold the virtual machine lease, or select No VM Lease to disable the functionality, from the Target Storage Domain for VM Lease drop-down list. See What is high availability for more information about virtual machine leases.

    This functionality is only available on storage domains that are V4 or later.

  6. Select AUTO_RESUME, LEAVE_PAUSED, or KILL from the Resume Behavior drop-down list. If you defined a virtual machine lease, KILL is the only option available. For more information see Virtual Machine High Availability settings explained.

  7. Select Low, Medium, or High from the Priority drop-down list. When migration is triggered, a queue is created in which the high priority virtual machines are migrated first. If a cluster is running low on resources, only the high priority virtual machines are migrated.

  8. Click OK.

6.16. Other Virtual Machine Tasks

6.16.1. Enabling SAP Monitoring

Enable SAP monitoring on a virtual machine through the Administration Portal.

Enabling SAP Monitoring on Virtual Machines

  1. Click and select a virtual machine.

  2. Click Edit.

  3. Click the Custom Properties tab.

  4. Select sap_agent from the drop-down list. Ensure the secondary drop-down menu is set to True.

    If previous properties have been set, select the plus sign to add a new property rule and select sap_agent.

  5. Click OK.

6.16.2. Configuring Enterprise Linux 5.4 and later Virtual Machines to use SPICE

SPICE is a remote display protocol designed for virtual environments, which enables you to view a virtualized desktop or server. SPICE delivers a high quality user experience, keeps CPU consumption low, and supports high quality video streaming.

Using SPICE on a Linux machine significantly improves the movement of the mouse cursor on the console of the virtual machine. To use SPICE, the X-Windows system requires additional QXL drivers. The QXL drivers are provided with Enterprise Linux 5.4 and later. Earlier versions are not supported. Installing SPICE on a virtual machine running Enterprise Linux significantly improves the performance of the graphical user interface.

Typically, this is most useful for virtual machines where the user requires the use of the graphical user interface. System administrators who are creating virtual servers may prefer not to configure SPICE if their use of the graphical user interface is minimal.

Installing and Configuring QXL Drivers

You must manually install QXL drivers on virtual machines running Enterprise Linux 5.4 or later. This is unnecessary for virtual machines running Enterprise Linux 6 or Enterprise Linux 7 as the QXL drivers are installed by default.

Installing QXL Drivers

  1. Log in to a Enterprise Linux virtual machine.

  2. Install the QXL drivers:

    # yum install xorg-x11-drv-qxl

You can configure QXL drivers using either a graphical interface or the command line. Perform only one of the following procedures.

Configuring QXL drivers in GNOME

  1. Click System.

  2. Click Administration.

  3. Click Display.

  4. Click the Hardware tab.

  5. Click Video Cards Configure.

  6. Select qxl and click OK.

  7. Restart X-Windows by logging out of the virtual machine and logging back in.

Configuring QXL drivers on the command line

  1. Back up /etc/X11/xorg.conf:

    # cp /etc/X11/xorg.conf /etc/X11/xorg.conf.$$.backup
  2. Make the following change to the Device section of /etc/X11/xorg.conf:

    Section         "Device"
    Identifier        "Videocard0"
    Driver                "qxl"
    Endsection
Configuring a Virtual Machine’s Tablet and Mouse to use SPICE

Edit the /etc/X11/xorg.conf file to enable SPICE for your virtual machine’s tablet devices.

Configuring a Virtual Machine’s Tablet and Mouse to use SPICE

  1. Verify that the tablet device is available on your guest:

    # /sbin/lsusb -v | grep 'QEMU USB Tablet'
    If there is no output from the command, do not continue configuring the tablet.
  2. Back up /etc/X11/xorg.conf:

    # cp /etc/X11/xorg.conf /etc/X11/xorg.conf.$$.backup
  3. Make the following changes to /etc/X11/xorg.conf:

    Section "ServerLayout"
    Identifier     "single head configuration"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Tablet" "SendCoreEvents"
    InputDevice    "Mouse" "CorePointer"
    EndSection
    
    Section "InputDevice"
    Identifier  "Mouse"
    Driver      "void"
    #Option      "Device" "/dev/input/mice"
    #Option      "Emulate3Buttons" "yes"
    EndSection
    
    Section "InputDevice"
    Identifier  "Tablet"
    Driver      "evdev"
    Option      "Device" "/dev/input/event2"
    Option "CorePointer" "true"
    EndSection
  4. Log out and log back into the virtual machine to restart X-Windows.

6.16.3. KVM Virtual Machine Timing Management

Virtualization poses various challenges for virtual machine time keeping. Virtual machines which use the Time Stamp Counter (TSC) as a clock source may suffer timing issues as some CPUs do not have a constant Time Stamp Counter. Virtual machines running without accurate timekeeping can have serious affects on some networked applications as your virtual machine will run faster or slower than the actual time.

KVM works around this issue by providing virtual machines with a paravirtualized clock. The KVM pvclock provides a stable source of timing for KVM guests that support it.

Presently, only Enterprise Linux 5.4 and later virtual machines fully support the paravirtualized clock.

Virtual machines can have several problems caused by inaccurate clocks and counters:

  • Clocks can fall out of synchronization with the actual time which invalidates sessions and affects networks.

  • Virtual machines with slower clocks may have issues migrating.

These problems exist on other virtualization platforms and timing should always be tested.

The Network Time Protocol (NTP) daemon should be running on the host and the virtual machines. Enable the ntpd service and add it to the default startup sequence:

  • For Enterprise Linux 6

# service ntpd start
# chkconfig ntpd on
  • For Enterprise Linux 7

# systemctl start ntpd.service
# systemctl enable ntpd.service

Using the ntpd service should minimize the affects of clock skew in all cases.

The NTP servers you are trying to use must be operational and accessible to your hosts and virtual machines.

Determining if your CPU has the constant Time Stamp Counter

Your CPU has a constant Time Stamp Counter if the constant_tsc flag is present. To determine if your CPU has the constant_tsc flag run the following command:

$ cat /proc/cpuinfo | grep constant_tsc

If any output is given your CPU has the constant_tsc bit. If no output is given follow the instructions below.

Configuring hosts without a constant Time Stamp Counter

Systems without constant time stamp counters require additional configuration. Power management features interfere with accurate time keeping and must be disabled for virtual machines to accurately keep time with KVM.

These instructions are for AMD revision F CPUs only.

If the CPU lacks the constant_tsc bit, disable all power management features (BZ#513138). Each system has several timers it uses to keep time. The TSC is not stable on the host, which is sometimes caused by cpufreq changes, deep C state, or migration to a host with a faster TSC. Deep C sleep states can stop the TSC. To prevent the kernel using deep C states append “processor.max_cstate=1” to the kernel boot options in the grub.conf file on the host:

term Enterprise Linux Server (2.6.18-159.el5)
        root (hd0,0)
        kernel /vmlinuz-2.6.18-159.el5 ro root=/dev/VolGroup00/LogVol00 rhgb quiet processor.max_cstate=1

Disable cpufreq (only necessary on hosts without the constant_tsc) by editing the /etc/sysconfig/cpuspeed configuration file and change the MIN_SPEED and MAX_SPEED variables to the highest frequency available. Valid limits can be found in the /sys/devices/system/cpu/cpu/cpufreq/scaling_available_frequencies files.

Using the engine-config tool to receive alerts when hosts drift out of sync.

You can use the engine-config tool to configure alerts when your hosts drift out of sync.

There are 2 relevant parameters for time drift on hosts: EnableHostTimeDrift and HostTimeDriftInSec. EnableHostTimeDrift, with a default value of false, can be enabled to receive alert notifications of host time drift. The HostTimeDriftInSec parameter is used to set the maximum allowable drift before alerts start being sent.

Alerts are sent once per hour per host.

Using the paravirtualized clock with Enterprise Linux virtual machines

For certain Enterprise Linux virtual machines, additional kernel parameters are required. These parameters can be set by appending them to the end of the /kernel line in the /boot/grub/grub.conf file of the virtual machine.

The process of configuring kernel parameters can be automated using the ktune package

The ktune package provides an interactive Bourne shell script, fix_clock_drift.sh. When run as the superuser, this script inspects various system parameters to determine if the virtual machine on which it is run is susceptible to clock drift under load. If so, it then creates a new grub.conf.kvm file in the /boot/grub/ directory. This file contains a kernel boot line with additional kernel parameters that allow the kernel to account for and prevent significant clock drift on the KVM virtual machine. After running fix_clock_drift.sh as the superuser, and once the script has created the grub.conf.kvm file, then the virtual machine’s current grub.conf file should be backed up manually by the system administrator, the new grub.conf.kvm file should be manually inspected to ensure that it is identical to grub.conf with the exception of the additional boot line parameters, the grub.conf.kvm file should finally be renamed grub.conf, and the virtual machine should be rebooted.

The table below lists versions of Enterprise Linux and the parameters required for virtual machines on systems without a constant Time Stamp Counter.

Enterprise Linux Additional virtual machine kernel parameters

5.4 AMD64/Intel 64 with the paravirtualized clock

Additional parameters are not required

5.4 AMD64/Intel 64 without the paravirtualized clock

notsc lpj=n

5.4 x86 with the paravirtualized clock

Additional parameters are not required

5.4 x86 without the paravirtualized clock

clocksource=acpi_pm lpj=n

5.3 AMD64/Intel 64

notsc

5.3 x86

clocksource=acpi_pm

4.8 AMD64/Intel 64

notsc

4.8 x86

clock=pmtmr

3.9 AMD64/Intel 64

Additional parameters are not required

3.9 x86

Additional parameters are not required

6.16.4. Adding a Trusted Platform Module device

Trusted Platform Module (TPM) devices provide a secure crypto-processor designed to carry out cryptographic operations such as generating cryptographic keys, random numbers, and hashes, or for storing data that can be used to verify software configurations securely. TPM devices are commonly used for disk encryption.

QEMU and libvirt implement support for emulated TPM 2.0 devices, which is what oVirt uses to add TPM devices to Virtual Machines.

Once an emulated TPM device is added to the virtual machine, it can be used as a normal TPM 2.0 device in the guest OS.

If there is TPM data stored for the virtual machine and the TPM device is disabled in the virtual machine, the TPM data is permanently removed.

Enabling a TPM device

  1. In the Add Virtual Machine or Edit Virtual Machine screen, click Show Advanced Options.

  2. In the Resource Allocation tab, select the TPM Device Enabled check box.

Limitations

The following limitations apply:

  • TPM devices can only be used on x86_64 machines with UEFI firmware and PowerPC machines with pSeries firmware installed.

  • Virtual machines with TPM devices can not have snapshots with memory.

  • While the Engine retrieves and stores TPM data periodically, there is no guarantee that the Engine will always have the latest version of the TPM data.

    This process can take 120 seconds or more, and you must wait for the process to complete before you can take snapshot of a running virtual machine, clone a running virtual machine, or migrate a running virtual machine.

  • TPM devices can only be enabled for virtual machines running RHEL 7 or later and Windows 8.1 or later.

  • Virtual machines and templates with TPM data can not be exported or imported.

7. Templates

7.1. About Templates

A template is a copy of a virtual machine that you can use to simplify the subsequent, repeated creation of similar virtual machines. Templates capture the configuration of software, configuration of hardware, and the software installed on the virtual machine on which the template is based. The virtual machine on which a template is based is known as the source virtual machine.

When you create a template based on a virtual machine, a read-only copy of the virtual machine’s disk is created. This read-only disk becomes the base disk image of the new template, and of any virtual machines created based on the template. As such, the template cannot be deleted while any virtual machines created based on the template exist in the environment.

Virtual machines created based on a template use the same NIC type and driver as the original virtual machine, but are assigned separate, unique MAC addresses.

You can create a virtual machine directly from , as well as from . In , select the required template and click New VM. For more information on selecting the settings and controls for the new virtual machine see Virtual Machine General settings explained.

7.2. Sealing Virtual Machines in Preparation for Deployment as Templates

This section describes procedures for sealing Linux and Windows virtual machines. Sealing is the process of removing all system-specific details from a virtual machine before creating a template based on that virtual machine. Sealing is necessary to prevent the same details from appearing on multiple virtual machines created based on the same template. It is also necessary to ensure the functionality of other features, such as predictable vNIC order.

7.2.1. Sealing a Linux Virtual Machine for Deployment as a Template

To seal a Linux virtual machine during the template creation process, select the Seal Template check box in the New Template window. See Creating a template from an existing virtual machine for details.

In RHV 4.4, to seal a RHEL 8 virtual machine for a template, its cluster level must be 4.4 and all hosts in the cluster must be based on RHEL 8.
You cannot seal a RHEL 8 virtual machine if you have set its cluster level to 4.3 so it can run on RHEL 7 hosts.

7.2.2. Sealing a Windows Virtual Machine for Deployment as a Template

A template created for Windows virtual machines must be generalized (sealed) before being used to deploy virtual machines. This ensures that machine-specific settings are not reproduced in the template.

Sysprep is used to seal Windows templates before use. Sysprep generates a complete unattended installation answer file. Default values for several Windows operating systems are available in the /usr/share/ovirt-engine/conf/sysprep/ directory. These files act as templates for Sysprep. The fields in these files can be copied, pasted, and altered as required. This definition will override any values entered into the Initial Run fields of the Edit Virtual Machine window.

The Sysprep file can be edited to affect various aspects of the Windows virtual machines created from the template that the Sysprep file is attached to. These include the provisioning of Windows, setting up the required domain membership, configuring the hostname, and setting the security policy.

Replacement strings can be used to substitute values provided in the default files in the /usr/share/ovirt-engine/conf/sysprep/ directory. For example, "<Domain><![CDATA[$JoinDomain$"]></Domain>" can be used to indicate the domain to join.

Prerequisites for Sealing a Windows Virtual Machine

Do not reboot the virtual machine while Sysprep is running.

Before starting Sysprep, verify that the following settings are configured:

  • The Windows virtual machine parameters have been correctly defined.

  • If not, click Edit in and enter the required information in the Operating System and Cluster fields.

  • The correct product key has been defined in an override file on the Engine.

The override file must be created under /etc/ovirt-engine/osinfo.conf.d/, have a filename that puts it after /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties, and ends in .properties. For example, /etc/ovirt-engine/osinfo.conf.d/10-productkeys.properties. The last file will have precedence and override any other previous file.

If not, copy the default values for your Windows operating system from /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties into the override file, and input your values in the productKey.value and sysprepPath.value fields.

Example 6. Windows 7 Default Configuration Values

# Windows7(11, OsType.Windows, false),false
os.windows_7.id.value = 11
os.windows_7.name.value = Windows 7
os.windows_7.derivedFrom.value = windows_xp
os.windows_7.sysprepPath.value = ${ENGINE_USR}/conf/sysprep/sysprep.w7
os.windows_7.productKey.value =
os.windows_7.devices.audio.value = ich6
os.windows_7.devices.diskInterfaces.value.3.3 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.4 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.5 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.isTimezoneTypeInteger.value = false
Sealing a Windows 7, Windows 2008, or Windows 2012 Virtual Machine for Deployment as Template

Seal a Windows 7, Windows 2008, or Windows 2012 virtual machine before creating a template to use to deploy virtual machines.

Procedure

  1. On the Windows virtual machine, launch Sysprep from C:\Windows\System32\sysprep\sysprep.exe.

  2. Enter the following information into Sysprep:

    • Under System Cleanup Action, select Enter System Out-of-Box-Experience (OOBE).

    • Select the Generalize check box if you need to change the computer’s system identification number (SID).

    • Under Shutdown Options, select Shutdown.

  3. Click OK to complete the sealing process; the virtual machine shuts down automatically upon completion.

The Windows 7, Windows 2008, or Windows 2012 virtual machine is sealed and ready to create a template to use for deploying virtual machines.

7.3. Creating a Template

Create a template from an existing virtual machine to use as a blueprint for creating additional virtual machines.

In RHV 4.4, to seal a RHEL 8 virtual machine for a template, its cluster level must be 4.4 and all hosts in the cluster must be based on RHEL 8.
You cannot seal a RHEL 8 virtual machine if you have set its cluster level to 4.3 so it can run on RHEL 7 hosts.

When you create a template, you specify the format of the disk to be raw or QCOW2:

  • QCOW2 disks are thin provisioned.

  • Raw disks on file storage are thin provisioned.

  • Raw disks on block storage are preallocated.

Creating a Template

  1. Click and select the source virtual machine.

  2. Ensure the virtual machine is powered down and has a status of Down.

  3. Click More Actions (), then click Make Template. For more details on all fields in the New Template window, see Explanation of Settings in the New Template and Edit Template Windows.

  4. Enter a Name, Description, and Comment for the template.

  5. Select the cluster with which to associate the template from the Cluster drop-down list. By default, this is the same as that of the source virtual machine.

  6. Optionally, select a CPU profile for the template from the CPU Profile drop-down list.

  7. Optionally, select the Create as a Template Sub-Version check box, select a Root Template, and enter a Sub-Version Name to create the new template as a sub-template of an existing template.

  8. In the Disks Allocation section, enter an alias for the disk in the Alias text field. Select the disk format in the Format drop-down, the storage domain on which to store the disk from the Target drop-down, and the disk profile in the Disk Profile drop-down. By default, these are the same as those of the source virtual machine.

  9. Select the Allow all users to access this Template check box to make the template public.

  10. Select the Copy VM permissions check box to copy the permissions of the source virtual machine to the template.

  11. Select the Seal Template check box (Linux only) to seal the template.

    Sealing, which uses the virt-sysprep command, removes system-specific details from a virtual machine before creating a template based on that virtual machine. This prevents the original virtual machine’s details from appearing in subsequent virtual machines that are created using the same template. It also ensures the functionality of other features, such as predictable vNIC order. See virt-sysprep operations for more information.

  12. Click OK.

The virtual machine displays a status of Image Locked while the template is being created. The process of creating a template may take up to an hour depending on the size of the virtual disk and the capabilities of your storage hardware. When complete, the template is added to the Templates tab. You can now create new virtual machines based on the template.

When a template is made, the virtual machine is copied so that both the existing virtual machine and its template are usable after template creation.

7.4. Editing a Template

Once a template has been created, its properties can be edited. Because a template is a copy of a virtual machine, the options available when editing a template are identical to those in the Edit Virtual Machine window.

Procedure

  1. Click and select a template.

  2. Click Edit.

  3. Change the necessary properties. Click Show Advanced Options and edit the template’s settings as required. The settings that appear in the Edit Template window are identical to those in the Edit Virtual Machine window, but with the relevant fields only. See Explanation of Settings in the New Virtual Machine and Edit Virtual Machine Windows for details.

  4. Click OK.

7.5. Deleting a Template

If you have used a template to create a virtual machine using the thin provisioning storage allocation option, the template cannot be deleted as the virtual machine needs it to continue running. However, cloned virtual machines do not depend on the template they were cloned from and the template can be deleted.

Deleting a Template

  1. Click and select a template.

  2. Click Remove.

  3. Click OK.

7.6. Exporting Templates

7.6.1. Migrating Templates to the Export Domain

The export storage domain is deprecated. Storage data domains can be unattached from a data center and imported to another data center in the same environment, or in a different environment. Virtual machines, floating virtual disks, and templates can then be uploaded from the imported storage domain to the attached data center. See the Importing Existing Storage Domains section in the oVirt Administration Guide for information on importing storage domains.

Export templates into the export domain to move them to another data domain, either in the same oVirt environment, or another one. This procedure requires access to the Administration Portal.

Exporting Individual Templates to the Export Domain

  1. Click and select a template.

  2. Click Export.

  3. Select the Force Override check box to replace any earlier version of the template on the export domain.

  4. Click OK to begin exporting the template; this may take up to an hour, depending on the virtual disk size and your storage hardware.

Repeat these steps until the export domain contains all the templates to migrate before you start the import process.

  1. Click and select the export domain.

  2. Click the domain name to see the details view.

  3. Click the Template Import tab to view all exported templates in the export domain.

7.6.2. Copying a Template’s Virtual Hard Disk

If you are moving a virtual machine that was created from a template with the thin provisioning storage allocation option selected, the template’s disks must be copied to the same storage domain as that of the virtual disk. This procedure requires access to the Administration Portal.

Copying a Virtual Hard Disk

  1. Click .

  2. Select the template disk(s) to copy.

  3. Click Copy.

  4. Select the Target data domain from the drop-down list(s).

  5. Click OK.

A copy of the template’s virtual hard disk has been created, either on the same, or a different, storage domain. If you were copying a template disk in preparation for moving a virtual hard disk, you can now move the virtual hard disk.

7.7. Importing Templates

7.7.1. Importing a Template into a Data Center

The export storage domain is deprecated. Storage data domains can be unattached from a data center and imported to another data center in the same environment, or in a different environment. Virtual machines, floating virtual disks, and templates can then be uploaded from the imported storage domain to the attached data center. See the Importing Existing Storage Domains section in the oVirt Administration Guide for information on importing storage domains.

Import templates from a newly attached export domain. This procedure requires access to the Administration Portal.

Importing a Template into a Data Center

  1. Click and select the newly attached export domain.

  2. Click the domain name to go to the details view.

  3. Click the Template Import tab and select a template.

  4. Click Import.

  5. Use the drop-down lists to select the Target Cluster and CPU Profile.

  6. Select the template to view its details, then click the Disks tab and select the Storage Domain to import the template into.

  7. Click OK.

  8. If the Import Template Conflict window appears, enter a New Name for the template, or select the Apply to all check box and enter a Suffix to add to the cloned Templates. Click OK.

  9. Click Close.

The template is imported into the destination data center. This can take up to an hour, depending on your storage hardware. You can view the import progress in the Events tab.

Once the importing process is complete, the templates will be visible in . The templates can create new virtual machines, or run existing imported virtual machines based on that template.

7.7.2. Importing a Virtual Disk from an OpenStack Image Service as a Template

Virtual disks managed by an OpenStack Image Service can be imported into the oVirt Engine if that OpenStack Image Service has been added to the Engine as an external provider. This procedure requires access to the Administration Portal.

  1. Click and select the OpenStack Image Service domain.

  2. Click the storage domain name to go to the details view.

  3. Click the Images tab and select the image to import.

  4. Click Import.

    If you are importing an image from a Glance storage domain, you have the option of specifying the template name. OpenStack Glance is now deprecated. This functionality will be removed in a later release.

  5. Select the Data Center into which the virtual disk will be imported.

  6. Select the storage domain in which the virtual disk will be stored from the Domain Name drop-down list.

  7. Optionally, select a Quota to apply to the virtual disk.

  8. Select the Import as Template check box.

  9. Select the Cluster in which the virtual disk will be made available as a template.

  10. Click OK.

The image is imported as a template and is displayed in the Templates tab. You can now create virtual machines based on the template.

7.8. Templates and Permissions

7.8.1. Managing System Permissions for a Template

As the SuperUser, the system administrator manages all aspects of the Administration Portal. More specific administrative roles can be assigned to other users. These restricted administrator roles are useful for granting a user administrative privileges that limit them to a specific resource. For example, a DataCenterAdmin role has administrator privileges only for the assigned data center with the exception of the storage for that data center, and a ClusterAdmin has administrator privileges only for the assigned cluster.

A template administrator is a system administration role for templates in a data center. This role can be applied to specific virtual machines, to a data center, or to the whole virtualized environment; this is useful to allow different users to manage certain virtual resources.

The template administrator role permits the following actions:

  • Create, edit, export, and remove associated templates.

  • Import and export templates.

You can only assign roles and permissions to existing users.

7.8.2. Template Administrator Roles Explained

The table below describes the administrator roles and privileges applicable to template administration.

Table 16. oVirt System Administrator Roles

Role Privileges Notes

TemplateAdmin

Can perform all operations on templates.

Has privileges to create, delete and configure a template’s storage domain and network details, and to move templates between domains.

NetworkAdmin

Network Administrator

Can configure and manage networks attached to templates.

7.8.3. Assigning an Administrator or User Role to a Resource

Assign administrator or user roles to resources to allow users to access or manage that resource.

Procedure

  1. Use the resource tabs, tree mode, or the search function to find and select the resource in the results list.

  2. Click the resource’s name to go to the details view.

  3. Click the Permissions tab to list the assigned users, the user’s role, and the inherited permissions for the selected resource.

  4. Click Add.

  5. Enter the name or user name of an existing user into the Search text box and click Go. Select a user from the resulting list of possible matches.

  6. Select a role from the Role to Assign: drop-down list.

  7. Click OK.

You have assigned a role to a user; the user now has the inherited permissions of that role enabled for that resource.

7.8.4. Removing an Administrator or User Role from a Resource

Remove an administrator or user role from a resource; the user loses the inherited permissions associated with the role for that resource.

Removing a Role from a Resource

  1. Use the resource tabs, tree mode, or the search function to find and select the resource in the results list.

  2. Click the resource’s name to go to the details view.

  3. Click the Permissions tab to list the assigned users, the user’s role, and the inherited permissions for the selected resource.

  4. Select the user to remove from the resource.

  5. Click Remove. The Remove Permission window opens to confirm permissions removal.

  6. Click OK.

You have removed the user’s role, and the associated permissions, from the resource.

7.9. Using Cloud-Init to Automate the Configuration of Virtual Machines

Cloud-Init is a tool for automating the initial setup of virtual machines such as configuring the host name, network interfaces, and authorized keys. It can be used when provisioning virtual machines that have been deployed based on a template to avoid conflicts on the network.

To use this tool, the cloud-init package must first be installed on the virtual machine. Once installed, the Cloud-Init service starts during the boot process to search for instructions on what to configure. You can then use options in the Run Once window to provide these instructions one time only, or options in the New Virtual Machine, Edit Virtual Machine and Edit Template windows to provide these instructions every time the virtual machine starts.

7.9.1. Cloud-Init Use Case Scenarios

Cloud-Init can be used to automate the configuration of virtual machines in a variety of scenarios. Several common scenarios are as follows:

  • Virtual Machines Created Based on Templates

    You can use the Cloud-Init options in the Initial Run section of the Run Once window to initialize a virtual machine that was created based on a template. This allows you to customize the virtual machine the first time that virtual machine is started.

  • Virtual Machine Templates

    You can use the Use Cloud-Init/Sysprep options in the Initial Run tab of the Edit Template window to specify options for customizing virtual machines created based on that template.

  • Virtual Machine Pools

    You can use the Use Cloud-Init/Sysprep options in the Initial Run tab of the New Pool window to specify options for customizing virtual machines taken from that virtual machine pool. This allows you to specify a set of standard settings that will be applied every time a virtual machine is taken from that virtual machine pool. You can inherit or override the options specified for the template on which the virtual machine is based, or specify options for the virtual machine pool itself.

7.9.2. Installing Cloud-Init

This procedure describes how to install Cloud-Init on a virtual machine. Once Cloud-Init is installed, you can create a template based on this virtual machine. Virtual machines created based on this template can leverage Cloud-Init functions, such as configuring the host name, time zone, root password, authorized keys, network interfaces, DNS service, etc on boot.

Installing Cloud-Init

  1. Log in to the virtual machine.

  2. Enable the repositories:

    • For Enterprise Linux 6:

      # subscription-manager repos \
          --enable=rhel-6-server-rpms \
          --enable=rhel-6-server-rh-common-rpms
    • For Enterprise Linux 7:

      # subscription-manager repos \
          --enable=rhel-7-server-rpms \
          --enable=rhel-7-server-rh-common-rpms
    • For Enterprise Linux 8, you normally do not need to enable repositories to install Cloud-Init. The Cloud-Init package is part of the AppStream repo, rhel-8-for-x86_64-appstream-rpms, which is enabled by default in Enterprise Linux 8.

  3. Install the cloud-init package and dependencies:

    For versions of Enterprise Linux earlier than version 8, use the command yum install cloud-init instead of dnf install cloud-init.

7.9.3. Using Cloud-Init to Prepare a Template

As long as the cloud-init package is installed on a Linux virtual machine, you can use the virtual machine to make a cloud-init enabled template. Specify a set of standard settings to be included in a template as described in the following procedure or, alternatively, skip the Cloud-Init settings steps and configure them when creating a virtual machine based on this template.

While the following procedure outlines how to use Cloud-Init when preparing a template, the same settings are also available in the New Virtual Machine, Edit Template, and Run Once windows.

Using Cloud-Init to Prepare a Template

  1. Click and select a template.

  2. Click Edit.

  3. Click Show Advanced Options

  4. Click the Initial Run tab and select the Use Cloud-Init/Sysprep check box.

  5. Enter a host name in the VM Hostname text field.

  6. Select the Configure Time Zone check box and select a time zone from the Time Zone drop-down list.

  7. Expand the Authentication section.

    • Select the Use already configured password check box to use the existing credentials, or clear that check box and enter a root password in the Password and Verify Password text fields to specify a new root password.

    • Enter any SSH keys to be added to the authorized hosts file on the virtual machine in the SSH Authorized Keys text area.

    • Select the Regenerate SSH Keys check box to regenerate SSH keys for the virtual machine.

  8. Expand the Networks section.

    • Enter any DNS servers in the DNS Servers text field.

    • Enter any DNS search domains in the DNS Search Domains text field.

    • Select the In-guest Network Interface check box and use the + Add new and — Renove selected buttons to add or remove network interfaces to or from the virtual machine.

      You must specify the correct network interface name and number (for example, eth0, eno3, enp0s). Otherwise, the virtual machine’s interface connection will be up, but it will not have the cloud-init network configuration.

  9. Expand the Custom Script section and enter any custom scripts in the Custom Script text area.

  10. Click OK.

You can now provision new virtual machines using this template.

7.9.4. Using Cloud-Init to Initialize a Virtual Machine

Use Cloud-Init to automate the initial configuration of a Linux virtual machine. You can use the Cloud-Init fields to configure a virtual machine’s host name, time zone, root password, authorized keys, network interfaces, and DNS service. You can also specify a custom script, a script in YAML format, to run on boot. The custom script allows for additional Cloud-Init configuration that is supported by Cloud-Init but not available in the Cloud-Init fields. For more information on custom script examples, see Cloud config examples.

Using Cloud-Init to Initialize a Virtual Machine

This procedure starts a virtual machine with a set of Cloud-Init settings. If the relevant settings are included in the template the virtual machine is based on, review the settings, make changes where appropriate, and click OK to start the virtual machine.

  1. Click and select a virtual machine.

  2. Click the Run drop-down button and select Run Once.

  3. Expand the Initial Run section and select the Cloud-Init check box.

  4. Enter a host name in the VM Hostname text field.

  5. Select the Configure Time Zone check box and select a time zone from the Time Zone drop-down menu.

  6. Select the Use already configured password check box to use the existing credentials, or clear that check box and enter a root password in the Password and Verify Password text fields to specify a new root password.

  7. Enter any SSH keys to be added to the authorized hosts file on the virtual machine in the SSH Authorized Keys text area.

  8. Select the Regenerate SSH Keys check box to regenerate SSH keys for the virtual machine.

  9. Enter any DNS servers in the DNS Servers text field.

  10. Enter any DNS search domains in the DNS Search Domains text field.

  11. Select the Network check box and use the + and buttons to add or remove network interfaces to or from the virtual machine.

    You must specify the correct network interface name and number (for example, eth0, eno3, enp0s). Otherwise, the virtual machine’s interface connection will be up, but the cloud-init network configuration will not be defined in it.

  12. Enter a custom script in the Custom Script text area. Make sure the values specified in the script are appropriate. Otherwise, the action will fail.

  13. Click OK.

To check if a virtual machine has Cloud-Init installed, select a virtual machine and click the Applications sub-tab. Only shown if the guest agent is installed.

7.10. Using Sysprep to Automate the Configuration of Virtual Machines

Sysprep is a tool used to automate the setup of Windows virtual machines, for example, configuring host names, network interfaces, authorized keys, set up users, or to connect to Active Directory. Sysprep is installed with every version of Windows.

oVirt enhances Sysprep by exploiting virtualization technology to deploy virtual workstations based on a single template. oVirt builds a tailored auto-answer file for each virtual workstation.

Sysprep generates a complete unattended installation answer file. Default values for several Windows operating systems are available in the /usr/share/ovirt-engine/conf/sysprep/ directory. You can also create a custom Sysprep file and reference it from the the osinfo file in the /etc/ovirt-engine/osinfo.conf.d/ directory. These files act as templates for Sysprep. The fields in these files can be copied and edited as required. This definition will override any values entered into the Initial Run fields of the Edit Virtual Machine window.

You can create a custom sysprep file when creating a pool of Windows virtual machines, to accommodate various operating systems and domains. See Creating a Virtual Machine Pool in the Administration Guide for details.

The override file must be created under /etc/ovirt-engine/osinfo.conf.d/, have a filename that puts it after /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties, and ends in .properties. For example, /etc/ovirt-engine/osinfo.conf.d/10-productkeys.properties. The last file will have precedence and override any other previous file.

Copy the default values for your Windows operating system from /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties into the override file, and input your values in the productKey.value and sysprepPath.value fields.

Example 7. Windows 7 Default Configuration Values

# Windows7(11, OsType.Windows, false),false
os.windows_7.id.value = 11
os.windows_7.name.value = Windows 7
os.windows_7.derivedFrom.value = windows_xp
os.windows_7.sysprepPath.value = ${ENGINE_USR}/conf/sysprep/sysprep.w7
os.windows_7.productKey.value =
os.windows_7.devices.audio.value = ich6
os.windows_7.devices.diskInterfaces.value.3.3 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.4 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.5 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.isTimezoneTypeInteger.value = false

7.10.1. Configuring Sysprep on a Template

You can use this procedure to specify a set of standard Sysprep settings to include in the template, alternatively you can configure the Sysprep settings when creating a virtual machine based on this template.

Replacement strings can be used to substitute values provided in the default files in the /usr/share/ovirt-engine/conf/sysprep/ directory. For example, «<Domain><![CDATA[$JoinDomain$»]></Domain>» can be used to indicate the domain to join.

Do not reboot the virtual machine while Sysprep is running.

Prerequisites

  • The Windows virtual machine parameters have been correctly defined.

    If not, click , click Edit, and enter the required information in the Operating System and Cluster fields.

  • The correct product key has been defined in an override file on the Engine.

Using Sysprep to Prepare a Template

  1. Build the Windows virtual machine with the required patches and software.

  2. Seal the Windows virtual machine. See Sealing Virtual Machines in Preparation for Deployment as Templates

  3. Create a template based on the Windows virtual machine. See Creating a template from an existing virtual machine

  4. Update the Sysprep file with a text editor if additional changes are required.

You can now provision new virtual machines using this template.

7.10.2. Using Sysprep to Initialize a Virtual Machine

Use Sysprep to automate the initial configuration of a Windows virtual machine. You can use the Sysprep fields to configure a virtual machine’s host name, time zone, root password, authorized keys, network interfaces, and DNS service.

Using Sysprep to Initialize a Virtual Machine

This procedure starts a virtual machine with a set of Sysprep settings. If the relevant settings are included in the template the virtual machine is based on, review the settings and make changes where required.

  1. Create a new Windows virtual machine based on a template of the required Windows virtual machine. See Creating a Virtual Machine Based on a Template.

  2. Click and select the virtual machine.

  3. Click the Run drop-down button and select Run Once.

  4. Expand the Boot Options section, select the Attach Floppy check box, and select the [sysprep] option.

  5. Select the Attach CD check box and select the required Windows ISO from the drop-down list.

  6. Move the CD-ROM to the top of the Boot Sequence field.

  7. Configure any further Run Once options as required. See Virtual Machine Run Once settings explained for more details.

  8. Click OK.

7.11. Creating a Virtual Machine Based on a Template

Create a virtual machine from a template to enable the virtual machines to be pre-configured with an operating system, network interfaces, applications and other resources.

Virtual machines created from a template depend on that template. So you cannot remove a template from the Engine if a virtual machine was created from that template. However, you can clone a virtual machine from a template to remove the dependency on that template.

If the BIOS type of the virtual machine differs from the BIOS type of the template, the Engine might change devices in the virtual machine, possibly preventing the operating system from booting. For example, if the template uses IDE disks and the i440fx chipset, changing the BIOS type to the Q35 chipset automatically changes the IDE disks to SATA disks. So configure the chipset and BIOS type to match the chipset and BIOS type of the template.

Creating a Virtual Machine Based on a Template

  1. Click .

  2. Click New.

  3. Select the Cluster on which the virtual machine will run.

  4. Select a template from the Template list.

  5. Enter a Name, Description, and any Comments, and accept the default values inherited from the template in the rest of the fields. You can change them if needed.

  6. Click the Resource Allocation tab.

  7. Select the Thin or Clone radio button in the Storage Allocation area. If you select Thin, the disk format is QCOW2. If you select Clone, select either QCOW2 or Raw for disk format.

  8. Use the Target drop-down list to select the storage domain on which the virtual machine’s virtual disk will be stored.

  9. Click OK.

The virtual machine is displayed in the Virtual Machines tab.

7.12. Creating a Cloned Virtual Machine Based on a Template

Cloned virtual machines are based on templates and inherit the settings of the template. A cloned virtual machine does not depend on the template on which it was based after it has been created. This means the template can be deleted if no other dependencies exist.

If you clone a virtual machine from a template, the name of the template on which that virtual machine was based is displayed in the General tab of the Edit Virtual Machine window for that virtual machine. If you change the name of that template, the name of the template in the General tab will also be updated. However, if you delete the template from the Engine, the original name of that template will be displayed instead.

Cloning a Virtual Machine Based on a Template

  1. Click .

  2. Click New.

  3. Select the Cluster on which the virtual machine will run.

  4. Select a template from the Based on Template drop-down menu.

  5. Enter a Name, Description and any Comments. You can accept the default values inherited from the template in the rest of the fields, or change them if required.

  6. Click the Resource Allocation tab.

  7. Select the Clone radio button in the Storage Allocation area.

  8. Select the disk format from the Format drop-down list. This affects the speed of the clone operation and the amount of disk space the new virtual machine initially requires.

    • QCOW2 (Default)

      • Faster clone operation

      • Optimized use of storage capacity

      • Disk space allocated only as required

    • Raw

      • Slower clone operation

      • Optimized virtual machine read and write operations

      • All disk space requested in the template is allocated at the time of the clone operation

  9. Use the Target drop-down menu to select the storage domain on which the virtual machine’s virtual disk will be stored.

  10. Click OK.

Cloning a virtual machine may take some time. A new copy of the template’s disk must be created. During this time, the virtual machine’s status is first Image Locked, then Down.

The virtual machine is created and displayed in the Virtual Machines tab. You can now assign users to it, and can begin using it when the clone operation is complete.

Appendix A: Reference: Settings in Administration Portal and VM Portal Windows

Explanation of Settings in the New Virtual Machine and Edit Virtual Machine Windows

Virtual Machine General Settings Explained

The following table details the options available on the General tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 17. Virtual Machine: General Settings

Field Name Description Power cycle required?

Cluster

The name of the host cluster to which the virtual machine is attached. Virtual machines are hosted on any physical machine in that cluster in accordance with policy rules.

Yes. Cross-cluster migration is for emergency use only. Moving clusters requires the virtual machine to be down.

Template

The template on which the virtual machine is based. This field is set to Blank by default, which allows you to create a virtual machine on which an operating system has not yet been installed. Templates are displayed as Name | Sub-version name (Sub-version number). Each new version is displayed with a number in brackets that indicates the relative order of the version, with a higher number indicating a more recent version.

The version name is displayed as base version if it is the root template of the template version chain.

When the virtual machine is stateless, there is an option to select the latest version of the template. This option means that anytime a new version of this template is created, the virtual machine is automatically recreated on restart based on the latest template.

Not applicable. This setting is for provisioning new virtual machines only.

Operating System

The operating system. Valid values include a range of Enterprise Linux and Windows variants.

Yes. Potentially changes the virtual hardware.

Instance Type

The instance type on which the virtual machine’s hardware configuration can be based. This field is set to Custom by default, which means the virtual machine is not connected to an instance type. The other options available from this drop down menu are Large, Medium, Small, Tiny, XLarge, and any custom instance types that the Administrator has created.

Other settings that have a chain link icon next to them are pre-filled by the selected instance type. If one of these values is changed, the virtual machine will be detached from the instance type and the chain icon will appear broken. However, if the changed setting is restored to its original value, the virtual machine will be reattached to the instance type and the links in the chain icon will rejoin.

NOTE: Support for instance types is now deprecated, and will be removed in a future release.

Yes.

Optimized for

The type of system for which the virtual machine is to be optimized. There are three options: Server, Desktop, and High Performance; by default, the field is set to Server. Virtual machines optimized to act as servers have no sound card, use a cloned disk image, and are not stateless. Virtual machines optimized to act as desktop machines do have a sound card, use an image (thin allocation), and are stateless. Virtual machines optimized for high performance have a number of configuration changes. See Configuring High Performance Virtual Machines Templates and Pools.

Yes.

Name

The name of the virtual machine. The name must be a unique name within the data center and must not contain any spaces, and must contain at least one character from A-Z or 0-9. The maximum length of a virtual machine name is 255 characters. The name can be reused in different data centers in the environment.

Yes.

VM ID

The virtual machine ID. The virtual machine’s creator can set a custom ID for that virtual machine. The custom ID must contain only numbers, in the format, 00000000-0000-0000-0000-00000000.

If no ID is specified during creation a UUID will be automatically assigned. For both custom and automatically-generated IDs, changes are not possible after virtual machine creation.

Yes.

Description

A meaningful description of the new virtual machine.

No.

Comment

A field for adding plain text human-readable comments regarding the virtual machine.

No.

Affinity Labels

Add or remove a selected Affinity Label.

No.

Stateless

Select this check box to run the virtual machine in stateless mode. This mode is used primarily for desktop virtual machines. Running a stateless desktop or server creates a new COW layer on the virtual machine hard disk image where new and changed data is stored. Shutting down the stateless virtual machine deletes the new COW layer which includes all data and configuration changes, and returns the virtual machine to its original state. Stateless virtual machines are useful when creating machines that need to be used for a short time, or by temporary staff.

Not applicable.

Start in Pause Mode

Select this check box to always start the virtual machine in pause mode. This option is suitable for virtual machines which require a long time to establish a SPICE connection; for example, virtual machines in remote locations.

Not applicable.

Delete Protection

Select this check box to make it impossible to delete the virtual machine. It is only possible to delete the virtual machine if this check box is not selected.

No.

Sealed

Select this check box to seal the created virtual machine. This option eliminates machine-specific settings from virtual machines that are provisioned from the template. For more information about the sealing process, see Sealing a Windows Virtual Machine for Deployment as a Template

No.

Instance Images

Click Attach to attach a floating disk to the virtual machine, or click Create to add a new virtual disk. Use the plus and minus buttons to add or remove additional virtual disks.

Click Edit to change the configuration of a virtual disk that has already been attached or created.

No.

Instantiate VM network interfaces by picking a vNIC profile.

Add a network interface to the virtual machine by selecting a vNIC profile from the nic1 drop-down list. Use the plus and minus buttons to add or remove additional network interfaces.

No.

Virtual Machine System Settings Explained

CPU Considerations

  • For non-CPU-intensive workloads, you can run virtual machines with a total number of processor cores greater than the number of cores in the host (the number of processor cores for a single virtual machine must not exceed the number of cores in the host). The following benefits can be achieved:

    • You can run a greater number of virtual machines, which reduces hardware requirements.

    • You can configure virtual machines with CPU topologies that are otherwise not possible, such as when the number of virtual cores is between the number of host cores and the number of host threads.

  • For best performance, and especially for CPU-intensive workloads, you should use the same topology in the virtual machine as in the host, so the host and the virtual machine expect the same cache usage. When the host has hyperthreading enabled, QEMU treats the host’s hyperthreads as cores, so the virtual machine is not aware that it is running on a single core with multiple threads. This behavior might impact the performance of a virtual machine, because a virtual core that actually corresponds to a hyperthread in the host core might share a single cache with another hyperthread in the same host core, while the virtual machine treats it as a separate core.

The following table details the options available on the System tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 18. Virtual Machine: System Settings

Field Name Description Power cycle required?

Memory Size

The amount of memory assigned to the virtual machine. When allocating memory, consider the processing and storage needs of the applications that are intended to run on the virtual machine.

If OS supports hotplugging, no. Otherwise, yes.

Maximum Memory

The maximum amount of memory that can be assigned to the virtual machine. Maximum guest memory is also constrained by the selected guest architecture and the cluster compatibility level.

If OS supports hotplugging, no. Otherwise, yes.

Total Virtual CPUs

The processing power allocated to the virtual machine as CPU Cores. For high performance, do not assign more cores to a virtual machine than are present on the physical host.

If OS supports hotplugging, no. Otherwise, yes.

Virtual Sockets

The number of CPU sockets for the virtual machine. Do not assign more sockets to a virtual machine than are present on the physical host.

If OS supports hotplugging, no. Otherwise, yes.

Cores per Virtual Socket

The number of cores assigned to each virtual socket.

If OS supports hotplugging, no. Otherwise, yes.

Threads per Core

The number of threads assigned to each core. Increasing the value enables simultaneous multi-threading (SMT). IBM POWER8 supports up to 8 threads per core. For x86 and x86_64 (Intel and AMD) CPU types, the recommended value is 1, unless you want to replicate the exact host topology, which you can do using CPU pinning. For more information, see Pinning CPU.

If OS supports hotplugging, no. Otherwise, yes.

Chipset/Firmware Type

Specifies the chipset and firmware type. Defaults to the cluster’s default chipset and firmware type. Options are:

  • I440FX Chipset with BIOS Legacy BIOS

  • Q35 Chipset with BIOS BIOS without UEFI (Default for clusters with compatibility version 4.4)

  • Q35 Chipset with UEFI BIOS with UEFI (Default for clusters with compatibility version 4.7)

  • Q35 Chipset with UEFI SecureBoot UEFI with SecureBoot, which authenticates the digital signatures of the boot loader

For more information, see UEFI and the Q35 chipset in the Administration Guide.

Yes.

Custom Emulated Machine

This option allows you to specify the machine type. If changed, the virtual machine will only run on hosts that support this machine type. Defaults to the cluster’s default machine type.

Yes.

Custom CPU Type

This option allows you to specify a CPU type. If changed, the virtual machine will only run on hosts that support this CPU type. Defaults to the cluster’s default CPU type.

Yes.

Hardware Clock Time Offset

This option sets the time zone offset of the guest hardware clock. For Windows, this should correspond to the time zone set in the guest. Most default Linux installations expect the hardware clock to be GMT+00:00.

Yes.

Custom Compatibility Version

The compatibility version determines which features are supported by the cluster, as well as, the values of some properties and the emulated machine type. By default, the virtual machine is configured to run in the same compatibility mode as the cluster as the default is inherited from the cluster. In some situations the default compatibility mode needs to be changed. An example of this is if the cluster has been updated to a later compatibility version but the virtual machines have not been restarted. These virtual machines can be set to use a custom compatibility mode that is older than that of the cluster. See Changing the Cluster Compatibility Version in the Administration Guide for more information.

Yes.

Serial Number Policy

Override the system-level and cluster-level policies for assigning a serial numbers to virtual machines. Apply a policy that is unique to this virtual machine:

  • System Default: Use the system-wide defaults, which are configured in the Engine database using the engine configuration tool and the DefaultSerialNumberPolicy and DefaultCustomSerialNumber key names. The default value for DefaultSerialNumberPolicy is to use the Host ID. See Scheduling Policies in the Administration Guide for more information.

  • Host ID: Set this virtual machine’s serial number to the UUID of the host.

  • Vm ID: Set this virtual machine’s serial number to the UUID of this virtual machine.

  • Custom serial number: Set this virtual machine’s serial number to the value you specify in the following Custom Serial Number parameter.

Yes.

Custom Serial Number

Specify the custom serial number to apply to this virtual machine.

Yes.

Virtual Machine Initial Run Settings Explained

The following table details the options available on the Initial Run tab of the New Virtual Machine and Edit Virtual Machine windows. The settings in this table are only visible if the Use Cloud-Init/Sysprep check box is selected, and certain options are only visible when either a Linux-based or Windows-based option has been selected in the Operating System list in the General tab, as outlined below.

This table does not include information on whether a power cycle is required because the settings apply to the virtual machine’s initial run; the virtual machine is not running when you configure these settings.

Table 19. Virtual Machine: Initial Run Settings

Field Name Operating System Description

Use Cloud-Init/Sysprep

Linux, Windows

This check box toggles whether Cloud-Init or Sysprep will be used to initialize the virtual machine.

VM Hostname

Linux, Windows

The host name of the virtual machine.

Domain

Windows

The Active Directory domain to which the virtual machine belongs.

Organization Name

Windows

The name of the organization to which the virtual machine belongs. This option corresponds to the text field for setting the organization name displayed when a machine running Windows is started for the first time.

Active Directory OU

Windows

The organizational unit in the Active Directory domain to which the virtual machine belongs.

Configure Time Zone

Linux, Windows

The time zone for the virtual machine. Select this check box and select a time zone from the Time Zone list.

Admin Password

Windows

The administrative user password for the virtual machine. Click the disclosure arrow to display the settings for this option.

  • Use already configured password: This check box is automatically selected after you specify an initial administrative user password. You must clear this check box to enable the Admin Password and Verify Admin Password fields and specify a new password.

  • Admin Password: The administrative user password for the virtual machine. Enter the password in this text field and the Verify Admin Password text field to verify the password.

Authentication

Linux

The authentication details for the virtual machine. Click the disclosure arrow to display the settings for this option.

  • Use already configured password: This check box is automatically selected after you specify an initial root password. You must clear this check box to enable the Password and Verify Password fields and specify a new password.

  • Password: The root password for the virtual machine. Enter the password in this text field and the Verify Password text field to verify the password.

  • SSH Authorized Keys: SSH keys to be added to the authorized keys file of the virtual machine. You can specify multiple SSH keys by entering each SSH key on a new line.

  • Regenerate SSH Keys: Regenerates SSH keys for the virtual machine.

Custom Locale

Windows

Custom locale options for the virtual machine. Locales must be in a format such as en-US. Click the disclosure arrow to display the settings for this option.

  • Input Locale: The locale for user input.

  • UI Language: The language used for user interface elements such as buttons and menus.

  • System Locale: The locale for the overall system.

  • User Locale: The locale for users.

Networks

Linux

Network-related settings for the virtual machine. Click the disclosure arrow to display the settings for this option.

  • DNS Servers: The DNS servers to be used by the virtual machine.

  • DNS Search Domains: The DNS search domains to be used by the virtual machine.

  • Network: Configures network interfaces for the virtual machine. Select this check box and click + or to add or remove network interfaces to or from the virtual machine. When you click +, a set of fields becomes visible that can specify whether to use DHCP, and configure an IP address, netmask, and gateway, and specify whether the network interface will start on boot.

Custom Script

Linux

Custom scripts that will be run on the virtual machine when it starts. The scripts entered in this field are custom YAML sections that are added to those produced by the Engine, and allow you to automate tasks such as creating users and files, configuring yum repositories and running commands. For more information on the format of scripts that can be entered in this field, see the Custom Script documentation.

Sysprep

Windows

A custom Sysprep definition. The definition must be in the format of a complete unattended installation answer file. You can copy and paste the default answer files in the /usr/share/ovirt-engine/conf/sysprep/ directory on the machine on which the oVirt Engine is installed and alter the fields as required. See Templates for more information.

Ignition 2.3.0

Red Hat Enterprise Linux CoreOS

When Red Hat Enterprise Linux CoreOS is selected as Operating System, this check box toggles whether Ignition will be used to initialize the virtual machine.

Virtual Machine Console Settings Explained

The following table details the options available on the Console tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 20. Virtual Machine: Console Settings

Field Name Description Power cycle required?

Graphical Console Section

A group of settings.

Yes.

Headless Mode

Select this check box if you do not a require a graphical console for the virtual machine.

When selected, all other fields in the Graphical Console section are disabled. In the VM Portal, the Console icon in the virtual machine’s details view is also disabled.

See Configuring Headless Machines for more details and prerequisites for using headless mode.

Yes.

Video Type

Defines the graphics device. QXL is the default and supports both graphic protocols. VGA supports only the VNC protocol.

Yes.

Graphics protocol

Defines which display protocol to use. SPICE is the default protocol. VNC is an alternative option. To allow both protocols select SPICE + VNC.

Yes.

VNC Keyboard Layout

Defines the keyboard layout for the virtual machine. This option is only available when using the VNC protocol.

Yes.

USB enabled

Defines SPICE USB redirection. This check box is not selected by default. This option is only available for virtual machines using the SPICE protocol:

  • Disabled (check box is cleared) — USB controller devices are added according to the devices.usb.controller value in the osinfo-defaults.properties configuration file. The default for all x86 and x86_64 operating systems is piix3-uhci. For ppc64 systems, the default is nec-xhci.

  • Enabled (check box is selected) — Enables native KVM/SPICE USB redirection for Linux and Windows virtual machines. Virtual machines do not require any in-guest agents or drivers for native USB.

Yes.

Console Disconnect Action

Defines what happens when the console is disconnected. This is only relevant with SPICE and VNC console connections. This setting can be changed while the virtual machine is running but will not take effect until a new console connection is established. Select either:

  • No action — No action is taken.

  • Lock screen — This is the default option. For all Linux machines and for Windows desktops this locks the currently active user session. For Windows servers, this locks the desktop and the currently active user.

  • Logout user — For all Linux machines and Windows desktops, this logs out the currently active user session. For Windows servers, the desktop and the currently active user are logged out.

  • Shutdown virtual machine — Initiates a graceful virtual machine shutdown.

  • Reboot virtual machine — Initiates a graceful virtual machine reboot.

No.

Monitors

The number of monitors for the virtual machine. This option is only available for virtual desktops using the SPICE display protocol. You can choose 1, 2 or 4. Note that multiple monitors are not supported for Windows systems with WDDMDoD drivers.

Yes.

Smartcard Enabled

Smart cards are an external hardware security feature, most commonly seen in credit cards, but also used by many businesses as authentication tokens. Smart cards can be used to protect oVirt virtual machines. Select or clear the check box to activate and deactivate Smart card authentication for individual virtual machines.

Yes.

Single Sign On method

Enabling Single Sign On allows users to sign into the guest operating system when connecting to a virtual machine from the VM Portal using the Guest Agent.

  • Disable Single Sign On — Select this option if you do not want the Guest Agent to attempt to sign into the virtual machine.

  • Use Guest Agent — Enables Single Sign On to allow the Guest Agent to sign you into the virtual machine.

If you select Use Guest Agent, no. Otherwise, yes.

Disable strict user checking

Click the Advanced Parameters arrow and select the check box to use this option. With this option selected, the virtual machine does not need to be rebooted when a different user connects to it.

By default, strict checking is enabled so that only one user can connect to the console of a virtual machine. No other user is able to open a console to the same virtual machine until it has been rebooted. The exception is that a SuperUser can connect at any time and replace a existing connection. When a SuperUser has connected, no normal user can connect again until the virtual machine is rebooted.

Disable strict checking with caution, because you can expose the previous user’s session to the new user.

No.

Soundcard Enabled

A sound card device is not necessary for all virtual machine use cases. If it is for yours, enable a sound card here.

Yes.

Enable SPICE file transfer

Defines whether a user is able to drag and drop files from an external host into the virtual machine’s SPICE console. This option is only available for virtual machines using the SPICE protocol. This check box is selected by default.

No.

Enable SPICE clipboard copy and paste

Defines whether a user is able to copy and paste content from an external host into the virtual machine’s SPICE console. This option is only available for virtual machines using the SPICE protocol. This check box is selected by default.

No.

Serial Console Section

A group of settings.

Enable VirtIO serial console

The VirtIO serial console is emulated through VirtIO channels, using SSH and key pairs, and allows you to access a virtual machine’s serial console directly from a client machine’s command line, instead of opening a console from the Administration Portal or the VM Portal. The serial console requires direct access to the Engine, since the Engine acts as a proxy for the connection, provides information about virtual machine placement, and stores the authentication keys. Select the check box to enable the VirtIO console on the virtual machine. Requires a firewall rule. See Opening a Serial Console to a Virtual Machine.

Yes.

Virtual Machine Host Settings Explained

The following table details the options available on the Host tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 21. Virtual Machine: Host Settings

Field Name Sub-element Description Power cycle required?

Start Running On

Defines the preferred host on which the virtual machine is to run. Select either:

  • Any Host in Cluster — The virtual machine can start and run on any available host in the cluster.

  • Specific Host(s) — The virtual machine will start running on a particular host in the cluster. However, the Engine or an administrator can migrate the virtual machine to a different host in the cluster depending on the migration and high-availability settings of the virtual machine. Select the specific host or group of hosts from the list of available hosts.

No. The virtual machine can migrate to that host while running.

CPU options

Pass-Through Host CPU

When selected, allows virtual machines to use the host’s CPU flags.
When selected, Migration Options is set to Allow manual migration only.

Yes

Migrate only to hosts with the same TSC frequency

When selected, this virtual machine can only be migrated to a host with the same TSC frequency. This option is only valid for High Performance virtual machines.

Yes

Migration Options

Migration mode

Defines options to run and migrate the virtual machine. If the options here are not used, the virtual machine will run or migrate according to its cluster’s policy.

  • Allow manual and automatic migration — The virtual machine can be automatically migrated from one host to another in accordance with the status of the environment, or manually by an administrator.

  • Allow manual migration only — The virtual machine can only be migrated from one host to another manually by an administrator.

  • Do not allow migration — The virtual machine cannot be migrated, either automatically or manually.

No

Migration policy

Defines the migration convergence policy. If the check box is left unselected, the host determines the policy.

  • Cluster default (Minimal downtime) — Overrides in vdsm.conf are still applied. The guest agent hook mechanism is disabled.

  • Minimal downtime — Allows the virtual machine to migrate in typical situations. Virtual machines should not experience any significant downtime. The migration will be aborted if virtual machine migration does not converge after a long time (dependent on QEMU iterations, with a maximum of 500 milliseconds). The guest agent hook mechanism is enabled.

  • Post-copy migration — When used, post-copy migration pauses the migrating virtual machine vCPUs on the source host, transfers only a minimum of memory pages, activates the virtual machine vCPUs on the destination host, and transfers the remaining memory pages while the virtual machine is running on the destination.

    The post-copy policy first tries pre-copy to verify whether convergence can occur. The migration switches to post-copy if the virtual machine migration does not converge after a long time.

    This significantly reduces the downtime of the migrated virtual machine, and also guarantees that the migration finishes regardless of how rapidly the memory pages of the source virtual machine change. It is optimal for migrating virtual machines in heavy continuous use, which would not be possible to migrate with standard pre-copy migration.

    The disadvantage of this policy is that in the post-copy phase, the virtual machine may slow down significantly as the missing parts of memory are transferred between the hosts.

    If the network connection breaks prior to the completion of the post-copy process, the Engine pauses and then kills the running virtual machine. Do not use post-copy migration if the virtual machine availability is critical or if the migration network is unstable.

  • Suspend workload if needed — Allows the virtual machine to migrate in most situations, including when the virtual machine is running a heavy workload. Because of this, virtual machines may experience a more significant downtime than with some other settings. The migration may still be aborted for extreme workloads. The guest agent hook mechanism is enabled.

No

Enable migration encryption

Allows the virtual machine to be encrypted during migration.

  • Cluster default

  • Encrypt

  • Don’t encrypt

No

Parallel Migrations

Allows you to specify whether and how many parallel migration connections to use.

  • Cluster default: Parallel migration connections are determined by the cluster default.

  • Disabled: The virtual machine is migrated using a single, non-parallel connection.

  • Auto: The number of parallel connections is automatically determined. This settings might automatically disable parallel connections.

  • Auto Parallel: The number of parallel connections is automatically determined.

  • Custom: Allows you to specify the preferred number of parallel connections, the actual number may be lower.

Number of VM Migration Connections

This setting is only available when Custom is selected. The preferred number of custom parallel migrations, between 2 and 255.

Configure NUMA

NUMA Node Count

The number of virtual NUMA nodes available in a host that can be assigned to the virtual machine.

No

NUMA Pinning

Opens the NUMA Topology window. This window shows the host’s total CPUs, memory, and NUMA nodes, and the virtual machine’s virtual NUMA nodes.
You can manually pin virtual NUMA nodes to host NUMA nodes by clicking and dragging each vNUMA from the box on the right to a NUMA node on the left.

You can also set Tune Mode for memory allocation:

Strict — Memory allocation will fail if the memory cannot be allocated on the target node.

Preferred — Memory is allocated from a single preferred node. If sufficient memory is not available, memory can be allocated from other nodes.

Interleave — Memory is allocated across nodes in a round-robin algorithm.

If you define NUMA pinning, Migration Options is set to Allow manual migration only.

Yes

Virtual Machine High Availability Settings Explained

The following table details the options available on the High Availability tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 22. Virtual Machine: High Availability Settings

Field Name Description Power cycle required?

Highly Available

Select this check box if the virtual machine is to be highly available. For example, in cases of host maintenance, all virtual machines are automatically live migrated to another host. If the host crashes and is in a non-responsive state, only virtual machines with high availability are restarted on another host. If the host is manually shut down by the system administrator, the virtual machine is not automatically live migrated to another host.

Note that this option is unavailable for virtual machines defined as Server or Desktop if the Migration Options setting in the Hosts tab is set to Do not allow migration. For a virtual machine to be highly available, it must be possible for the Engine to migrate the virtual machine to other available hosts as necessary.

However, for virtual machines defined as High Performance, you can define high availability regardless of the Migration Options setting.

Yes.

Target Storage Domain for VM Lease

Select the storage domain to hold a virtual machine lease, or select No VM Lease to disable the functionality. When a storage domain is selected, it will hold a virtual machine lease on a special volume that allows the virtual machine to be started on another host if the original host loses power or becomes unresponsive.

This functionality is only available on storage domain V4 or later.

If you define a lease, the only Resume Behavior available is KILL.

Yes.

Resume Behavior

Defines the desired behavior of a virtual machine that is paused due to storage I/O errors, once a connection with the storage is reestablished. You can define the desired resume behavior even if the virtual machine is not highly available.

The following options are available:

  • AUTO_RESUME — The virtual machine is automatically resumed, without requiring user intervention. This is recommended for virtual machines that are not highly available and that do not require user intervention after being in the paused state.

  • LEAVE_PAUSED — The virtual machine remains in pause mode until it is manually resumed or restarted.

  • KILL — The virtual machine is automatically resumed if the I/O error is remedied within 80 seconds. However, if more than 80 seconds pass, the virtual machine is ungracefully shut down. This is recommended for highly available virtual machines, to allow the Engine to restart them on another host that is not experiencing the storage I/O error.

    KILL is the only option available when using virtual machine leases.

No.

Priority for Run/Migration queue

Sets the priority level for the virtual machine to be migrated or restarted on another host.

No.

Watchdog

Allows users to attach a watchdog card to a virtual machine. A watchdog is a timer that is used to automatically detect and recover from failures. Once set, a watchdog timer continually counts down to zero while the system is in operation, and is periodically restarted by the system to prevent it from reaching zero. If the timer reaches zero, it signifies that the system has been unable to reset the timer and is therefore experiencing a failure. Corrective actions are then taken to address the failure. This functionality is especially useful for servers that demand high availability.

Watchdog Model: The model of watchdog card to assign to the virtual machine. At current, the only supported model is i6300esb.

Watchdog Action: The action to take if the watchdog timer reaches zero. The following actions are available:

  • none — No action is taken. However, the watchdog event is recorded in the audit log.

  • reset — The virtual machine is reset and the Engine is notified of the reset action.

  • poweroff — The virtual machine is immediately shut down.

  • dump — A dump is performed and the virtual machine is paused. The guest’s memory is dumped by libvirt, therefore, neither ‘kdump’ nor ‘pvpanic’ is required. The dump file is created in the directory that is configured by auto_dump_path in the /etc/libvirt/qemu.conf file on the host.

  • pause — The virtual machine is paused, and can be resumed by users.

Yes.

Virtual Machine Resource Allocation Settings Explained

The following table details the options available on the Resource Allocation tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 23. Virtual Machine: Resource Allocation Settings

Field Name Sub-element Description Power cycle required?

CPU Allocation

CPU Profile

The CPU profile assigned to the virtual machine. CPU profiles define the maximum amount of processing capability a virtual machine can access on the host on which it runs, expressed as a percent of the total processing capability available to that host. CPU profiles are defined for a cluster, based on quality of service entries created for data centers.

No.

CPU Shares

Allows users to set the level of CPU resources a virtual machine can demand relative to other virtual machines.

  • Low — 512

  • Medium — 1024

  • High — 2048

  • Custom — A custom level of CPU shares defined by the user.

No.

CPU Pinning Policy

  • None — Runs without any CPU pinning.

  • Manual — Runs a manually specified virtual CPU on a specific physical CPU and a specific host. Available only when the virtual machine is pinned to a Host.

  • Resize and Pin NUMA — Resizes the virtual CPU and NUMA topology of the virtual machine according to the Host, and pins them to the Host resources.

  • Dedicated — Exclusively pins virtual CPUs to host physical CPUs. Available for cluster compatibility level 4.7 or later. If the virtual machine has NUMA enabled, all nodes must be unpinned.

  • Isolate Threads — Exclusively pins virtual CPUs to host physical CPUs. Each virtual CPU gets a physical core. Available for cluster compatibility level 4.7 or later. If the virtual machine has NUMA enabled, all nodes must be unpinned.

No.

CPU Pinning topology

Enables the virtual machine’s virtual CPU (vCPU) to run on a specific physical CPU (pCPU) in a specific host. The syntax of CPU pinning is v#p[_v#p], for example:

  • 0#0 — Pins vCPU 0 to pCPU 0.

  • 0#0_1#3 — Pins vCPU 0 to pCPU 0, and pins vCPU 1 to pCPU 3.

  • 1#1-4,^2 — Pins vCPU 1 to one of the pCPUs in the range of 1 to 4, excluding pCPU 2.

The CPU Pinning Topology is populated automatically when Resize and Pin NUMA pinning is selected in CPU Pinning Policy.

In order to pin a virtual machine to a host, you must also select the following on the Host tab:

  • Start Running On: Specific

  • Pass-Through Host CPU

If CPU pinning is set and you change Start Running On: Specific a CPU pinning topology will be lost window appears when you click OK.

When defined, Migration Options in the Hosts tab is set to Allow manual migration only.

Yes.

Memory Allocation

Physical Memory Guaranteed

The amount of physical memory guaranteed for this virtual machine. Should be any number between 0 and the defined memory for this virtual machine.

If lowered, yes. Otherwise, no.

Memory Balloon Device Enabled

Enables the memory balloon device for this virtual machine. Enable this setting to allow memory overcommitment in a cluster. Enable this setting for applications that allocate large amounts of memory suddenly but set the guaranteed memory to the same value as the defined memory.Use ballooning for applications and loads that slowly consume memory, occasionally release memory, or stay dormant for long periods of time, such as virtual desktops. See Optimization Settings Explained in the Administration Guide for more information.

Yes.

Trusted Platform Module

TPM Device Enabled

Enables the addition of an emulated Trusted Platform Module (TPM) device. Select this check box to add an emulated Trusted Platform Module device to a virtual machine. TPM devices can only be used on x86_64 machines with UEFI firmware and PowerPC machines with pSeries firmware installed. See Adding Trusted Platform Module devices for more information.

Yes.

IO Threads

IO Threads Enabled

Enables IO threads. Select this check box to improve the speed of disks that have a VirtIO interface by pinning them to a thread separate from the virtual machine’s other functions. Improved disk performance increases a virtual machine’s overall performance. Disks with VirtIO interfaces are pinned to an IO thread using a round-robin algorithm.

Yes.

Queues

Multi Queues Enabled

Enables multiple queues. This check box is selected by default. It creates up to four queues per vNIC, depending on how many vCPUs are available.

It is possible to define a different number of queues per vNIC by creating a custom property as follows:

engine-config -s "CustomDeviceProperties={type=interface;prop={other-nic-properties;queues=[1-9][0-9]*}}"

where other-nic-properties is a semicolon-separated list of pre-existing NIC custom properties.

Yes.

VirtIO-SCSI Enabled

Allows users to enable or disable the use of VirtIO-SCSI on the virtual machines.

Not applicable.

VirtIO-SCSI Multi Queues Enabled

The VirtIO-SCSI Multi Queues Enabled option is only available when VirtIO-SCSI Enabled is selected. Select this check box to enable multiple queues in the VirtIO-SCSI driver. This setting can improve I/O throughput when multiple threads within the virtual machine access the virtual disks. It creates up to four queues per VirtIO-SCSI controller, depending on how many disks are connected to the controller and how many vCPUs are available.

Not applicable.

Storage Allocation

The Storage Allocation option is only available when the virtual machine is created from a template.

Not applicable.

Thin

Provides optimized usage of storage capacity. Disk space is allocated only as it is required. When selected, the format of the disks will be marked as QCOW2 and you will not be able to change it.

Not applicable.

Clone

Optimized for the speed of guest read and write operations. All disk space requested in the template is allocated at the time of the clone operation. Possible disk formats are QCOW2 or Raw.

Not applicable.

Disk Allocation

The Disk Allocation option is only available when you are creating a virtual machine from a template.

Not applicable.

Alias

An alias for the virtual disk. By default, the alias is set to the same value as that of the template.

Not applicable.

Virtual Size

The total amount of disk space that the virtual machine based on the template can use. This value cannot be edited, and is provided for reference only.

Not applicable.

Format

The format of the virtual disk. The available options are QCOW2 and Raw. When Storage Allocation is Thin, the disk format is QCOW2. When Storage Allocation is Clone, select QCOW2 or Raw.

Not applicable.

Target

The storage domain on which the virtual disk is stored. By default, the storage domain is set to the same value as that of the template.

Not applicable.

Disk Profile

The disk profile to assign to the virtual disk. Disk profiles are created based on storage profiles defined in the data centers. For more information, see Creating a Disk Profile.

Not applicable.

Virtual Machine Boot Options Settings Explained

The following table details the options available on the Boot Options tab of the New Virtual Machine and Edit Virtual Machine windows

Table 24. Virtual Machine: Boot Options Settings

Field Name Description Power cycle required?

First Device

After installing a new virtual machine, the new virtual machine must go into Boot mode before powering up. Select the first device that the virtual machine must try to boot:

  • Hard Disk

  • CD-ROM

  • Network (PXE)

Yes.

Second Device

Select the second device for the virtual machine to use to boot if the first device is not available. The first device selected in the previous option does not appear in the options.

Yes.

Attach CD

If you have selected CD-ROM as a boot device, select this check box and select a CD-ROM image from the drop-down menu. The images must be available in the ISO domain.

Yes.

Enable menu to select boot device

Enables a menu to select the boot device. After the virtual machine starts and connects to the console, but before the virtual machine starts booting, a menu displays that allows you to select the boot device. This option should be enabled before the initial boot to allow you to select the required installation media.

Yes.

Virtual Machine Random Generator Settings Explained

The following table details the options available on the Random Generator tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 25. Virtual Machine: Random Generator Settings

Field Name Description Power cycle required?

Random Generator enabled

Selecting this check box enables a paravirtualized Random Number Generator PCI device (virtio-rng). This device allows entropy to be passed from the host to the virtual machine in order to generate a more sophisticated random number. Note that this check box can only be selected if the RNG device exists on the host and is enabled in the host’s cluster.

Yes.

Period duration (ms)

Specifies the duration of the RNG’s «full cycle» or «full period» in milliseconds. If omitted, the libvirt default of 1000 milliseconds (1 second) is used. If this field is filled,
Bytes per period must be filled also.

Yes.

Bytes per period

Specifies how many bytes are permitted to be consumed per period.

Yes.

Device source:

The source of the random number generator. This is automatically selected depending on the source supported by the host’s cluster.

  • /dev/urandom source — The Linux-provided random number generator.

  • /dev/hwrng source — An external hardware generator.

Yes.

Virtual Machine Custom Properties Settings Explained

The following table details the options available on the Custom Properties tab of the New Virtual Machine and Edit Virtual Machine windows.

Table 26. Virtual Machine Custom Properties Settings

Field Name Description Recommendations and Limitations Power cycle required?

sndbuf

Enter the size of the buffer for sending the virtual machine’s outgoing data over the socket. Default value is 0.

Yes

hugepages

Enter the huge page size in KB.

  • Set the huge page size to the largest size supported by the pinned host.

  • The recommended size for x86_64 is 1 GB.

  • The virtual machine’s huge page size must be the same size as the pinned host’s huge page size.

  • The virtual machine’s memory size must fit into the selected size of the pinned host’s free huge pages. The NUMA node size must be a multiple of the huge page’s selected size.

Yes

vhost

Disables vhost-net, which is the kernel-based virtio network driver on virtual network interface cards attached to the virtual machine. To disable vhost, the format for this property is LogicalNetworkName: false.

This will explicitly start the virtual machine without the vhost-net setting on the virtual NIC attached to LogicalNetworkName.

vhost-net provides better performance than virtio-net, and if it is present, it is enabled on all virtual machine NICs by default. Disabling this property makes it easier to isolate and diagnose performance issues, or to debug vhost-net errors; for example, if migration fails for virtual machines on which vhost does not exist.

Yes

sap_agent

Enables SAP monitoring on the virtual machine. Set to true or false.

Yes

viodiskcache

Caching mode for the virtio disk. writethrough writes data to the cache and the disk in parallel, writeback does not copy modifications from the cache to the disk, and none disables caching.

In order to ensure data integrity in the event of a fault in storage, in the network, or in a host during migration, do not migrate virtual machines with viodiskcache enabled, unless virtual machine clustering or application-level clustering is also enabled.

Yes

scsi_hostdev

Optionally, if you add a SCSI host device to a virtual machine, you can specify the optimal SCSI host device driver. For details, see Adding Host Devices to a Virtual Machine.

  • scsi_generic: (Default) Enables the guest operating system to access OS-supported SCSI host devices attached to the host. Use this driver for SCSI media changers that require raw access, such as tape or CD changers.

  • scsi_block: Similar to scsi_generic but better speed and reliability. Use for SCSI disk devices. If trim or discard for the underlying device is desired, and it’s a hard disk, use this driver.

  • scsi_hd: Provides performance with lowered overhead. Supports large numbers of devices. Uses the standard SCSI device naming scheme. Can be used with aio-native. Use this driver for high-performance SSDs.

  • virtio_blk_pci: Provides the highest performance without the SCSI overhead. Supports identifying devices by their serial numbers.

If you are not sure, try scsi_hd.

Yes

Increasing the value of the sndbuf custom property results in increased occurrences of communication failure between hosts and unresponsive virtual machines.

Virtual Machine Icon Settings Explained

You can add custom icons to virtual machines and templates. Custom icons can help to differentiate virtual machines in the VM Portal. The following table details the options available on the Icon tab of the New Virtual Machine and Edit Virtual Machine windows.

This table does not include information on whether a power cycle is required because these settings apply to the virtual machine’s appearance in the Administration portal, not to its configuration.

Table 27. Virtual Machine: Icon Settings

Button Name Description

Upload

Click this button to select a custom image to use as the virtual machine’s icon. The following limitations apply:

  • Supported formats: jpg, png, gif

  • Maximum size: 24 KB

  • Maximum dimensions: 150px width, 120px height

Power cycle required?

Use default

Virtual Machine Foreman/Satellite Settings Explained

The following table details the options available on the Foreman/Satellite tab of the New Virtual Machine and Edit Virtual Machine windows

Table 28. Virtual Machine:Foreman/Satellite Settings

Field Name Description Power cycle required?

Provider

If the virtual machine is running Enterprise Linux and the system is configured to work with a Satellite server, select the name of the Satellite from the list. This enables you to use Satellite’s content management feature to display the relevant Errata for this virtual machine. See Configuring Satellite Errata for more details.

Yes.

Explanation of settings in the Run Once window

The Run Once window defines one-off boot options for a virtual machine. For persistent boot options, use the Boot Options tab in the New Virtual Machine window. The Run Once window contains multiple sections that can be configured.

The standalone Rollback this configuration during reboots check box specifies whether reboots (initiated by the Engine, or from within the guest) will be warm (soft) or cold (hard). Select this check box to configure a cold reboot that restarts the virtual machine with regular (non-Run Once) configuration. Clear this check box to configure a warm reboot that retains the virtual machine’s Run Once configuration.

The Boot Options section defines the virtual machine’s boot sequence, running options, and source images for installing the operating system and required drivers.

The following tables do not include information on whether a power cycle is required because these one-off boot options apply only when you reboot the virtual machine.

Table 29. Boot Options Section

Field Name Description

Attach CD

Attaches an ISO image to the virtual machine. Use this option to install the virtual machine’s operating system and applications. The CD image must reside in the ISO domain.

Attach Windows guest tools CD

Attaches a secondary virtual CD-ROM to the virtual machine with the virtio-win ISO image.
Use this option to install Windows drivers. For information on installing the image, see Uploading the VirtIO Image Files to a Storage Domain in the Administration Guide.

Enable menu to select boot device

Enables a menu to select the boot device. After the virtual machine starts and connects to the console, but before the virtual machine starts booting, a menu displays that allows you to select the boot device. This option should be enabled before the initial boot to allow you to select the required installation media.

Start in Pause Mode

Starts and then pauses the virtual machine to enable connection to the console. Suitable for virtual machines in remote locations.

Predefined Boot Sequence

Determines the order in which the boot devices are used to boot the virtual machine. Select Hard Disk, CD-ROM, or Network (PXE), and use Up and Down to move the option up or down in the list.

Run Stateless

Deletes all data and configuration changes to the virtual machine upon shutdown. This option is only available if a virtual disk is attached to the virtual machine.

The Linux Boot Options section contains fields to boot a Linux kernel directly instead of through the BIOS bootloader.

Table 30. Linux Boot Options Section

Field Name Description

kernel path

A fully qualified path to a kernel image to boot the virtual machine. The kernel image must be stored on either the ISO domain (path name in the format of iso://path-to-image) or on the host’s local storage domain (path name in the format of /data/images).

initrd path

A fully qualified path to a ramdisk image to be used with the previously specified kernel. The ramdisk image must be stored on the ISO domain (path name in the format of iso://path-to-image) or on the host’s local storage domain (path name in the format of /data/images).

kernel parameters

Kernel command line parameter strings to be used with the defined kernel on boot.

The Initial Run section is used to specify whether to use Cloud-Init or Sysprep to initialize the virtual machine. For Linux-based virtual machines, you must select the Use Cloud-Init check box in the Initial Run tab to view the available options. For Windows-based virtual machines, you must attach the [sysprep] floppy by selecting the Attach Floppy check box in the Boot Options tab and selecting the floppy from the list.

The options that are available in the Initial Run section differ depending on the operating system that the virtual machine is based on.

Table 31. Initial Run Section (Linux-based Virtual Machines)

Field Name Description

VM Hostname

The host name of the virtual machine.

Configure Time Zone

The time zone for the virtual machine. Select this check box and select a time zone from the Time Zone list.

Authentication

The authentication details for the virtual machine. Click the disclosure arrow to display the settings for this option.

Creates a new user account on the virtual machine. If this field is not filled in, the default user is root.

This check box is automatically selected after you specify an initial root password. You must clear this check box to enable the Password and Verify Password fields and specify a new password.

The root password for the virtual machine. Enter the password in this text field and the Verify Password text field to verify the password.

SSH keys to be added to the authorized keys file of the virtual machine.

Regenerates SSH keys for the virtual machine.

Networks

Network-related settings for the virtual machine. Click the disclosure arrow to display the settings for this option.

The DNS servers to be used by the virtual machine.

The DNS search domains to be used by the virtual machine.

Configures network interfaces for the virtual machine. Select this check box and click + or to add or remove network interfaces to or from the virtual machine. When you click +, a set of fields becomes visible that can specify whether to use DHCP, and configure an IP address, netmask, and gateway, and specify whether the network interface will start on boot.

Custom Script

Custom scripts that will be run on the virtual machine when it starts. The scripts entered in this field are custom YAML sections that are added to those produced by the Engine, and allow you to automate tasks such as creating users and files, configuring yum repositories and running commands. For more information on the format of scripts that can be entered in this field, see the Custom Script documentation.

Table 32. Initial Run Section (Windows-based Virtual Machines)

Field Name Description

VM Hostname

The host name of the virtual machine.

Domain

The Active Directory domain to which the virtual machine belongs.

Organization Name

The name of the organization to which the virtual machine belongs. This option corresponds to the text field for setting the organization name displayed when a machine running Windows is started for the first time.

Active Directory OU

The organizational unit in the Active Directory domain to which the virtual machine belongs. The distinguished name must be provided. For example CN=Users,DC=lab,DC=local

Configure Time Zone

The time zone for the virtual machine. Select this check box and select a time zone from the Time Zone list.

Admin Password

The administrative user password for the virtual machine. Click the disclosure arrow to display the settings for this option.

This check box is automatically selected after you specify an initial administrative user password. You must clear this check box to enable the Admin Password and Verify Admin Password fields and specify a new password.

The administrative user password for the virtual machine. Enter the password in this text field and the Verify Admin Password text field to verify the password.

Custom Locale

Locales must be in a format such as en-US. Click the disclosure arrow to display the settings for this option.

The locale for user input.

The language used for user interface elements such as buttons and menus.

The locale for the overall system.

The locale for users.

Sysprep

A custom Sysprep definition. The definition must be in the format of a complete unattended installation answer file. You can copy and paste the default answer files in the /usr/share/ovirt-engine/conf/sysprep/ directory on the machine on which the oVirt Engine is installed and alter the fields as required. The definition will overwrite any values entered in the Initial Run fields. See Templates for more information.

Domain

The Active Directory domain to which the virtual machine belongs. If left blank, the value of the previous Domain field is used.

Alternate Credentials

Selecting this check box allows you to set a User Name and Password as alternative credentials.

The System section enables you to define the supported machine type or CPU type.

Table 33. System Section

Field Name Description

Custom Emulated Machine

This option allows you to specify the machine type. If changed, the virtual machine will only run on hosts that support this machine type. Defaults to the cluster’s default machine type.

Custom CPU Type

This option allows you to specify a CPU type. If changed, the virtual machine will only run on hosts that support this CPU type. Defaults to the cluster’s default CPU type.

The Host section is used to define the virtual machine’s host.

Table 34. Host Section

Field Name Description

Any host in cluster

Allocates the virtual machine to any available host.

Specific Host(s)

Specifies a user-defined host for the virtual machine.

The Console section defines the protocol to connect to virtual machines.

Table 35. Console Section

Field Name Description

Headless Mode

Select this option if you do not require a graphical console when running the machine for the first time. See Configuring Headless Machines for more information.

VNC

Requires a VNC client to connect to a virtual machine using VNC. Optionally, specify VNC Keyboard Layout from the drop-down list.

SPICE

Recommended protocol for Linux and Windows virtual machines. Using SPICE protocol with QXLDOD drivers is supported for Windows 10 and Windows Server 2016 and later virtual machines.

Enable SPICE file transfer

Determines whether you can drag and drop files from an external host into the virtual machine’s SPICE console. This option is only available for virtual machines using the SPICE protocol. This check box is selected by default.

Enable SPICE clipboard copy and paste

Defines whether you can copy and paste content from an external host into the virtual machine’s SPICE console. This option is only available for virtual machines using the SPICE protocol. This check box is selected by default.

The Custom Properties section contains additional VDSM options for running virtual machines. See New VMs Custom Properties for details.

Explanation of Settings in the New Network Interface and Edit Network Interface Windows

These settings apply when you are adding or editing a virtual machine network interface. If you have more than one network interface attached to a virtual machine, you can put the virtual machine on more than one logical network.

Table 36. Network Interface Settings

Field Name Description Power cycle required?

Name

The name of the network interface. This text field has a 21-character limit and must be a unique name with any combination of uppercase and lowercase letters, numbers, hyphens, and underscores.

No.

Profile

The vNIC profile and logical network that the network interface is placed on. By default, all network interfaces are put on the ovirtmgmt management network.

No.

Type

The virtual interface the network interface presents to virtual machines.

  • rtl8139 and e1000 device drivers are included in most operating systems.

  • VirtIO is faster but requires VirtIO drivers. Enterprise Linux 5 and later include VirtIO drivers. Windows does not include VirtIO drivers, but they can be installed from the guest tools ISO or virtual floppy disk.

  • PCI Passthrough enables the vNIC to be directly connected to a virtual function (VF) of an SR-IOV-enabled NIC. The vNIC will then bypass the software network virtualization and connect directly to the VF for direct device assignment. The selected vNIC profile must also have Passthrough enabled.

Yes.

Custom MAC address

Choose this option to set a custom MAC address. The oVirt Engine automatically generates a MAC address that is unique to the environment to identify the network interface. Having two devices with the same MAC address online in the same network causes networking conflicts.

Yes.

Link State

Whether or not the network interface is connected to the logical network.

  • Up: The network interface is located on its slot.

    • When the Card Status is Plugged, it means the network interface is connected to a network cable, and is active.

    • When the Card Status is Unplugged, the network interface will automatically be connected to the network and become active once plugged.

  • Down: The network interface is located on its slot, but it is not connected to any network. Virtual machines will not be able to run in this state.

No.

Card Status

Whether or not the network interface is defined on the virtual machine.

  • Plugged: The network interface has been defined on the virtual machine.

    • If its Link State is Up, it means the network interface is connected to a network cable, and is active.

    • If its Link State is Down, the network interface is not connected to a network cable.

  • Unplugged: The network interface is only defined on the Engine, and is not associated with a virtual machine.

    • If its Link State is Up, when the network interface is plugged it will automatically be connected to a network and become active.

    • If its Link State is Down, the network interface is not connected to any network until it is defined on a virtual machine.

No.

Explanation of settings in the New Virtual Disk and Edit Virtual Disk windows

The following tables do not include information on whether a power cycle is required because that information is not applicable to these scenarios.

Table 37. New Virtual Disk and Edit Virtual Disk settings: Image

Field Name Description

Size(GB)

The size of the new virtual disk in GB.

Alias

The name of the virtual disk, limited to 40 characters.

Description

A description of the virtual disk. This field is recommended but not mandatory.

Interface

The virtual interface the disk presents to virtual machines. VirtIO is faster, but requires drivers. Enterprise Linux 5 and later include these drivers. Windows does not include these drivers, but you can install them from the virtio-win ISO image. IDE and SATA devices do not require special drivers.

The interface type can be updated after stopping all virtual machines that the disk is attached to.

Data Center

The data center in which the virtual disk will be available.

Storage Domain

The storage domain in which the virtual disk will be stored. The drop-down list shows all storage domains available in the given data center, and also shows the total space and currently available space in the storage domain.

Allocation Policy

The provisioning policy for the new virtual disk.

  • Preallocated allocates the entire size of the disk on the storage domain at the time the virtual disk is created. The virtual size and the actual size of a preallocated disk are the same. Preallocated virtual disks take more time to create than thin provisioned virtual disks, but have better read and write performance. Preallocated virtual disks are recommended for servers and other I/O intensive virtual machines. If a virtual machine is able to write more than 1 GB every four seconds, use preallocated disks where possible.

  • Thin Provision allocates 1 GB at the time the virtual disk is created and sets a maximum limit on the size to which the disk can grow. The virtual size of the disk is the maximum limit; the actual size of the disk is the space that has been allocated so far. Thin provisioned disks are faster to create than preallocated disks and allow for storage over-commitment. Thin provisioned virtual disks are recommended for desktops.

Disk Profile

The disk profile assigned to the virtual disk. Disk profiles define the maximum amount of throughput and the maximum level of input and output operations for a virtual disk in a storage domain. Disk profiles are defined on the storage domain level based on storage quality of service entries created for data centers.

Activate Disk(s)

Activate the virtual disk immediately after creation. This option is not available when creating a floating disk.

Wipe After Delete

Allows you to enable enhanced security for deletion of sensitive material when the virtual disk is deleted.

Bootable

Enables the bootable flag on the virtual disk.

Shareable

Attaches the virtual disk to more than one virtual machine at a time.

Read Only

Allows you to set the disk as read-only. The same disk can be attached as read-only to one virtual machine, and as rewritable to another. This option is not available when creating a floating disk.

Enable Discard

Allows you to shrink a thin provisioned disk while the virtual machine is up. For block storage, the underlying storage device must support discard calls, and the option cannot be used with Wipe After Delete unless the underlying storage supports the discard_zeroes_data property. For file storage, the underlying file system and the block device must support discard calls. If all requirements are met, SCSI UNMAP commands issued from guest virtual machines is passed on by QEMU to the underlying storage to free up the unused space.

The Direct LUN settings can be displayed in either Targets > LUNs or LUNs > Targets. Targets > LUNs sorts available LUNs according to the host on which they are discovered, whereas LUNs > Targets displays a single list of LUNs.

Table 38. New Virtual Disk and Edit Virtual Disk settings: Direct LUN

Field Name Description

Alias

The name of the virtual disk, limited to 40 characters.

Description

A description of the virtual disk. This field is recommended but not mandatory. By default the last 4 characters of the LUN ID is inserted into the field.

The default behavior can be configured by setting the PopulateDirectLUNDiskDescriptionWithLUNId configuration key to the appropriate value using the engine-config command. The configuration key can be set to -1 for the full LUN ID to be used, or 0 for this feature to be ignored. A positive integer populates the description with the corresponding number of characters of the LUN ID.

Interface

The virtual interface the disk presents to virtual machines. VirtIO is faster, but requires drivers. Enterprise Linux 5 and later include these drivers. Windows does not include these drivers, but you can install them from the virtio-win ISO image. IDE and SATA devices do not require special drivers.

The interface type can be updated after stopping all virtual machines that the disk is attached to.

Data Center

The data center in which the virtual disk will be available.

Host

The host on which the LUN will be mounted. You can select any host in the data center.

Storage Type

The type of external LUN to add. You can select from either iSCSI or Fibre Channel.

Discover Targets

This section can be expanded when you are using iSCSI external LUNs and Targets > LUNs is selected.

Address — The host name or IP address of the target server.

Port — The port by which to attempt a connection to the target server. The default port is 3260.

User Authentication — The iSCSI server requires User Authentication. The User Authentication field is visible when you are using iSCSI external LUNs.

CHAP user name — The user name of a user with permission to log in to LUNs. This field is accessible when the User Authentication check box is selected.

CHAP password — The password of a user with permission to log in to LUNs. This field is accessible when the User Authentication check box is selected.

Activate Disk(s)

Activate the virtual disk immediately after creation. This option is not available when creating a floating disk.

Bootable

Allows you to enable the bootable flag on the virtual disk.

Shareable

Allows you to attach the virtual disk to more than one virtual machine at a time.

Read Only

Allows you to set the disk as read-only. The same disk can be attached as read-only to one virtual machine, and as rewritable to another. This option is not available when creating a floating disk.

Enable Discard

Allows you to shrink a thin provisioned disk while the virtual machine is up. With this option enabled, SCSI UNMAP commands issued from guest virtual machines is passed on by QEMU to the underlying storage to free up the unused space.

Enable SCSI Pass-Through

Available when the Interface is set to VirtIO-SCSI. Selecting this check box enables passthrough of a physical SCSI device to the virtual disk. A VirtIO-SCSI interface with SCSI passthrough enabled automatically includes SCSI discard support. Read Only is not supported when this check box is selected.

When this check box is not selected, the virtual disk uses an emulated SCSI device. Read Only is supported on emulated VirtIO-SCSI disks.

Allow Privileged SCSI I/O

Available when the Enable SCSI Pass-Through check box is selected. Selecting this check box enables unfiltered SCSI Generic I/O (SG_IO) access, allowing privileged SG_IO commands on the disk. This is required for persistent reservations.

Using SCSI Reservation

Available when the Enable SCSI Pass-Through and Allow Privileged SCSI I/O check boxes are selected. Selecting this check box disables migration for any virtual machine using this disk, to prevent virtual machines that are using SCSI reservation from losing access to the disk.

Fill in the fields in the Discover Targets section and click Discover to discover the target server. You can then click the Login All button to list the available LUNs on the target server and, using the radio buttons next to each LUN, select the LUN to add.

Using LUNs directly as virtual machine hard disk images removes a layer of abstraction between your virtual machines and their data.

The following considerations must be made when using a direct LUN as a virtual machine hard disk image:

  • Live storage migration of direct LUN hard disk images is not supported.

  • Direct LUN disks are not included in virtual machine exports.

  • Direct LUN disks are not included in virtual machine snapshots.

Mounting a journaled file system requires read-write access. Using the Read Only option is not appropriate for virtual disks that contain such file systems (e.g. EXT3, EXT4, or XFS).

Explanation of Settings in the New Template Window

The following table details the settings for the New Template window.

The following tables do not include information on whether a power cycle is required because that information is not applicable to this scenario.
  1. New Template Settings

Field

Description/Action

Name

The name of the template. This is the name by which the template is listed in the Templates tab in the Administration Portal and is accessed via the REST API. This text field has a 40-character limit and must be a unique name within the data center with any combination of uppercase and lowercase letters, numbers, hyphens, and underscores. The name can be reused in different data centers in the environment.

Description

A description of the template. This field is recommended but not mandatory.

Comment

A field for adding plain text, human-readable comments regarding the template.

Cluster

The cluster with which the template is associated. This is the same as the original virtual machines by default. You can select any cluster in the data center.

CPU Profile

The CPU profile assigned to the template. CPU profiles define the maximum amount of processing capability a virtual machine can access on the host on which it runs, expressed as a percent of the total processing capability available to that host. CPU profiles are defined for a cluster based on quality of service entries created for data centers.

Create as a Template Sub-Version

Specifies whether the template is created as a new version of an existing template. Select this check box to access the settings for configuring this option.

  • Root Template: The template under which the sub-template is added.

  • Sub-Version Name: The name of the template. This is the name by which the template is accessed when creating a new virtual machine based on the template. If the virtual machine is stateless, the list of sub-versions will contain a latest option rather than the name of the latest sub-version. This option automatically applies the latest template sub-version to the virtual machine upon reboot. Sub-versions are particularly useful when working with pools of stateless virtual machines.

Disks Allocation

Alias — An alias for the virtual disk used by the template. By default, the alias is set to the same value as that of the source virtual machine.

Virtual Size — The total amount of disk space that a virtual machine based on the template can use. This value cannot be edited, and is provided for reference only. This value corresponds with the size, in GB, that was specified when the disk was created or edited.

Format — The format of the virtual disk used by the template. The available options are QCOW2 and Raw. By default, the format is set to Raw.

Target — The storage domain on which the virtual disk used by the template is stored. By default, the storage domain is set to the same value as that of the source virtual machine. You can select any storage domain in the cluster.

Disk Profile — The disk profile to assign to the virtual disk used by the template. Disk profiles are created based on storage profiles defined in the data centers. For more information, see Creating a Disk Profile.

Allow all users to access this Template

Specifies whether a template is public or private. A public template can be accessed by all users, whereas a private template can only be accessed by users with the TemplateAdmin or SuperUser roles.

Copy VM permissions

Copies explicit permissions that have been set on the source virtual machine to the template.

Seal Template (Linux only)

Specifies whether a template is sealed. ‘Sealing’ is an operation that erases all machine-specific configurations from a filesystem, including SSH keys, UDEV rules, MAC addresses, system ID, and hostname. This setting prevents a virtual machine based on this template from inheriting the configuration of the source virtual machine.

Appendix B: virt-sysprep Operations

The virt-sysprep command removes system-specific details.

Only operations marked with * are performed during the template sealing process.

# virt-sysprep --list-operations
abrt-data * Remove the crash data generated by ABRT
bash-history * Remove the bash history in the guest
blkid-tab * Remove blkid tab in the guest
ca-certificates   Remove CA certificates in the guest
crash-data * Remove the crash data generated by kexec-tools
cron-spool * Remove user at-jobs and cron-jobs
customize * Customize the guest
dhcp-client-state * Remove DHCP client leases
dhcp-server-state * Remove DHCP server leases
dovecot-data * Remove Dovecot (mail server) data
firewall-rules   Remove the firewall rules
flag-reconfiguration   Flag the system for reconfiguration
fs-uuids   Change filesystem UUIDs
kerberos-data   Remove Kerberos data in the guest
logfiles * Remove many log files from the guest
lvm-uuids * Change LVM2 PV and VG UUIDs
machine-id * Remove the local machine ID
mail-spool * Remove email from the local mail spool directory
net-hostname * Remove HOSTNAME in network interface configuration
net-hwaddr * Remove HWADDR (hard-coded MAC address) configuration
pacct-log * Remove the process accounting log files
package-manager-cache * Remove package manager cache
pam-data * Remove the PAM data in the guest
puppet-data-log * Remove the data and log files of puppet
rh-subscription-manager * Remove the RH subscription manager files
rhn-systemid * Remove the RHN system ID
rpm-db * Remove host-specific RPM database files
samba-db-log * Remove the database and log files of Samba
script * Run arbitrary scripts against the guest
smolt-uuid * Remove the Smolt hardware UUID
ssh-hostkeys * Remove the SSH host keys in the guest
ssh-userdir * Remove ".ssh" directories in the guest
sssd-db-log * Remove the database and log files of sssd
tmp-files * Remove temporary files
udev-persistent-net * Remove udev persistent net rules
user-account   Remove the user accounts in the guest
utmp * Remove the utmp file
yum-uuid * Remove the yum UUID

Appendix C: Legal notice

How to Open KVM oVirt Virtual machine console from windows

To open virtual machine console from ovirt manager (KVM)

1. Download and Install ovirt-viewer from the below link:

    https://virt-manager.org/download

2.From browser open ovirt engine and login to administrator portal

3.Right click the virtual machine and choose «Console»

4.Console file be getting created on your windows->downloads

5.Right click the file ->Properties and change the file «Opens With:» as a new program and browse till

c:\program files->ovirt-viewer-> «Remote-Viewer» type

5.Now double click on the «Console.vv» file

will open the console:

Popular posts from this blog

Deploy OVF fails Issues detected with selected template. Details: VALUE_ILLEGAL: No supported hardware versions among [virtualbox-2.2]; supported: [vmx-04, vmx-07, vmx-08, vmx-09, vmx-10, vmx-11, vmx-12, vmx-13, vmx-14, vmx-15, vmx-16, vmx-17, vmx-18, vmx-19].

 Error: While deploy using OVF file ,getting error as : Issues detected with selected template. Details: — -1:-1:VALUE_ILLEGAL: No supported hardware versions among [virtualbox-2.2]; supported: [vmx-04, vmx-07, vmx-08, vmx-09, vmx-10, vmx-11, vmx-12, vmx-13, vmx-14, vmx-15, vmx-16, vmx-17, vmx-18, vmx-19]. Solution: Open .OVF file and edit       <Info>Virtual hardware requirements for a virtual machine</Info>       <System>         <vssd:ElementName>Virtual Hardware Family</vssd:ElementName>         <vssd:InstanceID>0</vssd:InstanceID>         <vssd:VirtualSystemIdentifier>zabbix_appliance-6.2.7</vssd:VirtualSystemIdentifier>         <vssd:VirtualSystemType> virtualbox-2.2 </vssd:VirtualSystemType>       </System> to  vmx-19       <Info>Virtual hardware requireme…

  Error: While power ON VM fails » Failed to enumerate all disk”  Solution: Go to VM ->Edit settings->Hard disk make sure there are no stale hard disks assigned to VM if that disk is not needed, delete that disk and Power ON Else make the datastore or disks available/online and then Power ON

When you enable Vcenter HA on vsphere7.0 esxi cluster if you see any of the below error: vSphere HA agent for this host has an error: The vSphere HA agent is not reachable from vCenter Server Vsphere HA status error vSphere HA agent cannot be installed or configured  Solution: -Download latest Vmware tools VIB package from:   https://my.vmware.com/group/vmware/downloads/details?downloadGroup=VMTOOLS1125&productId=974&rPId=58693 -winscp to ESXi host the zip file of VIB. -Install the package:  esxcli software vib install -d  «/tmp/VMware-Tools-11.2.5-core-offline-depot-ESXi-all-17337674.zip» -Reboot the Esxi. -Right click on the esxi to do «Reconfigure vSphere HA»

To open a console on windows with ovirt with spice use virt-viewer 2.0.

Howto:
Install on the ovirt all the spice tools.
Install http://virt-manager.org/download/sources/virt-viewer/virt-viewer-x86-2.0.msi
If you open a console of a machine you will get a .vv file.
Associate this file with C:\Program Files (x86)\VirtViewer v2.0256\bin\remote-viewer
“right button an associate with”

Now the tool will open and your console is open!! every time..

Explore posts in the same categories: Uncategorized


This entry was posted on april 17, 2015 at 12:05 and is filed under Uncategorized. You can subscribe via RSS 2.0 feed to this post’s comments. You can comment below, or link to this permanent URL from your own site.

Руководство по работе с виртуальными машинами

1. Общие сведения о виртуальных машинах

Виртуальная машина — это компьютер, реализованный программными средствами. В традиционных вычислительных средах процессы обычно выполняются на серверах, которые администрируют и обновляют по отдельности, в среде zVirt же можно создавать виртуальные рабочие станции и виртуальные серверы, при этом вычислительные задачи и процессы выполняются в основном на виртуальных машинах. При выполнении сопоставимых вычислительных задач и процессов при использовании zVirt требуется меньший объем оборудования и администрирования.

Большинство задач, связанных с работой виртуальных машин в zVirt, можно выполнять на Пользовательском портале и на Портале администрирования. При этом пользовательский интерфейс на каждом портале разный, а для некоторых административных задач требуется доступ к Порталу администрирования. В этом руководстве в описании задачи будет отдельно указано, если ее можно выполнить только на Портале администрирования. Используемый портал и задачи, которые можно выполнять на каждом портале, зависят от уровня разрешений. Разрешения виртуальных машин описаны в разделе Виртуальные машины и разрешения.

1.1. Поддерживаемые операционные системы виртуальных машин

Информацию об операционных системах, которые можно виртуализировать в качестве гостевых операционных систем в zVirt, ищите на https://orionsoft.ru/.

1.2. Параметры производительности виртуальных машин

1.3. Установка вспомогательных компонентов на клиентские машины

1.3.1. Установка компонентов консоли

Консоль — это графическое окно,в котором отображаются экран запуска, экран выключения и рабочий стол виртуальной машины, и позволяет управлять ею, как физической машиной. В zVirt для открытия консоли виртуальной машины по умолчанию используется инструмент удаленного просмотра Remote Viewer и он должен быть установлен на клиентской машине до начала использования.

Установка инструмента удаленного просмотра Remote Viewer на ОС семейства Red Hat Enterprise Linux

Инструмент удаленного просмотра Remote Viewer предоставляет пользователям графическую консоль для подключения к виртуальным машинам. После установки он вызывается автоматически при открытии сессии SPICE на виртуальной машине. Его также можно использовать в качестве автономного приложения. Инструмент удаленного просмотра Remote Viewer входит в состав пакета virt-viewer.

Порядок действий:

  1. Установите пакет virt-viewer:

  2. Перезапустите браузер, чтобы изменения вступили в силу.

Теперь можно подключить виртуальные машины с помощью протокола SPICE, либо протокола VNC.

Установка инструмента удаленного просмотра Remote Viewer на Windows

Инструмент удаленного просмотра Remote Viewer предоставляет пользователям графическую консоль для подключения к виртуальным машинам. После установки он вызывается автоматически при открытии сессии SPICE на виртуальной машине. Его также можно использовать в качестве автономного приложения.

Порядок действий:

  1. Откройте веб-браузер и загрузите следующие установщики в соответствии с архитектурой вашей системы:

    • Virt Viewer для 32-разрядной версии Windows.

    • Virt Viewer для 64-разрядной версии Windows.

  2. Откройте папку, в которую сохранен файл.

  3. Дважды щелкните по файлу.

  4. Нажмите Запустить (Run), если всплывет предупреждение системы безопасности.

  5. Нажмите Да (Yes), если появится окно Контроль учетных записей пользователей (User Account Control).

Инструмент удаленного просмотра (Remote Viewer) установлен. Его можно открыть, нажав Remote Viewer в папке VirtViewer в списке Все программы (All Programs) в меню «Пуск».

Установка драйвера usbdk на Windows

usbdk — это драйвер, который обеспечивает эксклюзивный доступ Remote Viewer к USB-устройствам в операционных системах Windows. Для установки usbdk необходимы права Администратора. Обратите внимание, что ранее поддерживаемая опция USB Clerk устарела и больше поддерживаться не будет.

Порядок действий:

  1. Откройте веб-браузер и загрузите следующие установщики в соответствии с архитектурой вашей системы:

    • usbdk для 32-разрядной версии Windows.

    • usbdk для 64-разрядной версии Windows.

  2. Откройте папку, в которую сохранен файл.

  3. Дважды щелкните по файлу.

  4. Нажмите Запустить (Run), если всплывет предупреждение системы безопасности.

  5. Нажмите Да (Yes), если появится окно Контроль учетных записей пользователей (User Account Control).

2. Создание виртуальной машины Linux

Чтобы создать виртуальную машину Linux, выполните следующие шаги:

  1. Создайте виртуальную машину. Необходимо добавить виртуальный диск для хранилища и сетевой интерфейс для подключения виртуальной машины к сети.

  2. Запустите виртуальную машину и установите операционную систему. Сверьтесь с инструкциями по установке вашей операционной системы.

  3. Включите необходимые репозитории для вашей операционной системы.

  4. Установите гостевые агенты и драйверы для дополнительных функций виртуальной машины.

2.1. Создание виртуальной машины

Создание виртуальной машины заключается в задании её настроек (некоторые из них можно будет изменить позднее) и последующей установке операционной системы.

Порядок действий:

  1. Нажмите .

  2. Нажмите Создать (New). Откроется окно Новая виртуальная машина (New Virtual Machine).

  3. Выберите Операционную систему (Operating System) в выпадающем списке.

    Если выбрать Red Hat Enterprise Linux CoreOS в качестве операционной системы, то система может попросить задать способ инициализации. Для этого настройте параметры утилиты Ignition в Расширенных настройках (Advanced Options) на вкладке Запуск инициализации (Initial Run). См. раздел Конфигурирование утилиты Ignition.
  4. Укажите Имя (Name) виртуальной машины.

  5. Добавьте хранилище к виртуальной машине:

    • Для добавления существующего диска: нажмите Прикрепить (Attach) и выберите существующий виртуальный диск.

    • Для создания нового диска: нажмите Создать (Create) и укажите Размер (GiB) (Size(GiB)) и Имя (Alias) нового виртуального диска. В остальных полях можно принять настройки по умолчанию или изменить их при необходимости. Дополнительные сведения о полях для всех типов дисков см. в разделе Описание настроек в окнах «Новый диск (New Virtual Disk)» и «Изменить виртуальный диск (Edit Virtual Disk)».

  6. Подключите виртуальную машину к сети. Добавьте сетевой интерфейс, выбрав vNIC-профиль в выпадающем списке nic1 внизу на вкладке Общее (General).

  7. Задайте Оперативная память (разделяемая) (Memory Size) виртуальной машины на вкладке Система (System).

  8. На вкладке Параметры загрузки (Boot Options) выберите Первое устройство (First Device), которое виртуальная машина будет использовать для начальной загрузки.

  9. В остальных полях можно принять настройки по умолчанию или изменить их при необходимости. Дополнительные сведения о всех полях в окне Новая виртуальная машина (New Virtual Machine) см. в разделе Описание настроек в окнах «Создать ВМ (New Virtual Machine)» и «Изменить ВМ (Edit Virtual Machine)».

  10. Нажмите OK.

Новая виртуальная машина создана и отображается в списке виртуальных машин в состоянии Выключено (Down). Перед её использованием необходимо:

  • Установить операционную систему:

    • С помощью предустановленного образа путем Создания клонированной виртуальной машины на основе шаблона.

    • С помощью предустановленного образа с подключенного предустановленного диска.

    • С помощью установки операционной системы через меню начальной загрузки PXE или из файла ISO.

  • Настроить доступ к репозиториям программного обеспечения.

2.1.1. Конфигурирование утилиты Ignition

Ignition — это утилита, которая применяется в Red Hat Enterprise Linux CoreOS для работы с дисками во время первоначальной настройки. Она выполняет типовые манипуляции с дисками, включая разбиение на разделы, форматирование разделов, запись файлов и настройку пользователей. Во время первоначальной загрузки утилита Ignition считывает свои настройки с установочного носителя или из указанного места и применяет их к машинам.

После того как в качестве метода инициализации была настроена утилита Ignition, это нельзя отменить или перенастроить.
  1. В окне Новая виртуальная машина (New Virtual Machine) или Изменить виртуальную машину (Edit Virtual Machine) нажмите Показать расширенные настройки (Show Advanced Options).

  2. На вкладке Запуск инициализации (Initial Run) выберите Ignition 2.3.0 и введите Имя хоста ВМ (VM Hostname).

  3. Разверните параметр Аутентификация (Authentication), введите имя пользователя и хешированный (SHA-512) пароль и затем повторите ввод пароля для проверки.

  4. Если для аутентификации используется SSH-ключ, введите его в специальное поле.

  5. Можно также ввести пользовательский скрипт Ignition в формате JSON в поле Скрипт включения (Ignition Script). Этот скрипт будет выполняться на виртуальной машине сразу после ее запуска. Вводимые здесь скрипты — это пользовательские разделы JSON, которые добавляются к тем, что создает Менеджер управления, и позволяют использовать пользовательские инструкции Ignition.

Если используемый образ Red Hat Enterprise Linux CoreOS содержит в себе утилиту Ignition любой версии, кроме 2.3.0, то необходимо использовать скрипт в поле Скрипт включения (Ignition Script), чтобы принудительно запустить версию утилиты Ignition, которая включена в образ Red Hat Enterprise Linux CoreOS.

При использовании скрипта Ignition его инструкции будут иметь преобладающую силу и переопределяет любые конфликтующие с ним настройки Ignition, заданные вами в пользовательском интерфейсе.

2.2. Запуск виртуальной машины

2.2.1. Запуск виртуальной машины

Порядок действий:

  1. Нажмите и выберите виртуальную машину в состоянии Выключено (Down).

  2. Нажмите Запустить (Run).

Статус виртуальной машины поменяется на Включено (Up), и начнется установка операционной системы. Откройте консоль виртуальной машины, если та не откроется автоматически.

Виртуальная машина не запустится на хосте с перегруженным ЦП. По умолчанию ЦП хоста считается перегруженным, если нагрузка на него превышает 80% в течение 5 минут, но эти значения можно изменить с помощью политик планирования.

Поиск и устранение неполадок

Сценарий — начальная загрузка виртуальной машины не выполняется, и показано следующее сообщение об ошибке:

Boot failed: not a bootable disk - No Bootable device

Возможные решения проблемы:

  • Удостоверьтесь, что Жесткий диск (Hard Disk) выбран первым устройством в последовательности загрузки, а диск, с которого загружается виртуальная машина, помечен как Загрузочный (Bootable).

  • Создайте клон виртуальной машины на основе шаблона.

  • Создайте новую виртуальную машину с локальным диском начальной загрузки, управляемым zVirt, на котором есть ОС и необходимые приложения.

  • Установите ОС, запустив начальную загрузку с помощью варианта Сеть (PXE) (Network (PXE)).

2.2.2. Открытие консоли виртуальной машины

Для подключения к виртуальной машине используйте инструмент Remote Viewer.

Чтобы другие пользователи могли подключиться к ВМ, обязательно выключите и перезапустите виртуальную машину после завершения работы с консолью. Либо администратор может отключить строгую проверку пользователей (Disable strict user checking), чтобы исключить необходимость перезагрузки между сеансами пользователей. Дополнительную информацию см. в разделе Описание настроек консоли виртуальной машины.

Порядок действий:

  1. Установите инструмент Remote Viewer, если он еще не установлен. См. Установка компонентов консоли.

  2. Нажмите и выберите виртуальную машину.

  3. Нажмите Консоль (Console). По умолчанию браузер предложит загрузить файл с именем console.vv. При открытии файла откроется окно консоли виртуальной машины.

Данные в файле console.vv действительны на протяжении 120 секунд после загрузки. Если прошло больше времени, нажмите Консоль (Console) еще раз.

2.2.3. Открытие последовательной консоли виртуальной машины

Доступ к последовательной консоли виртуальной машины можно получить из командной строки вместо того, чтобы открывать консоль на Портале администрирования или Пользовательском портале. Последовательная консоль эмулируется через каналы VirtIO с использованием SSH и пар ключей. Менеджер управления действует как прокси-сервер для подключения, предоставляет информацию о размещении виртуальной машины и хранит ключи аутентификации. Открытые ключи для каждого пользователя можно добавить либо на Портале администрирования, либо на Пользовательском портале. Доступ к последовательным консолям можно получить только для тех виртуальных машин, для которых у вас есть соответствующие разрешения.

Для доступа к последовательной консоли виртуальной машины пользователь должен иметь разрешение UserVmManager, SuperUser или UserInstanceManager на этой виртуальной машине. Эти разрешения должны быть прямо заданы для каждого пользователя, недостаточно просто назначить их Everyone.

Для доступа к последовательной консоли служит порт TCP 2222 в Менеджере управления. Этот порт открывается во время работы engine-setup при новой инсталляции.

Использование последовательной консоли требует настройки правил межсетевого экрана.

Для работы последовательной консоли необходимы пакеты ovirt-vmconsole и ovirt-vmconsole-proxy в Менеджере управления, а также пакеты ovirt-vmconsole и ovirt-vmconsole-host на хостах виртуализации. При установке новых инсталляций эти пакеты устанавливаются по умолчанию. Чтобы установить эти пакеты на существующих системах, переустановите хост.

Включение последовательной консоли виртуальной машины
  1. На виртуальной машине, к последовательной консоли которой вы обращаетесь, добавьте следующие строки в /etc/default/grub:

    GRUB_CMDLINE_LINUX_DEFAULT="console=tty0 console=ttyS0,115200n8"
    GRUB_TERMINAL="console serial"
    GRUB_SERIAL_COMMAND="serial --speed=115200 --unit=0 --word=8 --parity=no --stop=1"

    GRUB_CMDLINE_LINUX_DEFAULT применяет эту конфигурацию только к пункту меню по умолчанию. Используйте GRUB_CMDLINE_LINUX, чтобы применить конфигурацию ко всем пунктам меню.

    Если эти строки уже есть в /etc/default/grub, обновите их, не дублируйте.

  2. Пересоздайте /boot/grub2/grub.cfg:

    • Машины на основе BIOS:

      grub2-mkconfig -o /boot/grub2/grub.cfg
    • Машины на основе UEFI:

      grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg
  3. На клиентской машине, с которой вы обращаетесь к последовательной консоли виртуальной машины, сгенерируйте пару SSH-ключей. Менеджер управления поддерживает стандартные типы SSH-ключей, например, RSA-ключ:

    ssh-keygen -t rsa -b 2048 -C "user@domain" -f .ssh/serialconsolekey

    Эта команда генерирует открытый ключ и закрытый ключ.

  4. Откройте параметры учетной записи:

    • На Портале администрирования в верхнем меню нажмите > Параметры аккаунта.

    • На Пользовательском портале нажмите Настройки учетной записи на верхней панели и перейдите на вкладку Консоль.

  5. В текстовое поле Публичный ключ пользователя (Открытый SSH ключ на портале пользователя) вставьте открытый ключ клиентской машины, который будет использоваться для доступа к последовательной консоли.

  6. Нажмите и выберите виртуальную машину.

  7. Нажмите Изменить (Edit).

  8. На вкладке Консоль (Console) окна Изменить виртуальную машину (Edit Virtual Machine) установите флажок Консольный порт VirtIO-serial (Enable VirtIO serial console).

Подключение к последовательной консоли виртуальной машины

На клиентской машине подключитесь к последовательной консоли виртуальной машины:

  • Если доступна одна виртуальная машина, то эта команда подключает пользователя к этой виртуальной машине:

    ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN -i .ssh/serialconsolekey
    Red Hat Enterprise Linux Server release 6.7 (Santiago)
    Kernel 2.6.32-573.3.1.el6.x86_64 on an x86_64
    USER login:
  • Если доступно несколько виртуальных машин, то эта команда выводит список доступных виртуальных машин и их идентификаторов:

    ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN -i .ssh/serialconsolekey list
    1. vm1 [vmid1]
    2. vm2 [vmid2]
    3. vm3 [vmid3]
    > 2
    Red Hat Enterprise Linux Server release 6.7 (Santiago)
    Kernel 2.6.32-573.3.1.el6.x86_64 on an x86_64
    USER login:

    Введите номер подключаемой машины и нажмите Enter.

  • Либо подключитесь напрямую к виртуальной машине, используя ее уникальный идентификатор или имя:

    ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN connect --vm-id vmid1
    ssh -t -p 2222 ovirt-vmconsole@Manager_FQDN connect --vm-name vm1
Отключение от последовательной консоли виртуальной машины

Нажмите любую клавишу, а затем ~ ., чтобы закрыть сеанс работы с последовательной консолью.

Если сеанс последовательной консоли завершается аварийно, возникает ситуация TCP-таймаута: повторно подключиться к последовательной консоли виртуальной машины будет невозможно, пока не истечет время ожидания.

2.3. Включение необходимых репозиториев

Включите необходимые репозитории для работы ОС.

2.4. Установка гостевых агентов и драйверов

2.4.1. Гостевые агенты, инструменты и драйверы

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

Обратите внимание на следующие важные моменты:

  • При поиске установочных пакетов, обязательно используйте официальный репозиторий производителя.

  • Для успешной установки и функционирования гостевых дополнений, вам потребуются административные права.

Инструменты и агенты предоставляют информацию для виртуальных машин, включая:

  • Использование ресурсов.

  • IP-адреса.

Гостевые агенты, инструменты и драйверы распространяются в виде rpm/deb-пакетов через официальные репозитории дистрибутивов. Для включения дополнительной функциональности на виртуальной машине установите на ней гостевые агенты и драйверы.

Таблица 1. Гостевые драйверы

Драйвер Описание

virtio-balloon

Драйвер virtio-balloon используется для управления размером памяти, фактически доступной виртуальной машине. Он обеспечивает улучшенное перераспределение памяти.

virtio-net

Паравиртуализированный сетевой драйвер обеспечивает повышенную производительность по сравнению с такими эмулируемыми устройствами, как rtl.

virtio-block

Паравиртуализированный драйвер жесткого диска обеспечивает повышенную производительность ввода-вывода на таких эмулируемых устройствах, как IDE, оптимизируя координацию и связь между виртуальной машиной и гипервизором. Драйвер дополняет программную реализацию virtio-устройства, используемого хостом для выполнения роли аппаратного устройства.

virtio-scsi

Паравиртуализированный драйвер жесткого диска SCSI предлагает похожую функциональность, что и устройство virtio-block, с некоторыми дополнительными улучшениями. В частности, этот драйвер поддерживает добавление сотен устройств и именует устройства согласно стандартной схеме именования устройств SCSI.

virtio-serial

Драйвер virtio-serial обеспечивает поддержку нескольких последовательных портов. Повышенная производительность используется для организации быстрой связи между виртуальной машиной и хостом, на которую не влияют проблемы в сети. Быстрая связь требуется для гостевых агентов и других функций (таких, как копирование и вставка через буфер обмена между виртуальной машиной и хостом и журналирование).

qxl

Паравиртуализированный драйвер дисплея разгружает ЦП хоста и повышает производительность путем сужения полосы пропускания сети на большинстве рабочих нагрузок.

Таблица 2. Гостевые агенты и инструменты

Гостевой агент/инструмент Описание

qemu-guest-agent

Используется вместо ovirt-guest-agent-common на виртуальных машинах Red Hat Enterprise Linux 8. Устанавливается и включается по умолчанию.

spice-agent

SPICE-агент поддерживает несколько мониторов и отвечает за поддержку режима «клиент-мышь», тем самым повышая удобство работы и скорость отклика по сравнению с эмуляцией QEMU. Захват курсора не требуется в режиме «клиент-мышь». SPICE-агент уменьшает использование полосы пропускания при использовании глобальной сети за счет снижения уровня отображения (в том числе глубину цвета), отключения обоев, сглаживания шрифтов и анимации. SPICE-агент включает поддержку буфера обмена (что позволяет вырезать и вставлять текст и изображения между клиентом и виртуальной машиной) и автоматическую настройку гостевого дисплея в соответствии с настройками на стороне клиента. На виртуальных машинах на Windows, SPICE-агент состоит из vdservice и vdagent.

2.4.2. Установка гостевых агентов и драйверов на Linux

Виртуальные машины с ОС на базе RHEL 8 и выше используют службу qemu-guest-agent, установленную и включенную по умолчанию, вместо службы ovirt-guest-agent. Если необходимо вручную установить гостевой агент (в том числе и на RHEL 8), следуйте указаниям ниже.

Порядок действий:

  1. Авторизуйтесь на виртуальной машине с Linux.

  2. Установите гостевые агенты и зависимости:

    • Для ОС на базе RHEL 7 и старше:

      yum install ovirt-guest-agent-common spice-vdagent
    • Для ОС на базе RHEL 8 и новее:

      dnf install qemu-guest-agent spice-vdagent
    • Для ОС на базе Debian:

      apt-get update && apt-get install qemu-guest-agent spice-vdagent
  3. Запустите и включите соответствующую службу:

    • Для ovirt-guest-agent:

      systemctl start ovirt-guest-agent spice-vdagent
      systemctl enable ovirt-guest-agent spice-vdagent
    • Для qemu-guest-agent:

      systemctl start qemu-guest-agent spice-vdagent
      systemctl enable qemu-guest-agent spice-vdagent

Гостевой агент теперь передает информацию об использовании в Менеджер управления. Гостевой агент можно сконфигурировать в файле /etc/ovirt-guest-agent.conf (только для ОС на базе RHEL 7).

Для других операционных систем на ядре Linux обратитесь к их руководству администратора. Чаще всего пакет с гостевыми дополнениями называется qemu-guest-agent.

3. Создание виртуальных машин Windows

Для создания виртуальной машины Windows необходимо выполнить следующие действия:

  1. Создайте пустую виртуальную машину, на которой будет установлена операционная система.

  2. Добавьте виртуальный диск для хранения.

  3. Добавьте сетевой интерфейс для подключения виртуальной машины к сети.

  4. Подключите ISO-диск гостевых инструментов Windows к виртуальной машине, чтобы установить драйверы VirtIO во время установки операционной системы.

  5. Установите операционную систему Windows на виртуальной машине. Ознакомьтесь с инструкциями в документации по операционной системе.

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

После выполнения всех действий новая виртуальная машина будет готова к работе и выполнению задач.

3.1. Создание виртуальной машины

При создании новой виртуальной машины задайте ее настройки. Можно изменить некоторые из этих настроек позднее, включая тип чипсета и BIOS.

Перед использованием этой виртуальной машины обязательно установите операционную систему и драйверы VirtIO.

Порядок действий:

  1. Можно изменить длину имени виртуальной машины, заданную по умолчанию, с помощью инструмента engine-config. Запустите следующую команду на машине с Менеджером управления:

    engine-config --set MaxVmNameLength=integer
  2. Нажмите .

  3. Нажмите Создать (New). Откроется окно Новая виртуальная машина (New Virtual Machine).

  4. Выберите Операционную систему (Operating System) в выпадающем списке.

  5. Введите Имя (Name) для виртуальной машины.

  6. Добавьте устройство хранения к виртуальной машине:

    • Для добавления существующего диска нажмите Прикрепить (Attach) и выберите существующий виртуальный диск.

    • Для создания нового диска нажмите Создать (Create) и введите Размер (GiB) (Size(GiB)) и Имя (Alias) для нового виртуального диска. В остальных полях можно принять настройки по умолчанию или изменить их при необходимости. Более подробную информацию обо всех полях типов дисков см. в разделе Описание настроек в окнах «Создать виртуальный диск (New Virtual Disk)» и «Изменить виртуальный диск (Edit Virtual Disk)».

  7. Подключите виртуальную машину к сети. Добавьте сетевой интерфейс, выбрав профиль vNIC из выпадающего списка nic1 внизу вкладки Общие (General).

  8. Задайте объём Оперативной памяти (разделяемой) (Memory Size) виртуальной машины на вкладке Система (System).

  9. Во вкладке Параметры загрузки (Boot Options) выберите Первое устройство (First Device), которое будет использоваться виртуальной машиной для начальной загрузки.

  10. В остальных полях можно принять настройки по умолчанию или изменить их при необходимости. Для получения дополнительных сведений о всех полях в окне Новая виртуальная машина (New Virtual Machine) см. в разделе Описание настроек в окнах «Новая виртуальная машина (New Virtual Disk)» и «Изменить виртуальную машину (Edit Virtual Machine)».

  11. Нажмите OK.

Новая виртуальная машина создается и отображается в списке виртуальных машин со статусом Выключено (Down).

3.2. Запуск виртуальной машины с использованием параметра «Однократный запуск (Run Once)

3.2.1. Установка Windows на оборудовании VirtIO

Образ ISO с драйверами virtio для Windows, необходимый для выполнения процедур, описанных в этом разделе, можно загрузить в официальном репозитории Orionsoft. Рекомендуем скачивать последнюю доступную версию образа.

Установите диск c драйверами VirtIO устройств во время установки Windows, подключив файл virtio-win_version.iso к виртуальной машине. Эти драйверы обеспечивают увеличение производительности на эмулируемых драйверах устройств.

Используйте , чтобы для разовой загрузки подключить файл virtio-win_version.iso, который отличается от Параметров загрузки (Boot Options), определенных в окне Новая виртуальная машина (New Virtual Machine).

Предварительные условия:

Следующие элементы должны быть добавлены в виртуальную машину:

  • сетевой интерфейс Red Hat VirtIO.

  • диск, использующий интерфейс VirtIO.

Можете загрузить virtio-win_version.iso в домен хранения данных.

Образы ISO следует загружать в домен данных через Портал администрирования или с помощью REST API.

Чтобы установить драйверы virtio-win при установке Windows, выполните следующие действия:

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите .

  3. Разверните меню Параметры загрузки (Boot Options).

  4. Установите флажок Прикрепить CD (Attach CD) и выберите Windows ISO из выпадающего списка.

  5. Установите флажок Прикрепить CD с гостевыми дополнениями для Windows (Attach Windows guest tools CD).

  6. Переместите CD-ROM в начало списка в поле Предпочитаемая последовательность загрузки (Predefined Boot Sequence).

  7. При необходимости настройте другие параметры в окне Запустить ВМ (Run Virtual Machine(s)). Для получения дополнительной информации см. раздел Описание настроек в окне «Запустить ВМ (Run Virtual Machine(s))».

  8. Нажмите OK. Статус виртуальной машины меняется на Включено (Up), и начинается установка операционной системы.

    Откройте консоль виртуальной машины, если она не открылась автоматически во время установки Windows.

  9. Когда система предложит выбрать диск, на который нужно установить Windows, нажмите Загрузить драйвер (Load driver) и затем OK.

  10. В разделе Выбрать драйвер для установки (Select the driver to install) выберите драйвер, подходящий для данной версии Windows. Например, для Windows Server 2019 выберите Red Hat VirtIO SCSI controller (E:\\amd64\\2k19\\viostor.inf).

  11. Нажмите Далее (Next).

Остальная часть процесса установки проходит как обычно.

3.2.2. Открытие консоли виртуальной машины

Для подключения к виртуальной машине используйте инструмент удаленного просмотра (Remote Viewer).

Чтобы другие пользователи могли подключиться к ВМ, обязательно выключите и перезапустите виртуальную машину после завершения работы с консолью. Либо администратор может Выключить строгую проверку пользователей (Disable strict user checking), чтобы исключить необходимость перезагрузки между сеансами пользователей. Для получения дополнительной информации см. Описание настроек консоли виртуальной машины.

Порядок действий:

  1. Установите инструмент удаленного просмотра (Remote Viewer), если он еще не установлен. См. Установка компонентов консоли.

  2. Нажмите и выберите виртуальную машину.

  3. Нажмите Консоль (Console). По умолчанию браузер предложит загрузить файл с именем console.vv. При открытии файла откроется окно консоли виртуальной машины. Браузер можно настроить на автоматическое открытие этих файлов, чтобы нажатие на Консоль (Console) просто открывало консоль.

Открыть файл console.vv можно в течение 120 секунд после загрузки. Если прошло больше времени, нажмите Консоль (Console) еще раз.

3.3. Установка гостевых агентов и драйверов

3.3.1. Гостевые агенты, инструменты и драйверы

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

Обратите внимание на следующие важные моменты:

  • При поиске установочных пакетов, обязательно используйте официальный репозиторий производителя.

  • Для успешной установки и функционирования гостевых дополнений, вам потребуются административные права.

Инструменты и агенты предоставляют информацию для виртуальных машин, включая:

  • Использование ресурсов.

  • IP-адреса.

Гостевые агенты, инструменты и драйверы распространяются в виде файла ISO, который можно подключить к виртуальным машинам.

Для включения этой функциональности на виртуальной машине установите на ней гостевые агенты и драйверы.

Таблица 3. Гостевые драйверы

Драйвер Описание

virtio-net

Паравиртуализированный сетевой драйвер обеспечивает повышенную производительность по сравнению с такими эмулируемыми устройствами, как rtl.

virtio-block

Паравиртуализированный драйвер жесткого диска обеспечивает повышенную производительность ввода-вывода на таких эмулируемых устройствах, как IDE, оптимизируя координацию и связь между виртуальной машиной и гипервизором. Драйвер дополняет программную реализацию virtio-устройства, используемого хостом для выполнения роли аппаратного устройства.

virtio-scsi

Паравиртуализированный драйвер жесткого диска SCSI предлагает похожую функциональность, что и устройство virtio-block, с некоторыми дополнительными улучшениями. В частности, этот драйвер поддерживает добавление сотен устройств и именует устройства согласно стандартной схеме именования устройств SCSI.

virtio-serial

Драйвер virtio-serial обеспечивает поддержку нескольких последовательных портов. Повышенная производительность используется для организации быстрой связи между виртуальной машиной и хостом, на которую не влияют проблемы в сети. Быстрая связь требуется для гостевых агентов и других функций (таких, как копирование и вставка через буфер обмена между виртуальной машиной и хостом и журналирование).

virtio-balloon

Драйвер virtio-balloon используется для управления размером памяти, фактически доступной виртуальной машине. Он улучшает процесс избыточного выделения памяти.

qxl

Паравиртуализированный драйвер дисплея разгружает ЦП хоста и повышает производительность путем сужения полосы пропускания сети на большинстве рабочих нагрузок.

Таблица 4. Гостевые агенты и инструменты

Гостевой агент/инструмент Описание

qemu-guest-agent

Используется вместо ovirt-guest-agent-common на виртуальных машинах Red Hat Enterprise Linux 8. Устанавливается и включается по умолчанию.

spice-agent

SPICE-агент поддерживает несколько мониторов и отвечает за поддержку режима «клиент-мышь», тем самым повышая удобство работы и скорость отклика по сравнению с эмуляцией QEMU. Захват курсора не требуется в режиме «клиент-мышь». SPICE-агент уменьшает использование полосы пропускания при использовании глобальной сети за счет снижения уровня отображения (включая глубину цвета), отключения обоев, сглаживания шрифтов и анимации. SPICE-агент включает поддержку буфера обмена (что позволяет вырезать и вставлять текст и изображения между клиентом и виртуальной машиной) и автоматическую настройку гостевого дисплея в соответствии с настройками на стороне клиента. На виртуальных машинах Windows, SPICE-агент состоит из vdservice и vdagent.

3.3.2. Установка гостевых агентов, инструментов и драйверов в Windows

Образ ISO с драйверами virtio и гостевыми агентами для Windows, необходимый для выполнения процедур, описанных в этом разделе, можно загрузить в официальном репозитории Orionsoft. Рекомендуем скачивать последнюю доступную версию образа.

Для установки гостевых агентов, инструментов и драйверов на виртуальную машину Windows, выполните следующие действия:

Порядок действий:

  1. Загрузите virtio-win_version.iso в домен хранения данных.

  2. Если виртуальная машина работает, то на Портале администрирования или Пользовательском портале кнопкой Сменить CD (Change CD) подключите файл virtio-win_version.iso к каждой иртуальной машине. Если виртуальная машина выключена, нажмите Однократный запуск (Run Once) и подключите файл ISO как CD.

  3. Авторизуйтесь на виртуальной машине.

  4. Выберите CD-привод, содержащий файл virtio-win_version.iso. Установку можно выполнить из графического интерфейса или из командной строки.

  5. Запустите установщик.

    Установку гостевых дополнений для Windows Server 2022 и Windows 11 производите с помощью установщика, расположенного в каталоге win2022-win11.

    Для установки из графического интерфейса пользователя выполните следующие действия:

    1. Дважды нажмите на virtio-win-gt-x64.msi или virtio-win-gt-x86.msi.

    2. Нажмите Далее (Next) на экране приветствия.

    3. Следуйте подсказкам мастера установки.

    4. Когда установка будет завершена, выберите Да, я хочу перезагрузить компьютер сейчас (Yes, I want to restart my computer now) и нажмите Завершить (Finish), чтобы применить изменения.

    5. После перезагрузки виртуальной машины откройте CD-ROM, перейдите в каталог guest-agent и дважды нажмите на qemu-ga-x86_64.msi или qemu-ga-i386.msi, чтобы установить qemu-ga, гостевой агент Qemu.

    Для автоматической установки из командной строки выполните следующие действия:

    1. Откройте командную строку от имени Администратора.

    2. Введите команду msiexec:

      D:\ msiexec /i "PATH_TO_MSI" /qn [/l*v "PATH_TO_LOG"][/norestart] ADDLOCAL=ALL

Другие возможные значения для ADDLOCAL перечислены ниже.

Например, чтобы запустить установку, когда virtio-win-gt-x64.msi находится на диске D:\, без сохранения действий в журнале событий, а затем сразу же перезапустить виртуальную машину, введите следующую команду:

D:\ msiexec /i "virtio-win-gt-x64.msi" /qn ADDLOCAL=ALL

После завершения установки гостевые агенты и драйверы передают информацию об использовании Менеджеру управления и позволяют получить доступ к USB-устройствам и другим функциям.

Драйверы и гостевой агент для Windows Server

Для установки драйверов и гостевого агента используйте образ virtio-win-1.1.1.2

Драйверы устанавливаются вручную из диспетчера устройств из папки z173 на диске с образом.

Гостевой агент устанавливается из папки z173\guest-agent.

Если на ВМ выбран чипсет(тип BIOS) Q35, то могут быть установлены не все драйверы. В такой ситуации смените чипсет(тип BIOS) на I440FX.

3.3.3. Значения для ADDLOCAL, позволяющие настроить процесс установки virtio-win из командной строки

При установке virtio-win-gt-x64.msi или virtio-win-gt-x32.msi из командной строки можно установить любой из драйверов или любое сочетание драйверов.

Кроме того, можно установить определенные агенты, но при этом для каждого агента нужно также установить соответствующие драйверы.

Параметр ADDLOCAL команды msiexec позволяет указать драйверы или агенты для установки. ADDLOCAL=ALL устанавливает все драйверы и агенты. Другие значения перечислены в следующих таблицах.

Таблица 5. Значения, которые можно указать для ADDLOCAL при установке драйверов

Значение для ADDLOCAL Имя драйвера Описание

FE_network_driver

virtio-net

Паравиртуализированный сетевой драйвер обеспечивает повышенную производительность по сравнению с такими эмулируемыми устройствами, как rtl.

FE_balloon_driver

virtio-balloon

Управляет объемом памяти, к которой фактически обращается виртуальная машина. Он улучшает процесс избыточного выделения памяти (облегчает работу планировщика выделения памяти гипервизору).

FE_pvpanic_driver

pvpanic

Драйвер устройства QEMU pvpanic.

FE_qemufwcfg_driver

qemufwcfg

Драйвер устройства QEMU FWCfg.

FE_qemupciserial_driver

qemupciserial

Драйвер последовательного PCI-устройства QEMU.

FE_spice_driver

Spice Driver

Паравиртуализированный драйвер дисплея, разгружает ЦП хоста и повышает производительность путем сужения полосы пропускания сети на большинстве рабочих нагрузок.

FE_vioinput_driver

vioinput

Драйвер ввода VirtIO.

FE_viorng_driver

viorng

Драйвер устройства VirtIO RNG.

FE_vioscsi_driver

vioscsi

Контроллер сквозного доступа VirtIO SCSI.

FE_vioserial_driver

vioserial

Драйвер устройства VirtIO Serial.

FE_viostor_driver

viostor

Драйвер VirtIO Block.

Таблица 6. Значения, которые можно указать для ADDLOCAL при установке агентов и соответствующих необходимых драйверов

Агент Описание Соответствующий драйвер (драйверы) Значение для ADDLOCAL

Spice Agent

Поддерживает несколько мониторов, отвечает за поддержку режима «клиент-мышь», снижает использование полосы пропускания, обеспечивает поддержку буфера обмена между клиентом и виртуальной машиной, повышает удобство работы и скорость отклика.

vioserial и драйвер Spice

FE_spice_Agent

FE_vioserial_driver

FE_spice_driver

Пример 1. Использование msiexec

Следующая команда устанавливает только контроллер сквозного доступа VirtIO SCSI, драйвер устройства VirtIO Serial и драйвер VirtIO Block:

D:\ msiexec /i "virtio-win-gt-x64.msi" /qn ADDLOCAL=`FE_vioscsi_driver,FE_vioserial_driver,FE_viostor_driver

Следующая команда устанавливает только Spice Agent и необходимые драйверы:

D:\ msiexec /i "virtio-win-gt-x64.msi" /qn ADDLOCAL = FE_spice_Agent,FE_vioserial_driver,FE_spice_driver

4. Дополнительная настройка виртуальных машин

4.1. Настройка операционных систем с помощью osinfo

zVirt хранит конфигурации операционных систем для виртуальных машин в файле /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties, который содержит значения по умолчанию, такие как os.other.devices.display.protocols.value = spice/qxl,vnc/vga,vnc/qxl.

Ситуаций, когда эти значения нужно редактировать, довольно мало:

  • Добавление ОС, которой нет в списке поддерживаемых гостевых ОС.

  • Добавление ключа продукта (например, os.windows_10x64.productKey.value =).

  • Настройка пути sysprep для виртуальной машины Windows (например, os.windows_10x64.sysprepPath.value = ${ENGINE_USR}/conf/sysprep/sysprep.w10x64).

Не редактируйте сам файл 00-defaults.properties. После обновления или восстановления Менеджера управления изменения будут перезаписаны.

Не изменяйте значения, переданные непосредственно из ОС или Менеджера управления, например, максимальный объем памяти.

Чтобы изменить настройки ОС, создайте переопределяющий файл в /etc/ovirt-engine/osinfo.conf.d/. Имя файла должно начинаться со значения больше 00, чтобы этот файл следовал за файлом /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties, и должно заканчиваться расширением .properties.

Например, файл 10-productkeys.properties переопределит файл 00-defaults.properties, заданный по умолчанию. Последний файл в списке имеет приоритет над более ранними файлами.

4.2. Настройка единого входа (Single Sign-On) для виртуальных машин

Настройка единого входа, именуемая также делегированием пароля, позволяет автоматически авторизоваться на виртуальной машине, используя учетные данные, введенные для авторизации на Пользовательском портале. Единый вход можно использовать как на виртуальных машинах Red Hat Enterprise Linux, так и на виртуальных машинах Windows.

Единый вход не поддерживается для виртуальных машин под управлением Red Hat Enterprise Linux 8.0.
Если включен единый вход на Пользовательский портал, то единый вход на виртуальные машины будет невозможен. Если включен единый вход на Пользовательский портал, то Пользовательскому порталу не требуется принимать пароль и поэтому невозможно делегировать пароль для входа на виртуальные машины.

4.2.1. Настройка единого входа для виртуальных машин Red Hat Enterprise Linux с использованием IPA

Чтобы настроить единый вход для виртуальных машин Red Hat Enterprise Linux с использованием графических сред рабочего стола GNOME и KDE и серверов IPA, установите пакет ovirt-guest-agent на виртуальную машину и пакеты, связанные с вашим оконным менеджером.

В следующей процедуре предполагается, что существует работающая конфигурация IPA и домен IPA уже подключен к Менеджеру управления. Кроме того, с помощью NTP обеспечьте синхронизацию часов Менеджера управления, виртуальной машины и системы, осуществляющей хостинг IPA.
Единый вход больше не рекомендуется для виртуальных машин под управлением Red Hat Enterprise Linux 7.0 или более ранних версий Единый вход не поддерживается для виртуальных машин под управлением Red Hat Enterprise Linux 8 или более поздних версий, а также для ОС Windows.

Настройка единого входа для виртуальных машин Red Hat Enterprise Linux.

Порядок действий:

  1. Авторизуйтесь на виртуальной машине с Red Hat Enterprise Linux.

  2. Включите репозиторий:

    • Для Red Hat Enterprise Linux 6:

      subscription-manager repos --enable=rhel-6-server-rhv-4-agent-rpms
    • Для Red Hat Enterprise Linux 7:

      subscription-manager repos --enable=rhel-7-server-rh-common-rpms
  3. Загрузите и установите пакеты гостевого агента, единого входа и IPA:

    yum install ovirt-guest-agent-common ovirt-guest-agent-pam-module ovirt-guest-agent-gdm-plugin ipa-client
  4. Выполните следующую команду и следуйте подсказкам, чтобы настроить ipa-client и подключить виртуальную машину к домену:

    ipa-client-install --permit --mkhomedir

    В средах, где используется обфускация DNS, команда должна быть следующей:

    ipa-client-install --domain=FQDN --server=FQDN
  5. Для Red Hat Enterprise Linux 7.2 и более поздних версий:

    authconfig --enablenis --update
    В Red Hat Enterprise Linux 7.2 есть новая версия сервиса System Security Services Daemon (SSSD), которая вводит конфигурацию, несовместимую с реализацией единого входа на гостевом агенте Менеджера управления. Эта команда делает так, чтобы единый вход работал.
  6. Получите подробную информацию о пользователе IPA:

  7. Запишите UID и GID пользователя IPA:

    ipa-user:*:936600010:936600001::/home/ipa-user:/bin/sh
  8. Создайте домашний каталог для пользователя IPA:

  9. Назначьте пользователя IPA владельцем каталога:

    chown 936600010:936600001 /home/ipa-user

Авторизуйтесь на Пользовательском портале, используя имя и пароль пользователя, для которого настроен единый вход, и подключитесь к консоли виртуальной машины. Авторизация произойдет автоматически.

4.2.2. Настройка единого входа на виртуальных машинах Windows

Чтобы настроить единый вход на виртуальных машинах Windows, на гостевой виртуальной машине должен быть установлен гостевой агент Windows. Этот агент включен в ISO-образ virtio-win. Если в вашем домене хранения образ virtio-win_version.iso недоступен, свяжитесь с системным администратором.

Порядок действий:

  1. Выберите виртуальную машину Windows. Убедитесь, что она включена.

  2. Нажмите > Сменить CD (Change CD).

  3. Из списка образов выберите virtio-win_version.iso.

  4. Нажмите OK.

  5. Нажмите Консоль (Console) и авторизуйтесь на виртуальной машине.

  6. Чтобы получить доступ к содержимому ISO-файла гостевых инструментов, на виртуальной машине найдите CD-привод и запустите virtio-win_version.iso. После установки инструментов вам будет предложено перезагрузить машину, чтобы изменения вступили в силу.

Авторизуйтесь на Пользовательском портале, используя имя и пароль пользователя, для которого настроен единый вход, и подключитесь к консоли виртуальной машины. Авторизация произойдет автоматически.

4.2.3. Отключение единого входа для виртуальных машин

Следующая процедура описывает, как отключить единый вход для виртуальной машины.

Порядок действий:

  1. Выберите виртуальную машину и нажмите Изменить (Edit).

  2. Откройте вкладку Консоль (Console).

  3. Установите флажок Отключить единый вход (Disable Single Sign On).

  4. Нажмите OK.

4.3. Настройка USB-устройств

Виртуальную машину, подключенную по протоколу SPICE, можно настроить на прямое подключение к USB-устройствам клиентской машины.

Автоматическое перенаправление USB-устройства будет выполнено только в том случае, если у виртуальной машины закладке Консоль (Console) окна Новая виртуальная машина (New Virtual Machine) или Изменить виртуальную машину (Edit Virtual Machine) отмечена флажком опция Включить USB (USB Enabled) и она перезагружена для применения этой настройки, виртуальная машина активна, находится в активном окне и запущена с Пользовательского портала. USB-перенаправление можно включать вручную при каждом подключении устройства, а можно настроить автоматическое перенаправление в окне Параметры консоли (Console Options) Портала администрирования.

Обратите внимание на различие между клиентской машиной и гостевой машиной. Клиент-это оборудование, используемое для доступа к гостевой машине. Гостевая машина — это виртуальная рабочая станция или виртуальный сервер, доступ к которому осуществляется через Пользовательский портал или Портал администрирования.

Если режим USB-перенаправления Включен (Enabled), то будет разрешено USB-перенаправление KVM/SPICE для виртуальных машин Linux и Windows. Виртуальные (гостевые) машины не требуют установленных гостевых агентов и драйверов для собственных USB-устройств. На клиентах Linux все пакеты, необходимые для USB-перенаправления, входят в пакет virt-viewer. На клиентах Windows нужно также установить пакет usbdk.

В случае ПК с 64-разрядной архитектурой для установки 64-разрядной версии драйвера USB необходимо использовать 64-разрядную версию браузера. USB-перенаправление не будет работать, если 32-разрядная версия установлена на компьютер с 64-разрядной архитектурой. Если с самого начала задан правильный тип USB, перенаправление USB может быть доступно как в 32-, так и в 64-разрядных браузерах.

4.3.1. Использование USB-устройств на клиенте Windows

Чтобы реализовать перенаправление USB-устройства на гостевую машину, на клиенте Windows должен быть установлен драйвер usbdk. Убедитесь, что версия usbdk соответствует архитектуре клиентской машины. Например, на 64-разрядные машины Windows нужно устанавливать 64-разрядную версию usbdk.

Автоматическое USB-перенаправление поддерживается, только если виртуальная машина открыта с Пользовательского портала.

Порядок действий (начинается на Портале администрирования):

  1. Когда драйвер usbdk установлен, нажмите .

  2. Выберите виртуальную машину, настроенную на использование протокола SPICE, и нажмите Изменить (Edit). Откроется окно Изменить виртуальную машину (Edit Virtual Machine).

  3. Откройте вкладку Консоль (Console).

  4. Установите флажок Включить USB (USB enabled) и нажмите OK.

  5. Нажмите .

  6. Установите флажок Включить USB Auto-Share (Enable USB Auto-Share) и нажмите OK.

  7. Запустите виртуальную машину с Пользовательского портала и нажмите Консоль (Console), чтобы подключиться к этой виртуальной машине.

  8. Подключите USB-устройство к клиентской машине, чтобы оно автоматически отображалось на гостевой машине.

4.3.2. Использование USB-устройств на клиенте Linux

Пакет usbredir включает USB-перенаправление с клиентов Linux на виртуальные машины. usbredir обычно зависит от пакета virt-viewer и автоматически устанавливается вместе с ним (уточните в документации производителя вашего дистрибутива).

USB-перенаправление поддерживается только если виртуальная машина открыта с Пользовательского портала.

Порядок действий (начинается на Портале администрирования):

  1. Нажмите .

  2. Выберите виртуальную машину, настроенную на использование протокола SPICE, и нажмите Изменить (Edit). Откроется окно Изменить виртуальную машину (Edit Virtual Machine).

  3. Откройте вкладку Консоль (Console).

  4. Установите флажок Включить USB (USB enabled) и нажмите OK.

  5. Нажмите .

  6. Установите флажок Включить USB Auto-Share (Enable USB Auto-Share) и нажмите OK.

  7. Запустите виртуальную машину с Пользовательского портала и нажмите Консоль (Console), чтобы подключиться к этой виртуальной машине.

  8. Подключите USB-устройство к клиентской машине, чтобы оно автоматически отображалось на гостевой машине.

4.4. Настройка нескольких мониторов

Для одной виртуальной машины можно настроить не более четырех дисплеев при подключении к виртуальной машине по протоколу SPICE.

  1. Нажмите и выберите виртуальную машину.

  2. Если виртуальная машина выключена, нажмите Изменить (Edit).

  3. Откройте вкладку Консоль (Console).

  4. Выберите количество дисплеев в выпадающем списке Мониторы (Monitors).

    Эта настройка управляет максимальным количеством дисплеев, которые можно включить для виртуальной машины. Во время работы виртуальной машины можно включать дополнительные дисплеи, пока не будет достигнуто их максимальное количество.
  5. Нажмите OK.

  6. Начните сеанс SPICE с виртуальной машиной.

  7. Откройте выпадающее меню Представление (View) в верхней части окна клиента SPICE.

  8. Откройте меню Дисплей (Display).

  9. Нажмите на имя дисплея, чтобы включить или выключить его.

    По умолчанию Дисплей 1 (Display 1) — единственный дисплей, включенный в начале сеанса SPICE с виртуальной машиной. Если никакие другие дисплеи не включены, то выключение этого дисплея завершит сеанс.

4.5. Настройка параметров консоли

4.5.1. Параметры консоли

Протоколы подключения — это базовая технология предоставления графических консолей виртуальным машинам, которая позволяет пользователям работать с виртуальными машинами так же, как бы они работали с физическими машинами. Сейчас в zVirt поддерживаются следующие протоколы подключения:

SPICE

Simple Protocol for Independent Computing Environments (SPICE) рекомендуется как для виртуальных машин Linux, так и Windows. Чтобы открыть консоль виртуальной машины с помощью SPICE, используйте инструмент удаленного просмотра — Remote Viewer.

VNC

Virtual Network Computing (VNC) можно использовать для открытия консолей как виртуальных машин Linux, так и Windows. Чтобы открыть консоль виртуальной машины с помощью VNC, используйте инструмент удаленного просмотра Remote Viewer или VNC-клиент.

RDP

Remote Desktop Protocol (RDP) можно использовать только для открытия консолей виртуальных машин Windows и только при доступе к виртуальным машинам с машины Windows с установленным инструментом удаленного просмотра (Remote Desktop). Прежде чем подключиться к виртуальной машине Windows по RDP, настройте удаленный общий доступ на виртуальной машине и разрешите в брандмауэре подключения к удаленному рабочему столу.

4.5.2. Доступ к параметрам консоли

На Портале администрирования можно настроить несколько вариантов открытия графических консолей виртуальных машин.

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите .

Протоколы подключения и тип видео можно настроить на вкладке Консоль (Console) окна Изменить виртуальную машину (Edit Virtual Machine) на Портале администрирования. Можно настроить дополнительные параметры, характерные для каждого из протоколов подключения (например, раскладку клавиатуры при использовании протокола подключения VNC). Для получения дополнительной информации см. раздел Описание настроек консоли виртуальной машины.

4.5.3. Параметры консоли SPICE

Когда выбран протокол подключения SPICE, в окне Параметры консоли (Console Options) доступны следующие параметры.

Опции SPICE
  • Изменить комбинацию клавиш Ctrl+Alt+Del на ctrl+alt+end (Map ctrl+alt+del shortcut to ctrl+alt+end): Установите этот флажок, чтобы преобразовать комбинацию Ctrl+Alt+Del в Ctrl+Alt+End внутри виртуальной машины.

  • Включить USB Auto-Share (Enable USB Auto-Share): Установите этот флажок для автоматического перенаправления USB-устройств на виртуальную машину. Если этот флажок не установлен, USB-устройства будут подключаться к клиентской машине, а не к гостевой виртуальной машине. Чтобы использовать USB-устройство на гостевой машине, включите его вручную в меню клиента SPICE.

  • Открыть в полноэкранном режиме (Open in Full Screen): Установите этот флажок, чтобы при подключении к виртуальной машине консоль виртуальной машины автоматически открывалась в полноэкранном режиме. Для включения/выключения полноэкранного режима нажмите Shift+F11.

  • Включить SPICE-прокси (Enable SPICE Proxy): Установите этот флажок, чтобы включить SPICE-прокси.

4.5.4. Параметры консоли VNC

Когда выбран протокол подключения VNC, в окне Параметры консоли (Console Options) доступны следующие параметры.

Вызов консоли (Console Invocation)
  • Нативный клиент (Native Client): При подключении к консоли виртуальной машины, диалоговое окно загрузки файла предоставляет файл, который открывает консоль виртуальной машины с помощью инструмента удаленного просмотра Remote Viewer.

  • noVNC: При подключении к консоли виртуальной машины, открывается вкладка браузера, выполняющая роль консоли.

Опции VNC
  • Изменить комбинацию клавиш Ctrl+Alt+Del на ctrl+alt+end (Map ctrl+alt+del shortcut to ctrl+alt+end): Установите этот флажок, чтобы преобразовать комбинацию Ctrl+Alt+Del в Ctrl+Alt+End внутри виртуальной машины.

4.5.5. Параметры консоли RDP

Когда выбран Удалённый рабочий стол (Remote Desktop) в окне Параметры консоли (Console Options), доступны следующие параметры.

Вызов консоли (Console Invocation)
  • Автоматически (Auto): Менеджер управления автоматически выбирает метод вызова консоли.

  • Нативный клиент (Native client): При подключении к консоли виртуальной машины, диалоговое окно загрузки файла предоставляет файл, который открывает консоль виртуальной машины с помощью инструмента удаленного просмотра Remote Viewer.

Опции RDP
  • Использовать локальные диски (Use Local Drives): Установите этот флажок, чтобы гостевая виртуальная машина смогла обращаться к дискам на клиентской машине.

4.5.6. Параметры инструмента удаленного просмотра (Remote Viewer)

Параметры инструмента удаленного просмотра Remote Viewer

Если указан параметр вызова консоли Нативный клиент (Native client), то для подключения к виртуальной машине используется инструмент удаленного просмотра Remote Viewer. Окно Remote Viewer предлагает ряд параметров для взаимодействия с виртуальной машиной, к которой подключен этот инструмент.

Таблица 7. Параметры инструмента удаленного просмотра Remote Viewer

Параметр Описание

Файл (File)

  • Снимок экрана (Screenshot): Делает экранный снимок активного окна и сохраняет его в указанном месте.

  • Выбор USB-устройства (USB device selection): Если на виртуальной машине включено USB-перенаправление, то доступ к USB-устройству, подключенному к клиентской машине, можно получить из этого меню.

  • Выход (Quit): Закрывает консоль. Клавишная комбинация для этого параметра: Shift+Ctrl+Q.

Представление (View)

  • Полный экран (Full screen): Включает и выключает полноэкранный режим. При включении полноэкранного режима виртуальная машина разворачивается на весь экран. При его выключении виртуальная машина отображается в виде окна. Клавишная комбинация для включения/выключения полноэкранного режима: SHIFT+F11.

  • Изменение масштаба (Zoom): Изменение масштаба окна консоли. Ctrl++ увеличивает масштаб, Ctrl+- уменьшает, а Ctrl+0 возвращает экран к изначальному размеру.

  • Изменять размер автоматически (Automatically resize): Выберите этот параметр, чтобы разрешение гостевой системы автоматически подстраивалось под размер окна консоли.

  • Дисплеи (Displays): Позволяет пользователям включать и выключать дисплеи для гостевой виртуальной машины.

Отправить клавишную комбинацию (Send key)

  • Ctrl + Alt + Del: На виртуальной машине Red Hat Enterprise Linux она отображает диалоговое окно с параметрами приостановки, выключения или перезапуска виртуальной машины. На виртуальной машине Windows она отображает диспетчер задач или диалоговое окно Безопасность Windows (Windows Security).

  • Ctrl + Alt + Backspace: На виртуальной машине Red Hat Enterprise Linux она перезапускает X-сервер. На виртуальной машине Windows она не делает ничего.

  • Ctrl + Alt + F1

  • Ctrl + Alt + F2

  • Ctrl + Alt + F3

  • Ctrl + Alt + F4

  • Ctrl + Alt + F5

  • Ctrl + Alt + F6

  • Ctrl + Alt + F7

  • Ctrl + Alt + F8

  • Ctrl + Alt + F9

  • Ctrl + Alt + F10

  • Ctrl + Alt + F11

  • Ctrl + Alt + F12

  • Printscreen: Передает нажатие на клавиатуре Клиента Printscreen виртуальной машине.

Справка (Help)

Пункт О программе (About) отображает сведения об используемой версии инструмента просмотра виртуальных машин Virtual Machine Viewer.

Высвободить курсор из виртуальной машины (Release Cursor from Virtual Machine)

SHIFT+F12

Клавишные комбинации инструмента удаленного просмотра Remote Viewer

Клавишные комбинации для виртуальной машины доступны как в полноэкранном, так и в оконном режиме. Чтобы в полноэкранном режиме отобразить меню, в котором есть кнопка для клавишных комбинаций, переместите указатель мыши в середину верхней части экрана. В оконном режиме клавишные комбинации доступны через меню Отправить клавишную комбинацию (Send key) в строке заголовка окна виртуальной машины.

Если мышь используется внутри виртуальной машины и виртуальная машина не находится в полноэкранном режиме, то мышь может быть заблокирована окном виртуальной машиной, так как Vdagent не запущен на клиентском компьютере. Чтобы разблокировать мышь, нажмите Shift+F12.

4.6. Настройка сервиса watchdog

4.6.1. Добавление карты сервиса watchdog в виртуальную машину

В виртуальную машину можно добавить карту сервиса watchdog, чтобы отслеживать работоспособность операционной системы.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Высокая доступность (High Availability).

  4. Выберите используемую модель сервиса watchdog в выпадающем списке Модель (Watchdog Model).

  5. Выберите действие в выпадающем списке Действие (Watchdog Action). Это действие, которое выполняет виртуальная машина при срабатывании сервиса watchdog.

  6. Нажмите OK.

4.6.2. Установка сервиса watchdog

Чтобы активировать карту сервиса watchdog, подключенную к виртуальной машине, установите пакет watchdog на этой виртуальной машине и запустите службу watchdog.

Порядок действий:

  1. Авторизуйтесь на виртуальной машине, к которой подключена карта сервиса watchdog.

  2. Установите пакет watchdog и зависимости:

  3. Измените файл /etc/watchdog.conf и раскомментируйте следующую строку:

    watchdog-device = /dev/watchdog
  4. Сохраните изменения.

  5. Запустите службу watchdog и убедитесь, что она запускается при загрузке:

    • Red Hat Enterprise Linux 6:

      service watchdog start
      chkconfig watchdog on
    • Red Hat Enterprise Linux 7:

      systemctl start watchdog.service
      systemctl enable watchdog.service

4.6.3. Подтверждение функциональности сервиса watchdog

Убедитесь, что карта сервиса watchdog подключена к виртуальной машине и служба watchdog активна.

Эта процедура предназначена только для проверки функциональности сервисов watchdog и не должна выполняться на продуктивных машинах.

Порядок действий:

  1. Авторизуйтесь на виртуальной машине, к которой подключена карта сервиса watchdog.

  2. Убедитесь, что карта сервиса watchdog опознана виртуальной машиной:

  3. Выполните одну из следующих команд, чтобы убедиться в активности сервиса watchdog:

    • Инициируйте панику ядра:

      echo c > /proc/sysrq-trigger
    • Остановите службу watchdog:

Таймер сервиса watchdog больше невозможно сбросить, поэтому счетчик сервиса watchdog вскоре досчитает до нуля. Когда это произойдет, будет выполнено действие, выбранное в выпадающем меню Действие (Watchdog Action) для данной виртуальной машины.

4.6.4. Параметры сервиса watchdog в файле watchdog.conf

Ниже приводится список параметров для настройки службы watchdog, включенных в файл /etc/watchdog.conf. Чтобы настроить параметр, раскомментируйте его, сохраните изменения и перезапустите службу watchdog.

Более подробно о параметрах настройки службы watchdog и использовании команды watchdog смотрите в справочной системе man watchdog.

Таблица 8. Переменные в файле watchdog.conf

Имя переменной Значение по умолчанию Примечания

ping

IP-адрес, на который сторожевой сервис пытается отправить icmp-запрос, чтобы проверить доступность этого адреса. Можно указать несколько IP-адресов, добавив строки ping.

interface

Сетевой интерфейс, за которым будет следить сторожевой сервис и на котором он будет проверять наличие сетевого трафика. Можно указать несколько сетевых интерфейсов, добавив строки interface.

file

/var/log/messages

Файл в локальной системе, изменения в котором будет отслеживать сторожевой сервис. Можно указать несколько файлов, добавив строки file.

change

1407

Количество интервалов сервиса watchdog, после которого он проверяет наличие изменений в файлах. Строка change должна указываться сразу после каждой строки file и применяется к строке file, находящейся непосредственно над ней.

max-load-1

24

Максимальная средняя нагрузка, которую виртуальная машина может выдержать в течение 1 минуты. При превышении этого среднего значения срабатывает сторожевой сервис. Значение 0 выключает эту функцию.

max-load-5

18

Максимальная средняя нагрузка, которую виртуальная машина может выдержать в течение 5 минут. При превышении этого среднего значения срабатывает сторожевой сервис. Значение 0 выключает эту функцию. По умолчанию значение этой переменной равно примерно 3/4 значения max-load-1.

max-load-15

12

Максимальная средняя нагрузка, которую виртуальная машина может выдержать в течение 15 минут. При превышении этого среднего значения срабатывает сторожевой сервис. Значение 0 выключает эту функцию. По умолчанию значение этой переменной равно примерно 1/2 значения max-load-1.

min-memory

1

Минимальный объем виртуальной памяти, который должен оставаться свободным на виртуальной машине. Измеряется в страницах. Значение 0 выключает эту функцию.

repair-binary

/usr/sbin/repair

Путь и имя двоичного файла в локальной системе, который будет запускаться при срабатывании сервиса watchdog. Если указанный файл устраняет проблемы, не давая сторожевому сервису сбросить счетчик, то действие сервиса watchdog не активируется.

test-binary

Путь и имя двоичного файла в локальной системе, который сторожевой сервис будет пытаться запустить в течение каждого интервала. Этот параметр позволяет указать файл для запуска пользовательских тестов.

test-timeout

Лимит времени (в секундах), в течение которого могут выполняться пользовательские тесты. Значение 0 позволяет выполнять пользовательские тесты без ограничений по времени.

temperature-device

Путь и имя устройства для проверки температуры машины, на которой запущена служба watchdog.

max-temperature

120

Максимальная допустимая температура машины, на которой запущена службы watchdog. При достижении этой температуры машина будет остановлена. Преобразование единиц измерения не учитывается, поэтому указывайте значение, соответствующее используемой карте сервиса watchdog.

admin

root

Адрес эл. почты, на который отправляются уведомления.

interval

10

Интервал (в секундах) между обновлениями, отправляемыми в устройство сервиса watchdog. Устройство сервиса watchdog ожидает, что обновления будут поступать как минимум каждую минуту, и если в течение минуты обновлений нет, то срабатывает сторожевой сервис. Этот одноминутный интервал жестко задан в драйверах сервиса watchdog и не настраивается.

logtick

1

Когда для службы watchdog включен режим детального журналирования, служба watchdog периодически записывает сообщения журнала в локальную систему. Значение logtick обозначает количество интервалов сервиса watchdog, после которого пишется сообщение.

realtime

yes

Указывает, заблокирован ли сторожевой сервис в памяти. Значение yes блокирует сторожевой сервис в памяти, предотвращая его выгрузку из нее , а no разрешает такую выгрузку. Если сторожевой сервис выгружается из памяти и не возвращается обратно до обнуления счетчика, то срабатывает сторожевой сервис.

priority

1

Приоритет в графике задач, когда параметр realtime установлен в значение yes.

pidfile

/var/run/syslogd.pid

Путь и имя PID-файла, за которым следит сторожевой сервис, чтобы определить, по-прежнему ли активен соответствующий процесс. Если соответствующий процесс не активен, то срабатывает сторожевой сервис.

4.7. Настройка виртуальных узлов NUMA

На Портале администрирования можно настроить виртуальные узлы NUMA на виртуальной машине и закрепить их за физическими узлами NUMA на одном или нескольких хостах. Согласно политике хоста по умолчанию, виртуальные машины планируются и запускаются на любых доступных ресурсах хоста. В результате ресурсы, обеспечивающие работу большой виртуальной машины, которая не может поместиться в один сокет хоста, могут быть распределены по нескольким узлам NUMA. Со временем эти ресурсы могут перемещаться, ухудшая производительность и делая ее непредсказуемой. Чтобы избежать этого и повысить производительность, настройте и закрепите виртуальные узлы NUMA.

Для настройки виртуальных узлов NUMA нужен хост с включенным NUMA. Чтобы убедиться, что NUMA на хосте включен, авторизуйтесь на хосте и запустите numactl --hardware. В выводе этой команды должны присутствовать минимум два узла NUMA. Можно также просмотреть топологию NUMA хоста на Портале администрирования, выбрав хост на вкладке Хосты (Hosts) () перейдя в его детальное описание и, нажав , кликнуть по Поддержка NUMA (NUMA Support).

numa description

Эта кнопка доступна, только если выбранный хост имеет минимум два узла NUMA.

Если задано Закрепление NUMA (NUMA Pinning), то режимом миграции по умолчанию будет Разрешить только ручную миграцию (Allow manual migration only).

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Нажмите Показать расширенные настройки (Show Advanced Options).

  4. Откройте вкладку Хост (Host).

  5. Под Запустить на: (Запустить на:) нажмите кнопку-переключатель Указанном хосте (Specific Host(s)) и выберите хосты из списка. Выбранные хосты должны иметь минимум два узла NUMA.

  6. Нажмите Привязка NUMA (NUMA Pinning).

  7. В окне Топология NUMA (NUMA Topology) выберите и перетащите необходимые виртуальные узлы NUMA из блока справа в блок узлов NUMA хоста слева, затем нажмите OK.

  8. На каждом узле NUMA в выпадающем списке Режим тонкой настройки (Tune Mode) выберите Строгий (Strict), Предпочитаемый (Preferred) или Интерактивный (Interleave). Если выбран Предпочитаемый (Preferred) режим, то Количество хостов NUMA (NUMA Node Count) должно быть установлено в значение 1.

  9. Можно также задать политику закрепления NUMA автоматически, выбрав в выпадающем списке Рекомендации по автоматическому закреплению (Auto Pinning Policy):

    • Отсутствует (None) — не вносит никаких изменений в виртуальную машину.

    • Изменить размер и прикрепить (Resize and Pin) — устанавливает максимальную топологию ЦП и генерирует конфигурации закрепления ЦП и NUMA.

  10. Нажмите OK.

Если не закрепить виртуальный узел NUMA на узле NUMA хоста, то система по умолчанию использует узел NUMA, который содержит ввод-вывод с отображением памяти (MMIO) устройства хоста, при условии, что имеется одно или несколько устройств хоста и все эти устройства из одного узла NUMA.

4.8. Настройка фоновых виртуальных машин (Headless Virtual Machines)

Можно настроить фоновую виртуальную машину, когда нет необходимости обращаться к машине через графическую консоль. Такая фоновая машина будет работать без видео- и графических устройств. Это может быть полезно в ситуациях, когда ресурсы хоста ограничены или нужно соблюсти требования к использованию виртуальных машин (например, виртуальных машин реального времени).

Управлять фоновыми виртуальными машинами можно через последовательную консоль, SSH или любую другую службу доступа из командной строки. Чтобы применить фоновый режим, откройте вкладку Консоль(Console) при создании или изменении виртуальных машин и пулов машин, а также при изменении шаблонов. Эта возможность также доступна при создании или изменении типов экземпляров.

При создании новой фоновой виртуальной машины можно использовать окно Однократный запуск (Run Once), чтобы обратиться к виртуальной машине через графическую консоль, но только для однократного запуска. Для получения дополнительной информации см. раздел Описание настроек в окне «Запустить ВМ (Run Virtual Machine(s))».

Предварительные условия:

  • При изменении существующей виртуальной машины и отсутствии установленного гостевого агента zVirt запишите IP-адрес машины, прежде чем выбирать Режим Headless (Headless Mode).

  • Перед запуском виртуальной машины в фоновом режиме конфигурацию GRUB для этой машины нужно установить в консольный режим, иначе процесс загрузки гостевой операционной системы зависнет. Чтобы установить консольный режим, закомментируйте флаг splashimage в файле конфигурации меню GRUB:

    #splashimage=(hd0,0)/grub/splash.xpm.gz serial --unit=0 --speed=9600 --parity=no --stop=1 terminal --timeout=2 serial
При выборе Режим Headless (Headless Mode) перезапустите виртуальную машину, если она уже работает.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Консоль (Console).

  4. Выберите Режим Headless (Headless Mode). Все остальные поля в разделе Графический адаптер (Graphical Console) станут неактивны.

  5. При желании выберите Консольный порт VirtIO-serial (Enable VirtIO serial console), чтобы включить взаимодействие с виртуальной машиной через последовательную консоль. Рекомендуем это сделать.

  6. Если виртуальная машина работает, перезагрузите ее. См. раздел Перезагрузка или сброс виртуальной машины.

4.9. Настройка высокопроизводительных виртуальных машин, шаблонов и пулов

Виртуальную машину можно настроить на обеспечение высокой производительности, чтобы ее показатели производительности были максимально близки к показателям физической машины. При выборе оптимизации для высокой производительности виртуальная машина конфигурируется с набором автоматических и рекомендуемых ручных настроек, обеспечивающих максимальную эффективность. Параметр «высокая производительность» доступен только на Портале администрирования: выберите Высокая производительность (High Performance) в выпадающем списке Профиль нагрузки (Optimized for) в закладке «Высокая доступность» окне Изменить виртуальную машину (Edit) или Создать (New) виртуальную машину, шаблон или пул. Эта опция недоступна на Пользовательском портале.

Виртуальные машины

Если изменить режим оптимизации работающей виртуальной машины на «высокую производительность», то некоторые изменения конфигурации потребуют перезапуска виртуальной машины. Чтобы изменить режим оптимизации новой или существующей виртуальной машины на «высокую производительность», может потребоваться сначала вручную внести изменения в кластер и конфигурацию закрепленного хоста.

Высокопроизводительная виртуальная машина имеет определенные ограничения, поскольку повышение производительности приводит к уменьшению гибкости:

  • Если для потоков ЦП, потоков ввода/вывода, потоков эмулятора или узлов NUMA установлено закрепление в соответствии с рекомендуемыми настройками, то высокопроизводительной виртуальной машине может быть назначено только подмножество хостов кластера.

  • Многие устройства выключаются автоматически, из-за чего использовать виртуальную машину может быть не так удобно.

Шаблоны и пулы

Высокопроизводительные шаблоны и пулы создаются и изменяются так же, как и виртуальные машины. Если для создания новых виртуальных машин используется высокопроизводительный шаблон или пул, то эти виртуальные машины наследуют это свойство и его конфигурации. Однако некоторые настройки не наследуются и должны быть установлены вручную:

  • Закрепление ЦП (CPU pinning).

  • Виртуальный узел NUMA и топология закрепления NUMA.

  • Топология закрепления потоков ввода/вывода и эмулятора.

  • Сквозной доступ ЦП хоста (Pass-through Host CPU).

4.9.1. Создание высокопроизводительной виртуальной машины, шаблона или пула

Чтобы создать высокопроизводительную виртуальную машину, шаблон или пул выполните следующие действия.

Порядок действий:

  1. Нажмите .

  2. Нажмите Создать (New). Откроется окно Новая виртуальная машина (New Virtual Machine).

  3. На вкладке Общее (General) выберите Высокая производительность (High Performance) в выпадающем меню Профиль нагрузки (Optimized for).

    При выборе этого параметра автоматически выполняются определенные изменения конфигурации этой виртуальной машины, которые можно просмотреть, открывая разные вкладки. Их можно как вернуть в изначальные значения, так и переопределить (подробности см. в разделе Автоматические настройки высокопроизводительной конфигурации). При изменении настройки ее последнее значение сохраняется.

  4. Нажмите OK.

    Если ручные настройки не заданы, отобразится экран Высокопроизводительные параметры виртуальной машины/пула (High Performance Virtual Machine/Pool Settings), описывающий рекомендуемые ручные настройки.

    Если некоторые ручные настройки заданы, на экране Высокопроизводительные параметры виртуальной машины/пула (High Performance Virtual Machine/Pool Settings) отобразятся неустановленные настройки.

    Если все ручные настройки заданы, экран Высокопроизводительные параметры виртуальной машины/пула (High Performance Virtual Machine/Pool Settings) не появится.

  5. Если появляется экран Высокопроизводительные параметры виртуальной машины/пула (High Performance Virtual Machine/Pool Settings), нажмите Отменить (Cancel), чтобы вернуться в окно Создать (New) или Изменить (Edit) и выполнить ручную настройку. Подробности см. в разделе Конфигурирование рекомендуемых ручных настроек.
    Либо нажмите OK, чтобы проигнорировать рекомендации. В результате может снизиться производительность.

  6. Нажмите OK.

    Тип оптимизации можно просмотреть на вкладке Общие (General) подробного представления виртуальной машины, пула или шаблона.

Определенные конфигурации могут переопределять настройки высокой производительности. Например, если выбрать тип экземпляра для виртуальной машины до выбора Высокой производительности (High Performance) в выпадающем меню Профиль нагрузки (Optimized for) и выполнения ручной настройки, то настройка типа экземпляра не повлияет на высокопроизводительную конфигурацию. Однако это не относится к случаям, когда тип экземпляра выбирается после выбора высокопроизводительной конфигурации, проверьте окончательную конфигурацию на разных вкладках, чтобы убедиться, что высокопроизводительные конфигурации не переопределены типом экземпляра.

Приоритет обычно имеет конфигурация, сохраненная последней.

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

Автоматические настройки сведены в следующую таблицу. В столбце Включено (Д/Н) (Enabled (Y/N)) отображаются включенные или выключенные конфигурации. В столбце Применяется к (Applies to) отображаются соответствующие ресурсы:

  • ВМ — виртуальная машина;

  • Ш — шаблон;

  • П — пул;

  • К — кластер;

Таблица 9. Автоматические настройки высокопроизводительной конфигурации

Параметр Включено (Д/Н) (Enabled (Y/N)) Применяется к (Applies to)

Фоновый режим (Headless Mode) (вкладка Консоль (Console))

Д

ВМ, Ш, П

Включить USB (USB Enabled) (вкладка Консоль (Console))

Н

ВМ, Ш, П

Поддержка смарт-карт (Smartcard Enabled) (вкладка Консоль (Console))

Н

ВМ, Ш, П

Включить звуковую карту (Soundcard Enabled) (вкладка Консоль (Console))

Н

ВМ, Ш, П

Консольный порт VirtIO-serial (Enable VirtIO serial console) (вкладка Консоль (Console))

Д

ВМ, Ш, П

Разрешить только ручную миграцию (Allow manual migration only) (вкладка Хост (Host))

Д

ВМ, Ш, П

Сквозной доступ ЦП хоста (Pass-Through Host CPU) (вкладка Хост (Host))

Д

ВМ, Ш, П

Высокая доступность (Highly Available) (вкладка Высокая доступность (High Availability))

Высокая доступность не включается автоматически, если выбрать её вручную, то высокая доступность должна быть включена только для закрепленных хостов.

Н

ВМ, Ш, П

Без использования watchdog (No-Watchdog) (вкладка Высокая доступность (High Availability))

Н

ВМ, Ш, П

Включить Balloning (Memory Balloon Device) (вкладка Выделение ресурсов (Resource Allocation))

Н

ВМ, Ш, П

Потоки ввода/вывода (I/O Threads Enabled) (вкладка Выделение ресурсов (Resource Allocation), Количество потоков ввода/вывода = 1)

Д

ВМ, Ш, П

Устройство Паравиртуализированный генератор случайных чисел PCI (Paravirtualized Random Number Generator PCI) (virtio-rng) (вкладка Генератор случайных чисел (Random Generator))

Д

ВМ, Ш, П

Топология закрепления потоков ввода/вывода и эмулятора

Д

ВМ, Ш

Кэш ЦП третьего уровня

Д

ВМ, Ш, П

Закрепление привязки ввода/вывода и эмуляции потоков (автоматические настройки)

Для закрепления ввода/вывода и эмуляции потоков конфигурации нужно, чтобы потоки ввода-вывода, узлы NUMA и закрепление NUMA были включены и настроены на виртуальной машине, в противном случае в журнале engine отобразится предупреждение.

Автоматическая топология привязки
  • Закрепляются первые два ЦП каждого узла NUMA.

  • Если все ЦП находятся на одном узле NUMA хоста:

    • Первые два виртуальных ЦП автоматически резервируются/закрепляются.

    • Остальные виртуальные ЦП доступны для ручного закрепления виртуальных ЦП.

  • Если виртуальная машина занимает более одного узла NUMA:

    • Первые два ЦП узла NUMA с наибольшим количеством закреплений зарезервированы/закреплены.

    • Остальные закрепленные узлы NUMA предназначены только для закрепления виртуальных ЦП.

Пулы не поддерживают закрепление потоков ввода/вывода и эмулятора.

Если ЦП хоста закреплен как за виртуальным ЦП, так и за потоками ввода-вывода и эмулятора, то в журнале появится предупреждение, и система предложит рассмотреть возможность изменения топологии закрепления ЦП, чтобы избежать этой ситуации.
Значки «Высокая производительность»

На экране следующими значками обозначаются состояния высокопроизводительной виртуальной машины.

Таблица 10. Значки «Высокая производительность»

Значок Описание

Высокопроизводительная виртуальная машина

Высокопроизводительная виртуальная машина с конфигурацией «Следующий запуск (Next Run)»

Высокопроизводительная виртуальная машина без сохранения состояния

Высокопроизводительная виртуальная машина без сохранения состояния с конфигурацией «Следующий запуск (Next Run)»

Виртуальная машина в высокопроизводительном пуле

Виртуальная машина в высокопроизводительном пуле c конфигурацией «Следующий запуск (Next Run)»

4.9.2. Конфигурирование рекомендуемых ручных настроек

Рекомендуемые ручные настройки можно задать в окнах Новая виртуальная машина (New) или Изменить виртуальную машину (Edit).

Если рекомендуемая настройка не задана, то на экране Высокопроизводительные параметры виртуальной машины/пула (High Performance Virtual Machine/Pool Settings) при сохранении ресурса отображается рекомендуемая настройка.

К рекомендуемыми ручными настройкам относятся:

  • Закрепление ЦП.

  • Настройка политики закрепления NUMA.

  • Конфигурирование больших страниц.

  • Выключение KSM.

Ручные настройки высокопроизводительной конфигурации

В таблице ниже приведены все рекомендуемые ручные настройки. В столбце Включено (да/нет) показано, какие параметры должны быть включены, а какие — выключены. В столбце Применяется к отображаются соответствующие ресурсы:

  • ВМ — виртуальная машина;

  • Ш — шаблон;

  • П — пул;

  • К — кластер;

Таблица 11. Ручные настройки высокопроизводительной конфигурации

Параметр Включено (да/нет) Применяется к

Количество хостов NUMA (NUMA Node Count) (вкладка Хост (Host))

Д

ВМ

Режим тонкой настройки (Tune Mode) (экран после нажатия Закрепление NUMA (NUMA Pinning))

Д

ВМ

Закрепление NUMA (NUMA Pinning) (вкладка Хост (Host))

Д

ВМ

Рекомендации по автоматическому закреплению (Auto Pinning Policy) (вкладка Хост (Host))

Д

ВМ

Топология привязки ЦП (CPU Pinning topology) (вкладка Выделение ресурсов (Resource Allocation))

Д

ВМ, П

Большие страницы (hugepages) (вкладка Пользовательские свойства (Custom Properties))

Д

ВМ, Ш, П

KSM (вкладка Оптимизация (Optimization tab))

Н

К

Закрепление ЦП

Чтобы закрепить виртуальные ЦП за физическим ЦП конкретного хоста:

  1. На вкладке Хост (Host) в блоке Запустить на: (Start Running On:) нажмите кнопку-переключатель Указанном хосте (Specific Host(s)).

  2. На вкладке Выделение ресурсов (Resource Allocation) в меню Политика Закрепления ЦПУ выберите подходящую политику.

    • При использовании политики закрепления Manual также введите конфигурацию в поле Топология привязки ЦП (CPU Pinning Topology) и подтвердите, что такая конфигурация соответствует конфигурации закрепленного хоста.

      Если в поле Топология привязки ЦП (CPU Pinning Topology) задана конфигурация, то режим миграции ВМ (вкладка Хост) автоматически меняется на Разрешить только ручную миграцию.

      Это поле заполняется автоматически, а топология ЦП обновляется, когда активируется автоматическое закрепление NUMA.

  3. Проверьте, что конфигурация виртуальной машины совместима с конфигурацией хоста:

    • Количество сокетов виртуальной машины не должно превышать количество сокетов хоста.

    • Количество ядер виртуальной машины на один виртуальный сокет не должно превышать количество ядер хоста.

    • Процессы, сильно загружающие ЦП, лучше всего выполняются, когда на хосте и виртуальной машине ожидается одинаковая загрузка кэша. Чтобы производительность была максимальной, количество потоков на ядро у виртуальной машины не должно превышать количество потоков у хоста.

К закреплению ЦП предъявляются следующие требования:

  • Если на хосте включен NUMA, то необходимо учитывать настройки NUMA хоста (память и ЦП), поскольку виртуальная машина должна соответствовать конфигурации NUMA хоста.

  • Необходимо учитывать Топологию закрепления потоков ввода-вывода.

  • Закрепление ЦП можно настроить только для виртуальных машин и пулов, но не для шаблонов. Поэтому закрепление ЦП необходимо настроить вручную при создании высокопроизводительной виртуальной машины или пула, даже если они основаны на высокопроизводительном шаблоне.

Настройка политики закрепления NUMA

Чтобы настроить политику закрепления NUMA, нужен закрепленный хост с включенным NUMA и как минимум двумя узлами NUMA. Можно настроить топологию NUMA вручную или воспользоваться Рекомендации по автоматическому закреплению (Auto Pinning Policy) для автоматической настройки топологии вкладки Хост (Host) окна Создать (New)/Изменить (Edit).

Ручная настройка политики закрепления NUMA
  1. Нажмите Привязка NUMA (NUMA Pinning).

  2. В окне Топология NUMA (NUMA Topology) выберите и перетащите необходимые виртуальные узлы из NUMA из блока справа в блок физических узлов NUMA хоста слева.

  3. Выберите режим Строгий (Strict), Предпочтительный (Preferred) или С чередованием (Interleave) из выпадающего списка Режим тонкой настройки (Tune Mode) для каждого узла NUMA. Если выбран режим Предпочтительный (Preferred), то Количество узлов NUMA (NUMA Node Count) должно быть установлено в значение 1.

  4. Нажмите OK.

Автоматическая настройка политики закрепления NUMA
  1. На вкладке Хост (Host) и блоке Запустить на: (Start Running On:) нажмите кнопку-переключатель Указанном хосте (Specific Host(s)) и выберите хост(ы) из списка. У заданного(ых) хоста(ов) должно быть не менее двух узлов NUMA.

  2. В блоке Настройки NUMA (Configure NUMA) выберите Рекомендации по автоматическому закреплению (Auto Pinning Policy) из выпадающего списка:

    • Не назначено (None) — не вносит никаких изменений в виртуальную машину.

    • Изменить размер и прикрепить (Resize and Pin) — устанавливает максимальную топологию ЦП и генерирует конфигурации закрепления ЦП и NUMA.

  3. Нажмите OK.

Менеджер управления рассчитывает Топологию закрепления ЦП, обновляет поля топологии ЦП (Общее количество виртуальных ЦП, ядер на виртуальный сокет, потоков на ядро) и вводит строку конфигурации топологии в поле Топология привязки ЦП (CPU Pinning Topology) вкладки Выделение ресурсов (Resource Allocation) виртуальной машины.

Необходимо учитывать количество указанных виртуальных узлов NUMA и политику закрепления NUMA:

  • Настройки NUMA хоста (память и ЦП).

  • Узел NUMA, в котором указаны устройства хоста.

  • Топология закрепления ЦП.

  • Топологию закрепления потоков ввода-вывода.

  • Размеры больших страниц.

  • Закрепление NUMA можно настроить только для виртуальных машин, но не для пулов и шаблонов. Закрепление NUMA необходимо настроить вручную при создании высокопроизводительной виртуальной машины из шаблона.

Конфигурирование больших страниц (Configuring Huge Pages)

При запуске ВМ с настроенным свойством hugepages на хосте резервируется необходимое количество страниц оперативной памяти. Данная настройка рекомендована при наличии требований к производительности ОЗУ ВМ.

Количество свободных и занятых страниц можно найти на вкладке Общее подробного представления хоста в свойстве Доступно Huge Pages (размер: количество).
Конфигурирование больших страниц
  1. На вкладке Доп. параметры (Custom Properties) окна Создать…​ (New)/Изменить…​ (Edit) выберите hugepages из списка пользовательских свойств, где по умолчанию отображается Выберите ключ…​ (Please select a key…).

  2. Укажите размер большой страницы в КБ (например, для задания размера страниц равной 1Гб, необходимо установить значение 1048576).

К размеру большой страницы предъявляются следующие требования:

  • Размер большой страницы у виртуальной машины должен быть такой же, что и у закрепленного хоста.

  • Объем памяти виртуальной машины должен соответствовать выбранному размеру свободных больших страниц закрепленного хоста.

  • Размер узла NUMA должен представлять собой величину, кратную выбранному размеру большой страницы.

При использовании больших страниц на виртуальной машине становится недоступным динамическое добавление или изъятие ОЗУ ВМ.

Данная настройка не влияет на количество и размер больших страниц внутри гостевой операционной системы ВМ.

При необходимости настройки больших страниц внутри гостевой ОС необходимо в дополнение к настройке hugepages добавить пользовательское свойство ВМ extra_cpu_flags со значением pdpe1gb.

Выключение KSM (Disabling KSM)

Порядок действий:

  1. Нажмите и выберите кластер.

  2. Нажмите Изменить (Edit).

  3. На вкладке Оптимизация (Optimization) снимите флажок Включить KSM (Enable KSM).

4.10. Настройка часового пояса

Настройки часовых поясов для виртуальных машин хранятся в zVirt в файле /etc/ovirt-engine/timezones/00-defaults.properties. В этом файле содержатся значения часовых поясов по умолчанию, например, Etc/GMT=Greenwich Standard Time. В нем используются сопоставления, действительные для часовых поясов Windows и других.

Не изменяйте настоящий файл 00-defaults.properties. Обновление или восстановление Менеджера управления приведет к перезаписи изменений.

Не изменяйте значения, которые поступают непосредственно от операционной системы или Менеджера управления.

Порядок действий:

  1. Создайте файл переопределения в /etc/ovirt-engine/timezones/. Имя файла должно начинаться со значения больше 00, чтобы файл появился после файла /etc/ovirt-engine/timezones/00-defaults.properties и заканчивался расширением .properties. Например, 10-timezone.properties переопределяет файл по умолчанию 00-defaults.properties. Последний файл в списке будет иметь приоритет перед предыдущими файлами.

  2. Добавьте новые часовые пояса в этот файл. Убедитесь, что каждый ключ — это действительный Общий часовой пояс из базы данных часовых поясов, а значение — действительный часовой пояс Windows:

    Общее

    Часовые пояса, которые используются в операционных системах, отличных от Windows, должны соответствовать стандартному формату часового пояса, например, Etc/GMT или Europe/Moscow.

    Windows

    Часовые пояса, которые Windows непосредственно поддерживает, например, GMT Standard Time или Israel Standard Time.

  3. Перезапустите службу zVirt:

    systemctl restart ovirt-engine

5. Изменение виртуальных машин

5.1. Изменение свойств виртуальных машин

Изменения параметров хранилища, операционной системы или сети могут негативно сказаться на работе виртуальной машины. Убедитесь в правильности всех данных, прежде чем вносить какие-либо изменения. Вносить изменения в виртуальные машины можно, пока те работают, при этом некоторые изменения (перечисленные в процедуре ниже) сразу вступят в силу. Чтобы все остальные изменения вступили в силу, необходимо выключить и перезапустить виртуальную машину.

Внешние виртуальные машины (отмеченные префиксом внешняя (external)) нельзя изменить через Менеджер управления.

Порядок действий:

  1. Нажмите .

  2. Выберите виртуальную машину, которую нужно изменить.

  3. Нажмите Изменить (Edit).

  4. Измените настройки нужным образом.

    Изменения следующих настроек сразу вступают в силу:

    • Имя (Name).

    • Описание (Description).

    • Комментарий (Comment).

    • Профиль нагрузки (Optimized for) (рабочей станции/сервера/высокой производительности).

    • Защита от удаления (Delete Protection).

    • Сетевые интерфейсы (с привязкой к vNIC профилю) (Instantiate VM network interfaces by picking a vNIC profile).

    • Оперативная память (разделяемая) (Memory Size) (измените это поле, чтобы выполнить горячее подключение виртуальной памяти. См. Горячее подключение виртуальной памяти).

    • Виртуальные сокеты (Virtual Sockets) (измените это поле, чтобы выполнить горячее подключение ЦП. См. Горячее подключение виртуальных ЦП).

    • Высокая доступность (Highly Available).

    • Приоритет очереди запуска/миграции (Priority for Run/Migration queue).

    • Отключить строгую проверку пользователей (Disable strict user checking).

    • Значок (Icon).

  5. Нажмите OK.

  6. Если появляется всплывающее окно Конфигурация следующего запуска (Next Start Configuration), нажмите OK.

Некоторые изменения сразу вступают в силу. Другие — после выключения и перезапуска виртуальной машины. До этого будет отображаться значок предстоящих изменений, напоминая о необходимости перезапустить виртуальную машину.

5.2. Сетевые интерфейсы

5.2.1. Добавление нового сетевого интерфейса

Можно добавить несколько сетевых интерфейсов к виртуальным машинам — это позволит подключить её к нескольким логическим сетям.

Можно создать наложенную сеть для виртуальных машин, изолированную от хостов, задав логическую сеть, которая не подключена к физическим интерфейсам хоста. Например, можно создать среду ДМЗ, в которой виртуальные машины взаимодействуют между собой через мост, созданный на хосте.

Наложенная сеть использует открытую виртуальную сеть, которая должна быть установлена как внешний провайдер сети.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Сетевые интерфейсы (Network Interfaces).

  4. Нажмите Новый (New).

  5. Задайте Имя (Name) сетевого интерфейса.

  6. Выберите Профиль (Profile) и Тип (Type) сетевого интерфейса из выпадающих списков. Выпадающие списки Профиль (Profile) и Тип (Type) заполнены согласно профилям и типам сетей, которые доступны кластеру, и сетевым картам, которые, в свою очередь, доступны виртуальной машине.

  7. При необходимости установите флажок Пользовательский MAC-адрес (Custom MAC address) и введите необходимый MAC-адрес для сетевой карты.

  8. Нажмите OK.

Новый сетевой интерфейс появится в списке на вкладке Сетевые интерфейсы (Network Interfaces) в подробном представлении виртуальной машины. Параметр Состояние соединения (Link State) установлен на значение Включено (Up) по умолчанию, когда сетевая карта создаётся на виртуальной машине и подключена к сети.

5.2.2. Изменение сетевого интерфейса

Чтобы внести изменения в настройки сети, необходимо изменить сетевой интерфейс. Эту процедуру можно выполнить на работающих виртуальных машинах, но некоторые действия можно выполнить только на остановленных виртуальных машинах.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Сетевые интерфейсы (Network Interfaces) и выберите сетевой интерфейс, который хотите изменить.

  4. Нажмите Изменить (Edit).

  5. Измените настройки нужным образом. Можно указать Имя (Name), Профиль (Profile), Тип (Type) и Пользовательский MAC-адрес (Custom MAC address). См. раздел Добавление нового сетевого интерфейса.

  6. Нажмите OK.

5.2.3. Горячее подключение сетевого интерфейса

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

Горячее подключение сетевых интерфейсов должно поддерживаться гостевой операционной системой.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Сетевые интерфейсы (Network Interfaces) и выберите сетевой интерфейс, для которого хотите выполнить горячее подключение.

  4. Нажмите Изменить (Edit).

  5. Установите параметр Состояние карты (Card Status) в значение Подключена (Plugged), чтобы включить сетевой интерфейс, или в значение Отключена (Unplugged), чтобы отключить её.

  6. Нажмите OK.

5.2.4. Удаление сетевого интерфейса

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Сетевые интерфейсы (Network Interfaces) и выберите сетевой интерфейс, который хотите удалить.

  4. Нажмите Удалить (Remove).

  5. Нажмите OK.

5.3. Виртуальные диски

5.3.1. Добавление нового виртуального диска

Можно добавить несколько виртуальных дисков к виртуальной машине.

Тип диска по умолчанию: Образ (Image). Можно также добавить диск Direct LUN. Созданием диска Образ (Image) полностью управляет Менеджер управления. Для дисков Direct LUN требуются уже существующие таргеты, подготовленные извне. Существующие диски — это либо «плавающие» диски, либо общие диски, подключенные к виртуальным машинам.

При добавлении диска типа Direct LUN для фильтрации используемых LUN активируйте опцию Скрыть используемые LUN’ы.

rdm filter

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть подробное представление.

  3. Откройте вкладку Диски (Disks).

  4. Нажмите Новый (New).

  5. Нажмите на соответствующую кнопку-переключатель для переключения между типами Образ (Image) и Direct LUN.

  6. Введите Размер (GiB) (Size (GiB)), Имя (Alias) и Описание (Description) нового диска.

  7. Используйте выпадающие списки и флажки для настройки диска. Дополнительные сведения о полях для всех типов дисков см. в разделе Описание настроек в окнах «Создать виртуальный диск (New Virtual Disk)» и «Изменить виртуальный диск (Edit Virtual Disk)».

  8. Нажмите OK.

Вскоре новый диск появится в подробном представлении виртуальной машины.

Диск можно добавить также через вкладку Общее (General) окна Изменить виртуальную машину (Edit Virtual Machine), вызываемого через   .

5.3.2. Подключение существующего диска к виртуальной машине

«Плавающие» диски — это диски, которые не ассоциированы ни с одной виртуальной машиной.

При использовании «плавающих» дисков на настройку виртуальных машин уходит минимум времени. Если назначить «плавающий» диск в качестве хранилища для виртуальной машины, то больше не нужно ждать предварительного выделения пространства на диске при создании виртуальной машины.

«Плавающие» диски можно подключить к одной или к нескольким виртуальным машинам, если это общий диск. Каждая виртуальная машина, использующая общий диск, может использовать свой тип интерфейса диска.

Когда «плавающий» диск подключен к виртуальной машине, виртуальная машина может получить к нему доступ.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Диски (Disks).

  4. Нажмите Подключить (Attach).

  5. Выберите один или несколько виртуальных дисков из списка доступных дисков и выберите нужный интерфейс из выпадающего списка Интерфейс (Interface).

  6. Нажмите OK.

Диск можно добавить также через вкладку Общее (General) окна Изменить виртуальную машину (Edit Virtual Machine), вызываемого через .

При подключении виртуальных дисков к виртуальным машинам или их отключении ресурсы по квоте не расходуются.

5.3.3. Увеличение доступного размера виртуального диска

Можно увеличить доступный размер виртуального диска, пока виртуальный диск подключен к виртуальной машине. Изменение размера виртуального диска не приводит к изменению размеров базовых разделов или файловых систем на этом виртуальном диске. Используйте утилиту fdisk или parted для изменения размеров разделов и файловых систем нужным образом.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Диски (Disks) и выберите диск, который хотите изменить.

  4. Нажмите Изменить (Edit).

  5. Введите значение в поле Увеличить размер на (GB) (Extend size by(GiB)).

  6. Нажмите OK.

Статус целевого диска ненадолго изменится на Заблокировано (Locked), пока меняется размер диска/Когда размер диска будет изменен, его статус поменяется на значение OK.

5.3.4. Горячее подключение виртуального диска

Для виртуальных дисков можно выполнять горячее подключение, т.е. включать или выключать их во время работы виртуальной машины.

Горячее подключение виртуальных дисков должно поддерживаться гостевой операционной системой.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Диски (Disks) и выберите виртуальный диск, для которого хотите выполнить горячее подключение.

  4. Нажмите , затем нажмите Включить (Activate), чтобы включить диск, или Выключить (Deactivate), чтобы выключить диск.

    disk menu

  5. Нажмите OK.

5.3.5. Удаление виртуального диска из виртуальной машины

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Диски (Disks) и выберите виртуальный диск, который хотите удалить.

  4. Нажмите кнопку , затем Выключить (Deactivate).

  5. Нажмите OK.

  6. Нажмите Удалить (Remove).

  7. При желании отметьте флажком Удалить окончательно (Remove Permanently), чтобы полностью удалить виртуальный диск из среды. Если не выбрать эту настройку, например, потому что диск общий, то виртуальный диск останется в разделе .

  8. Нажмите OK.

Если диск был создан как блочное устройство, например, iSCSI, и при создании диска был установлен флажок Очистить после удаления (Wipe After Delete), то файл журнала хоста можно использовать для проверки того, были ли удалены данные после последнего стирания диска. Если диск был создан как блочное устройство, например iSCSI, и в домене хранения до удаления диска был установлен флажок Очистить после удаления (Discard After Delete), то при удалении логического тома вызывается команда blkdiscard, и базовое хранилище получает уведомление, что блоки свободны. Команда blkdiscard также вызывается на логическом томе при удалении виртуального диска, если виртуальный диск подключен хотя бы к одной виртуальной машине с установленным флажком Включить Discard (Enable Discard).

5.3.6. Импортирование образа диска из импортированного домена хранения

Можно импортировать плавающие виртуальные диски из импортированного домена хранения. Для этой процедуры требуется доступ к Порталу администрирования.

Импортировать можно только диски совместимые с QEMU.

Порядок действий:

  1. Нажмите .

  2. Нажмите на импортированный домен хранения, чтобы открыть подробное представление.

  3. Нажмите Импорт диска (Disk Import).

  4. Выберите один или несколько образов дисков и нажмите Импортировать (Import). Откроется окно Импорт дисков (Import Disk(s)).

  5. Выберите подходящий Профиль диска (Disk Profile) для каждого диска.

  6. Нажмите OK, чтобы импортировать выбранные диски.

5.3.7. Импортирование незарегистрированного образа диска из импортированного домена хранения

Можно импортировать «плавающие» виртуальные диски из домена хранения. Плавающие диски, созданные вне среды zVirt, не регистрируются в Менеджере управления. Сканируйте домен хранения, чтобы обнаружить незарегистрированные плавающие диски для импортирования.

Для этой процедуры требуется доступ к Порталу администрирования.

Импортировать можно только диски совместимые с QEMU.

Порядок действий:

  1. Нажмите .

  2. Нажмите , затем нажмите Сканировать диски (Scan Disks), чтобы Менеджер управления мог обнаружить незарегистрированные диски.

  3. Нажмите на имя незарегистрированного диска и выберите Импорт диска (Disk Import).

  4. Выберите один или несколько образов дисков и нажмите Импортировать (Import). Откроется окно Импорт дисков (Import Disk(s)).

  5. Выберите подходящий Профиль диска (Disk Profile) для каждого диска.

  6. Нажмите OK, чтобы импортировать выбранные диски.

5.4. Виртуальная память

5.4.1. Горячее подключение виртуальной памяти

Для модулей виртуальной памяти можно выполнять горячее подключение, т.е. включать или выключать их во время работы виртуальной машины. Каждый раз при горячем подключении памяти она появляется как новое устройство памяти на вкладке Устройства ВМ (Vm Devices) в подробном представлении виртуальной машины (максимум 16 доступных слотов). При перезапуске виртуальной машины эти устройства удаляются с вкладки Устройства ВМ (Vm Devices) без уменьшения памяти виртуальной машины, что позволяет подключать больше устройств памяти с помощью горячего подключения. При неудачной попытке горячего подключения (например, если больше нет доступных слотов), память будет увеличена при перезапуске виртуальной машины.

ram hotplug

В настоящее время эта функция не поддерживается для виртуальной машины с Менеджером управления hosted engine.
Если память, подключаемую в горячем режиме,необходимо подключить позже, см. раздел Горячее отключение виртуальной памяти.

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Система (System).

  4. Увеличьте Оперативную память (разделяемая) (Memory Size), указав необходимый общий объем. Объем добавляемой памяти должен быть кратен 256 МБ. По умолчанию максимально допустимый объем памяти для виртуальной машины в 4 раза больше указанного объема памяти. Хотя значение изменяется в пользовательском интерфейсе, на максимальное значение горячее подключение не распространяется, и появится значок предстоящих изменений . Чтобы избежать этого, можно вернуть максимальное значение памяти на исходное.

  5. Нажмите OK.

    После этого действия открывается окно Ожидание изменений виртуальной машины (Pending Virtual Machine changes), т.к. некоторые значения, например, Максимум памяти (Maximum memory) и Оперативная память (гарантированная) (Physical Memory Guaranteed), не изменятся, пока виртуальная машина не будет перезагружена. Однако горячее подключение запускается при изменении значения Оперативная память (разделяемая) (Memory Size), которое сразу вступает в силу.

  6. Нажмите OK.

Объявленная память (Defined Memory) виртуальной машины обновляется на вкладке Общее (General) в подробном представлении. Новые только что добавленные устройства памяти можно посмотреть на вкладке Устройства ВМ (Vm Devices) в подробном представлении.

5.4.2. Горячее отключение виртуальной памяти

Для виртуальной памяти можно выполнять горячее отключение, т.е. выключать ее во время работы виртуальной машины.

Предварительные условия:

  • Горячее отключение допустимо только для памяти, добавленной с помощью горячего подключения.

  • Горячее отключение памяти должно поддерживаться операционной системой виртуальной машины.

  • На виртуальной машине не должно быть включено устройство регулирования размера памяти (balloon device).

  • Чтобы память, добавленную через горячее подключение, можно было в дальнейшем и отключить без остановки виртуальной машины, добавьте параметр перемещаемый узел (movable_node) в командную строку ядра виртуальной машины, как показано ниже, и перезагрузите виртуальную машину:

    grubby --update-kernel=ALL --args="movable_node"

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Устройства ВМ (Vm Devices).

  4. В столбце Отключение на лету (Hot Unplug) нажмите Отключение на лету (Hot Unplug) рядом с теми устройствами памяти, которые хотите удалить.

  5. Нажмите OK в окне Отключение памяти на лету (Memory Hot Unplug).

    При необходимости значение Оперативная память (гарантированная) (Physical Memory Guaranteed) для виртуальной машины автоматически уменьшается.

5.5. Горячее подключение виртуальных ЦП

Для виртуальных ЦП можно выполнять горячее подключение, т.е. включать или выключать их во время работы виртуальной машины.

Горячее отключение допустимо только для виртуальных ЦП, которые были ранее добавлены с помощью горячего подключения. После горячего отключения оставшееся количество виртуальных ЦП не может быть меньше того, с которым виртуальная машина была изначально создана.

Предварительные условия*

  • Операционная система (Operating System) виртуальной машины должна быть прямо указана в окне Новая виртуальная машина (New Virtual Machine) или Изменить виртуальную машину (Edit Virtual Machine).

  • Горячее отключение ЦП должно поддерживаться операционной системой виртуальной машины. Подробности см. в таблице ниже.

  • На виртуальных машинах Windows должны быть установлены гостевые агенты. См. Установка гостевых агентов.

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Система (System).

  4. Измените значение Виртуальные сокеты (Virtual Sockets) раскрыв блок Дополнительные параметры (Advanced Parameters) нужным образом.

  5. Нажмите OK.

Таблица 12. Матрица поддержки операционных систем для горячего подключения виртуальных ЦП

Операционная система Версия Архитектура Горячее подключение поддерживается Горячее отключение поддерживается

Red Hat Enterprise Linux Atomic Host 7

x86

Да

Да

Red Hat Enterprise Linux 6.3 и выше

x86

Да

Да

Red Hat Enterprise Linux 7.0 и выше

x86

Да

Да

Red Hat Enterprise Linux 7.3 и выше

PPC64

Да

Да

Red Hat Enterprise Linux 8.0 и выше

x86

Да

Да

Microsoft Windows Server 2012 R2

все

x64

Да

Нет

Microsoft Windows Server 2016

Стандартная, центр данных (Standard, Datacenter)

x64

Да

Нет

Microsoft Windows Server 2019

Стандартная, центр данных (Standard, Datacenter)

x64

Да

Нет

Microsoft Windows 8.x

все

x86

Да

Нет

Microsoft Windows 8.x

все

x64

Да

Нет

Microsoft Windows 10

все

x86

Да

Нет

Microsoft Windows 10

все

x64

Да

Нет

5.6. Закрепление виртуальной машины за несколькими хостами

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

При отказе хоста виртуальная машина с признаком высокой доступности автоматически перезапускается на одном из других хостов, за которым она закреплена.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Хост (Host).

  4. Нажмите кнопку-переключатель Указанном хосте (Specific Host(s)) под блоком Запустить на (Start Running On) и выберите минимум два хоста из списка.

  5. Откройте вкладку Высокая доступность (High Availability).

  6. Поставьте флажок Высокая доступность (High Availability).

  7. Выберите домен хранения для аренды ВМ.

  8. Выберите значение Низкий (Low), Средний (Medium) или Высокий (High) из выпадающего списка Приоритет (Priority). Когда запускается миграция, создается очередь, и виртуальные машины с высоким приоритетом переносятся первыми. При дефиците ресурсов в кластере будут перенесены только виртуальные машины с признаком высокой доступности.

  9. Нажмите OK.

5.7. Просмотр виртуальных машин, закрепленных на хосте

Виртуальные машины, закрепленные на хосте, можно просматривать, даже когда они выключены. Откройте список Закрепленные на хосте (Pinned to Host), чтобы посмотреть, какие виртуальные машины будут затронуты и какие нужно будет перезапустить вручную, как только хост снова станет активным.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя хоста, чтобы открыть его подробное представление.

  3. Откройте вкладку Виртуальные машины (Virtual Machines).

  4. Выберите фильтр Прикреплён к текущему хосту (Pinned to Host).

5.8. Замена CD-диска на виртуальной машине

Доступный для виртуальной машины CD-диск можно заменить во время ее работы с помощью образов ISO, загруженных в домен данных кластера виртуальной машины.

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите Дополнительные действия и затем Сменить CD (Change CD).

    cd change

  3. Выберите файл ISO из списка, чтобы извлечь CD-диск, доступный в данный момент виртуальной машине, и смонтировать этот файл ISO как CD-диск.

  4. Нажмите OK.

5.9. Аутентификация по смарт-карте

Смарт-карты — это внешнее аппаратное средство защиты, которое чаще всего встречается в кредитных картах, но также используется многими компаниями в качестве токена аутентификации. Смарт-карты можно использовать для защиты виртуальных машин.

Включение смарт-карт:

  1. Убедитесь, что аппаратное обеспечение смарт-карты подключено к клиентской машине и установлено в соответствии с инструкциями производителя.

  2. Нажмите и выберите виртуальную машину.

  3. Нажмите Изменить (Edit).

  4. Откройте вкладку Консоль (Console) и установите флажок Поддержка смарт-карт (Smartcard enabled).

  5. Нажмите OK.

  6. Подключитесь к работающей виртуальной машине, нажав кнопку Консоль (Console). Теперь аутентификация с помощью смарт-карты передается от клиентского оборудования на виртуальную машину.

Если аппаратное обеспечение смарт-карты установлено некорректно, то включение функции смарт-карты приведет к тому, что виртуальная машина не сможет нормально загрузиться.

Выключение смарт-карт:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Консоль (Console) и снимите флажок Поддержка смарт-карт (Smartcard enabled).

  4. Нажмите OK.

    Настройка клиентских систем для совместного использования смарт-карт
    • Смарт-картам могут потребоваться определенные библиотеки для доступа к сертификатам. Эти библиотеки должны быть видны библиотеке NSS, которую spice-gtk использует для предоставления смарт-карты гостевой машине. Библиотека NSS требует, чтобы библиотеки предоставляли интерфейс PKCS#11.

    • Убедитесь, что архитектура модуля соответствует архитектуре spice-gtk / remote-viewer. Например, если у вас есть только 32-разрядная библиотека PKCS#11, то для работы смарт-карт необходимо установить 32-разрядную сборку virt-viewer.

    Настройка клиентов операционных систем семейства RHEL для поддержки смарт-карт

    Linux поддерживает смарт-карты. Установите группу пакетов Smart card support. Если группа поддержки смарт-карт установлена в системе Linux, то смарт-карты перенаправляются на гостевую машину, когда включена поддержка смарт-карт. Чтобы установить группу Smart card support, выполните следующую команду:

    dnf groupinstall "Smart card support"
    Настройка клиентов RHEL с другим промежуточным ПО смарт-карт

    Red Hat Enterprise Linux предоставляет общесистемный реестр модулей pkcs11 в p11-kit, и они доступны для всех приложений. Чтобы зарегистрировать стороннюю библиотеку PKCS#11 в базе данных p11-kit, выполните следующую команду от имени пользователя root:

    echo "module: /path/to/library.so" > /etc/pkcs11/modules/my.module

    Чтобы убедиться, что смарт-карта отображается для p11-kit через эту библиотеку, выполните следующую команду:

    Настройка клиентов Windows

    Для клиентов Windows библиотеки, обеспечивающие поддержку PKCS#11, необходимо получить от сторонних производителей. Когда такие библиотеки получены, зарегистрируйте их, выполнив следующую команду от имени пользователя с расширенными правами:

    modutil -dbdir %PROGRAMDATA%\pki\nssdb -add "module name" -libfile C:_\Path\to\module_.dll

6. Администрирование виртуальных машин

6.1. Выключение виртуальной машины

Прекратить работу виртуальной машины можно с помощью кнопки Выключить (Shutdown) или Отключить питание (Power Off). Кнопка Выключить (Shutdown) позволяет корректно выключить виртуальную машину. Кнопка Отключить питание (Power Off) позволяет выполнить принудительное выключение. Корректное выключение предпочтительнее, нежели принудительное.

Если рядом с виртуальной машиной появился восклицательный знак, значит, удалить моментальный снимок не удалось, и после выключения невозможно будет повторно запустить виртуальную машину. Попробуйте удалить моментальный снимок снова и убедитесь, что восклицательный знак исчез, перед тем как выключить виртуальную машину. Дополнительную информацию см. в разделе Удаление моментального снимка.

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите Выключить (Shutdown) или нажмите правой кнопкой мыши на виртуальную машину и выберите Выключить (Shutdown) из всплывающего контекстного меню.

  3. При желании на Портале администрирования введите Причину (Reason) выключения виртуальной машины в окне подтверждения Выключить ВМ (Shut down Virtual Machine(s)). В нем можно указать причину выключения, которая будет отображаться в журналах и при последующем включении питания виртуальной машины.

  4. Нажмите OK в окне подтверждения Выключить ВМ (Shut down Virtual Machine(s)).

При корректном выключении Состояние (Status) виртуальной машины изменится на Выключена (Down) и обозначится зачком . Если виртуальную машину нельзя выключить корректно, нажмите стрелку «вниз» рядом с кнопкой Выключить (Shutdown), а затем нажмите Выключить питание (Power Off) для выполнения принудительного выключения или нажмите правой кнопкой мыши на виртуальную машину и выберите Выключить питание (Power Off) из всплывающего контекстного меню.

vm shutdown

6.2. Приостановка виртуальной машины

Приостановка виртуальной машины это то же самое, что и ее перевод в Спящий режим (Hibernate).

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите Приостановить (Suspend) или нажмите правой кнопкой мыши на виртуальную машину и выберите Приостановить (Suspend) из всплывающего контекстного меню.

Состояние (Status) виртуальной машины изменится на Приостановлена (Suspended) и будет обозначено значком .

6.3. Перезагрузка или сброс виртуальной машины

Виртуальные машины можно перезапустить двумя способами — используя перезагрузку или сброс.

Перезагрузка виртуальной машины может потребоваться в некоторых случаях, например, после обновления или изменения конфигурации. При перезагрузке консоль виртуальной машины остается открытой, пока гостевая операционная система перезапускается.

Если гостевая операционная система не загружается или не отвечает, то требуется сброс виртуальной машины. При сбросе консоль виртуальной машины остается открытой, пока гостевая операционная система перезапускается.

Сброс выполняется только с Портала администрирования.
Перезагрузка виртуальной машины

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите Перезагрузить (Reboot) или нажмите правой кнопкой мыши на виртуальную машину и выберите Перезагрузить (Reboot) из всплывающего контекстного меню.

  3. Нажмите OK в окне подтверждения Перезагрузить ВМ (Reboot Virtual Machine(s)).

Сброс виртуальной машины

Порядок действий:

  1. Нажмите и выберите работающую виртуальную машину.

  2. Нажмите стрелку «вниз» рядом с кнопкой Перезагрузить (Reboot), затем нажмите Сбросить питание (Reset) или нажмите правой кнопкой мыши на виртуальную машину и выберите Сбросить питание (Reset) из всплывающего контекстного меню.

  3. Нажмите OK в окне подтверждения Сбросить питание ВМ (Reset Virtual Machine(s)).

Во время операций по перезагрузке и сбросу Состояние (Status) виртуальной машины сначала изменится на Перезагрузка в процессе (Reboot In Progress) со значком , а затем вернется в значение Работает (Up) .

vm restart

6.4. Удаление виртуальной машины

Кнопка Удалить (Remove) не активна во время работы виртуальных машин. Чтобы можно было удалить виртуальную машину, ее сначала нужно выключить.

Порядок действий:

  1. Нажмите и выберите виртуальную машину, которую нужно удалить.

  2. Нажмите Удалить (Remove) в .

  3. При желании установите флажок Удалить диск(и) (Remove Disk(s)), чтобы вместе с виртуальной машиной удалить подключенные к ней виртуальные диски. Если флажок Удалить диск(и) (Remove Disk(s)) снят, то виртуальные диски останутся в среде в качестве плавающих дисков.

  4. Нажмите OK.

6.5. Клонирование виртуальной машины

Виртуальные машины можно клонировать без предварительного создания шаблона или моментального снимка.

Порядок действий:

  1. Нажмите и выберите виртуальную машину, которую нужно клонировать.

  2. Нажмите Клонировать ВМ (Clone VM) в .

  3. Введите Имя (Name) для новой виртуальной машины.

  4. Нажмите OK.

6.6. Обновление гостевых агентов и драйверов виртуальных машин

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

Обратите внимание на следующие важные моменты:

  • При поиске установочных пакетов, обязательно используйте официальный репозиторий производителя.

  • Для успешной установки и функционирования гостевых дополнений, вам потребуются административные права.

Инструменты и агенты также предоставляют информацию для виртуальных машин, включая:

  • Использование ресурсов.

  • IP-адреса.

  • Установленные приложения.

Гостевые инструменты для операционной систем семейства MS Windows распространяются в виде файла ISO, который можно подключить к виртуальным машинам. Гостевые инструменты для операционных систем семейства Linux распространяются с этими ОС в виде пакета, обычно называемым qemu-guest-agent-<version>.rpm/qemu-guest-agent-<version>.deb.

6.6.1. Обновление гостевых агентов и драйверов в Linux

Обновите гостевые агенты и драйверы на виртуальных машинах с Linux, чтобы использовать последнюю версию.

Порядок действий

  1. Авторизуйтесь на виртуальной машине с Linux.

  2. Обновите пакет qemu-guest-agent:

    • Для семейства ОС RedHat:

      dnf update qemu-guest-agent
    • Для семейства ОС Debian

      apt-get upgrade qemu-guest-agent
  3. Перезапустите службу:

    systemctl restart qemu-guest-agent.service

6.6.2. Обновление гостевых агентов и драйверов Windows

Образ ISO с драйверами virtio для Windows, необходимый для выполнения процедур, описанных в этом разделе, можно загрузить в официальном репозитории Orionsoft. Рекомендуем скачивать последнюю доступную версию образа.

Обновить драйверы Windows или гостевые агентов Windows можно с помощью ISO-образа virtio-win, используя командную строку виртуальной машины. Во время этой процедуры нужно удалить и переустановить драйверы, которые могут привести к нарушению работы сети. После переустановки драйверов ваши настройки восстановятся.

Порядок действий:

  1. При обновлении драйверов на виртуальной машине Windows используйте утилиту netsh, чтобы сохранить настройки TCP перед удалением драйвера netkvm: C:\WINDOWS\system32>netsh dump > filename.txt

  2. Выгрузите файл virtio-win_version.iso в домен данных.

  3. Если виртуальная машина работает, то на Портале администрирования или Пользовательском портале нажмите Cменить CD (Change CD), чтобы подключить файл virtio-win_version.iso к каждой виртуальной машине. Если виртуальная машина выключена, нажмите кнопку Однократный запуск(Run Once) и подключите файл virtio-win_version.iso как CD.

  4. Авторизуйтесь на виртуальной машине.

  5. Выберите CD-привод (в этом примере — D:\\), содержащий файл virtio-win_version.iso.

  6. Переустановите гостевые агенты или драйверы:

    • Чтобы переустановить только гостевые агенты, используйте qemu-ga-x86_64.msi:

      C:\WINDOWS\system32>msiexec.exe /i D:\guest-agent\qemu-ga-x86_64.msi /passive /norestart
    • Чтобы переустановить гостевые агенты и драйверы или только драйверы, используйте virtio-win-gt-x64.msi:

      C:\WINDOWS\system32>msiexec.exe /i D:\virtio-win-gt-x64.msi /passive /norestart
  7. При обновлении драйверов восстановите настройки, сохраненные с использованием netsh:

    C:\WINDOWS\system32>netsh -f filename.txt

6.7. Виртуальные машины и разрешения

6.7.1. Управление системными разрешениями для виртуальной машины

Будучи Суперпользователем (SuperUser), системный администратор управляет всеми аспектами Портала администрирования. Другим пользователям могут быть назначены ограниченные административные роли. Ограниченные роли нужны, чтобы предоставить пользователю административные права, которые действуют только в отношении определенного ресурса. Например, роль Администратор центра данных (DataCenterAdmin) имеет права администратора только на назначенный центр данных (кроме его хранилища), а роль Администратор кластера (ClusterAdmin) имеет права администратора только на назначенный кластер.

Пользователь, управляющий ВМ (UserVmManager) — это системная административная роль для виртуальных машин в центре данных. Эту роль можно применять к конкретным виртуальным машинам, к центру данных или ко всей среде виртуализации, что довольно удобно, т.к. можно разрешать разным пользователям управлять определенными виртуальными ресурсами.

Роль администратора виртуальной машины разрешает пользователю выполнять следующие действия:

  • Создавать, изменять и удалять виртуальные машины.

  • Запускать, приостанавливать, выключать и останавливать виртуальные машины.

Роли и разрешения могут быть назначены только существующим пользователям.

Многие конечные пользователи связаны только с ресурсами виртуальной машины в среде виртуализации. Поэтому пользователю zVirt предоставляются несколько пользовательских ролей, позволяющих управлять именно виртуальными машинами, а не другими ресурсами центра данных.

6.7.2. Описание ролей администратора виртуальных машин

В приведенной ниже таблице описаны роли и права администратора, применимые к администрированию виртуальных машин.

Таблица 13. Роли системного администратора zVirt

Роль Права Примечания

DataCenterAdmin

Администратор центра данных

Обладает административными разрешениями в отношении всех объектов в конкретном центре данных, за исключением хранилища.

ClusterAdmin

Администратор кластера

Обладает административными разрешениями в отношении всех объектов в конкретном кластере.

NetworkAdmin

Администратор сети

Обладает административными разрешениями в отношении всех операций в конкретной логической сети. Может конфигурировать и управлять сетями, подключенными к виртуальным машинам. Чтобы сконфигурировать зеркалирование портов в сети виртуальных машин, примените роль Администратора сети (NetworkAdmin) к сети и роль Пользователя, управляющего ВМ (UserVmManager) к виртуальной машине.

6.7.3. Описание ролей пользователя виртуальных машин

В приведенной ниже таблице описаны пользовательские роли и права, применимые к пользователям виртуальных машин. Эти роли открывают доступ к Пользовательскому порталу, чтобы заходить на виртуальные машины и управлять ими, но не предоставляют никаких разрешений для Портала администрирования.

Таблица 14. Системные роли пользователя zVirt

Роль Права Примечания

UserRole

Может получать доступ к виртуальным машинам и пулам и использовать их.

Может авторизовываться на Пользовательском портале и использовать виртуальные машины и пулы.

PowerUserRole

Может создавать виртуальные машины и шаблоны и управлять ими.

В окне Настройка (Configure) () назначьте эту роль пользователю для всей среды, либо только для отдельных центров данных или кластеров. Например, если роль ключевого пользователя (PowerUserRole) применяется на уровне центра данных, то пользователь в этой роли может создавать виртуальные машины и шаблоны в центре данных. Роль ключевого пользователя (PowerUserRole) эквивалентна таким ролям, как Создатель ВМ (VmCreator), Создатель диска (DiskCreator) и Создатель шаблонов (TemplateCreator).

UserVmManager

Системный администратор виртуальной машины.

Может управлять виртуальными машинами, создавать и использовать моментальные снимки. Пользователю, который создает виртуальную машину через Пользовательский портал, автоматически назначается роль UserVmManager для этой машины.

UserTemplateBasedVm

Ограниченные права на использование только Шаблонов.

Уровень прав позволяет создавать виртуальные машины с помощью шаблона.

VmCreator

Может создавать виртуальные машины на Пользовательском портале.

Эта роль применяется не к отдельной виртуальной машине. Применяйте эту роль ко всей среде в окне Настройка (Configure). Применяя эту роль к кластеру, нужно также применить роль Создателя диска (DiskCreator) ко всему центру данных или к конкретным доменам хранения.

VnicProfileUser

Пользователь логической сети и сетевого интерфейса для виртуальных машин.

Если при создании профиля интерфейса логической сети vNIC, была выбрана опция Разрешить всем пользователям доступ к этому профилю (Allow all users to use this Profile), то разрешения VnicProfileUser назначаются всем пользователям логической сети. Затем пользователи могут подключать/отключать сетевые интерфейсы виртуальных машин к/от логической сети.

6.7.4. Назначение виртуальных машин пользователям

Если виртуальные машины создаются для других пользователей, а не для себя, то сначала следует назначить роли пользователям, и только потом они смогут использовать виртуальные машины. Обратите внимание, что разрешения можно назначать только существующим пользователям. Для получения дополнительной информации о создании учетных записей пользователей см. раздел Пользователи и роли в Руководстве администратора

Пользовательский портал поддерживает три роли по умолчанию: Пользователь (User), Ключевой пользователь (PowerUser) и Пользователь, управляющий ВМ (UserVmManager). Однако нестандартные роли можно настраивать через Портал администрирования. Роли по умолчанию описаны ниже.

  • Пользователь (User) может подключаться к виртуальным машинам и использовать их. Эта роль подходит конечным пользователям ПК, выполняющим повседневные задачи.

  • Ключевой пользователь (PowerUser) может создавать виртуальные машины и просматривать виртуальные ресурсы. Эта роль подходит администраторам или менеджерам, которые хотят предоставить виртуальные ресурсы работникам.

  • Пользователь, управляющий ВМ (UserVmManager) может изменять и удалять виртуальные машины, назначать пользовательские разрешения, использовать моментальные снимки и шаблоны. Роль подходит, если требуется внести изменения конфигурации в виртуальной среде.

Когда создается виртуальная машина, она автоматически наследует права Пользователя, который управляет ВМ (UserVmManager). Это позволяет вносить изменения в виртуальную машину и назначать пользователям разрешения на управление ею.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы перейти к её подробному представлению.

  3. Откройте вкладку Разрешения (Permissions).

  4. Нажмите Добавить (Add).

  5. Введите реальное или пользовательское имя или часть имени пользователя в текстовое поле и нажмите Поиск (Go). Список возможных совпадений отобразится в списке результатов.

  6. Установите флажок напротив пользователя, которому будут назначены разрешения.

  7. Выберите Пользовательскую роль (UserRole) из выпадающего списка Роль для связи: (Role to Assign).

  8. Нажмите OK.

Имя и роль пользователя отобразятся в списке пользователей, которым разрешен доступ к этой виртуальной машине.

Если пользователю назначены разрешения только в отношении одной виртуальной машины, то для этой виртуальной машины может быть настроен единый вход (SSO). Когда включен единый вход, пользователь авторизуется на Пользовательском портале, а затем подключается к виртуальной машине, например, через SPICE-консоль, при этом пользователи автоматически авторизуются на виртуальной машине, и им не нужно снова вводить имя пользователя и пароль. Единый вход можно включить или выключить на каждой отдельно взятой виртуальной машине. Подробную информацию о включении и выключении единого входа для виртуальных машин см. в разделе Настройка единого входа (Single Sign-On) для виртуальных машин.

6.7.5. Лишение пользователей доступа к виртуальным машинам

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы перейти к её подробному представлению.

  3. Нажмите Разрешения (Permissions).

  4. Выберите разрешения, которые хоте удалить (чтобы выбрать несколько зажмите клавишу Ctrl на клавиатуре и щёлкните на разрешениях).

  5. Нажмите Удалить (Remove). Появится предупреждающее сообщение с просьбой подтвердить удаление выбранных разрешений.

  6. Для продолжения нажмите OK. Для отмены нажмите Закрыть (Cancel).

6.8. Моментальные снимки

6.8.1. Создание моментального снимка виртуальной машины

Моментальный снимок — это представление операционной системы и приложений виртуальной машины на любом или всех доступных дисках в конкретный момент времени. Сделайте моментальный снимок виртуальной машины, прежде чем вносить в нее изменения, которые могут привести к нежелательным последствиям. С помощью снимка можно откатить виртуальную машину до предыдущего состояния.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Снимки (Snapshots) и нажмите Создать (Create).

  4. Введите описание моментального снимка.

  5. Выберите диски в Выбрать диски (Disks to include), отметив их флажками.

    Если ни один диск не выбран, то будет создан частичный моментальный снимок виртуальной машины (без диска). Доступен предварительный просмотр моментального снимка для проверки конфигурации виртуальной машины. Обратите внимание, что если подтвердить частичный моментальный снимок в процедуре восстановления, то ее результатом каждый раз будет виртуальная машина без диска.
  6. Выберите Сохранить память (Save Memory), чтобы память работающей виртуальной машины была включена в моментальный снимок.

  7. Нажмите OK.

Операционная система и приложения виртуальной машины на выбранном(-ых) диске(-ах) хранятся в моментальном снимке, для которого доступны предварительный просмотр и восстановление. При создании моментального снимка у него будет статус Заблокировано (Locked), который потом изменится на Ok. Если нажать на моментальный снимок, то подробные сведения о нем будут отображаться в выпадающих списках Общее (General), Диски (Disks), Сетевые интерфейсы (Network Interfaces) и Установленные приложения (Installed Applications) на вкладке Cнимки (Snapshots).

6.8.2. Использование моментальных снимков для восстановления виртуальной машины

С помощью моментального снимка можно восстановить виртуальную машину до предыдущего состояния.

Процесс восстановления можно начать только при выключенной виртуальной машине.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Снимки (Snapshots), чтобы открыть список доступных моментальных снимков.

  4. В верхней панели выберите моментальный снимок для восстановления. Подробные сведения о моментальном снимке отображаются в нижней панели.

  5. Нажмите кнопку Предварительный просмотр (Preview) и выберите Пользовательский (Custom).

  6. Установите флажки, чтобы выбрать Память (Memory) и Диски (Disks) , которые хотите восстановить, и нажмите OK. Так, можно создавать и восстанавливаться с пользовательского моментального снимка, используя конфигурацию и диск(-и) из нескольких моментальных снимков.

    Статус моментального снимка изменится на Режим предварительного просмотра (Preview Mode). Статус виртуальной машины ненадолго изменится на Образ заблокирован (Image Locked) , а потом вернется в значение Выключен (Down) .

  7. Включите виртуальную машину; она будет работать на образе диска моментального снимка.

  8. Выключите виртуальную машину.

  9. Нажмите Подтвердить (Commit), чтобы всегда восстанавливать виртуальную машину до состояния этого моментального снимка. Все последующие моментальные снимки будут стерты.
    Либо нажмите Отменить (Undo), чтобы отключить моментальный снимок и вернуть виртуальную машину до предыдущего состояния.

При наличии нескольких снимков, восстановление состояния виртуальной машины из одного из них, удалит более поздние снимки, а их данные будут потеряны.

6.8.3. Создание виртуальной машины из моментального снимка

С помощью моментального снимка можно создать другую виртуальную машину.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Снимки (Snapshots), чтобы открыть список доступных моментальных снимков.

  4. Выберите моментальный снимок из списка и нажмите Клонировать (Clone).

  5. Введите Имя (Name) виртуальной машины.

  6. Нажмите OK.

Вскоре клонированная виртуальная машина появится на вкладке Виртуальные машины (Virtual Machines) на панели навигации со статусом Образ заблокирован (Image Locked). Статус виртуальной машины не изменится, пока zVirt не завершит ее создание. Создание виртуальных дисков с динамическим расширением пространства занимает меньше времени, чем создание виртуальных дисков с предварительным выделением.

Когда виртуальная машина готова к использованию, ее статус в разделе изменится с Образ заблокирован (Image Locked) на Выключен (Down) .

6.8.4. Удаление моментального снимка

Моментальный снимок виртуальной машины можно стереть и навсегда удалить из среды zVirt.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Снимки (Snapshots), чтобы открыть список моментальных снимков выбранной виртуальной машины.

  4. Выберите моментальный снимок, который хотите удалить.

  5. Нажмите Удалить (Delete).

  6. Нажмите OK.

При неудачной попытке удаления устраните проблему, из-за которой удаление не произошло (например, отказ хоста, недоступное устройство хранения или временные проблемы в работе сети), и попробуйте еще раз.

6.8.5. Просмотр списка всех моментальных снимков

В разделе отображаются моментальные снимки из всех доменов хранения.

Моментальные снимки можно:

  • отфильтровать по:

    • центру данных;

    • домену хранения;

  • найти по:

    • имени снимка;

    • имени ВМ.

При необходимости можно включить опцию Показать активные слои виртуальной машины.

all snapshots

С помощью кнопки можно:

  • экспортировать в csv;

  • настроить видимость колонок.

    column

На странице Снимки (Snapshots) при нажатии на имя:

  • центра данных будет выполнен переход на страницу администрирования центра данных, к которому относится моментальный снимок;

  • домена хранения будет выполнен переход на страницу администрирования домена хранения, на котором располагается моментальный снимок;

  • виртуальной машины будет выполнен переход на страницу администрирования виртуальной машины, к которой относится моментальный снимок;

    list vm

6.9. Устройства хоста

6.9.1. Добавление устройства хоста к виртуальной машине

Чтобы повысить производительность, можно подключить устройство хоста к виртуальной машине.

Устройства хоста — это физические устройства, подключенные к определенной машине хоста, например:

  • накопители на магнитной ленте, диски и чейнджеры SCSI;

  • сетевые карты, графические процессоры, HBA-адаптеры;

  • мыши, камеры и диски с USB-интерфейсом;

Добавить устройство хоста к виртуальной машине можно через закладку Устройства хоста (Host Devices) её подробного представления. Сначала выберите один из хостов кластера и тип устройства. Затем выберите и подключите одно или несколько устройств хоста на этом хосте.

При изменении настройки через кнопку Прикрепить к другому хосту (Pin to another host) удаляются текущие устройства хоста. Когда эти изменения сохраняются в настройках Хост (Host) виртуальной машины, параметр Запустить на (Start Running On) переключается в значение Указанном хосте (Specific Host(s)) и задает хост, который был выбран ранее через настройку Прикрепить к другому хосту (Pin to another host).

После подключения одного или нескольких устройств хоста, запустите виртуальную машину, чтобы изменения вступили в силу. Виртуальная машина запускается на хосте, у которого есть подключенные устройства хоста. Если виртуальная машина не может запуститься на указанном хосте или получить доступ к устройству хоста, то она отменяет операцию запуска и показывает сообщение об ошибке с информацией о причине отмены.

Предварительные условия:

  • Статус хоста Включено (Up) .

  • Хост настроен на прямое назначение устройств.

Порядок действий:

  1. На Портале администрирования нажмите .

  2. Выключите виртуальную машину.

  3. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  4. Откройте вкладку Устройства хоста (Host Devices).

  5. Нажмите Добавить устройство (Add device). Откроется окно Добавить устройства хоста (Add Host Devices).

  6. Используйте параметр Хост (Pinned Host), чтобы выбрать хост, на котором будет работать виртуальная машина.

  7. Используйте параметр Совместимость (Capability), чтобы открыть список устройств pci, scsi, nvdimm или usb_device.

    Параметр nvdimm — это предварительная версия функции, представленная для оценки. Дополнительные сведения см. Устройства хоста NVDIMM.
  8. Выберите устройства через Доступные устройства хоста (Available Host Devices).

  9. Нажмите стрелку вниз , чтобы перенести устройства в Подключаемые устройства хоста (Host Devices to be attached).

  10. Нажмите OK, чтобы подключить эти устройства к виртуальной машине и закрыть окно.

  11. Дополнительно: при подключении хост-устройств SCSI настройте наиболее подходящий драйвер.

    1. Нажмите Изменить (Edit). Откроется окно Изменить виртуальную машину (Edit Virtual Machine).

    2. Откройте вкладку Доп. параметры (Custom Properties).

    3. Нажмите Выберите ключ (Please select a key) и выберите scsi_hostdev внизу выпадающего списка.

    4. В большинстве случаев выбирайте scsi-hd. В остальных случаях, а именно для накопителей на магнитной ленте или CD-чейнджеров, выбирайте параметр scsi_generic. Дополнительные сведения см. в разделе Описание настроек пользовательских свойств виртуальных машин.

    5. Нажмите кнопку ОК.

  12. Запустите виртуальную машину.

  13. Пока виртуальная машина запускается, посмотрите сообщения об ошибках Отмененные операции (Operation Canceled).

Поиск и устранение неполадок

Если не получается добавить устройство хоста к виртуальной машине, или виртуальная машина не запускается с подключенными устройствами хоста, то появятся сообщения об ошибках Отмененные операции (Operation Canceled). Например:

Operation Canceled
Error while executing action:

<vm name>:
* Cannot run VM. There is no host that satisfies current scheduling constraints. See below for details:
* The host <first_hostname> did not satisfy internal filter HostDevice because it does not support host device passthrough.
* The host <second_hostname> did not satisfy internal filter HostDevice because the host does not provide requested host devices.

Ошибку можно устранить, удалив устройство хоста из виртуальной машины или исправив проблемы, о которых говорится в сообщении об ошибке. Например:

  • В ответ на сообщение The host <hostname> did not satisfy internal filter HostDevice because it does not support host device passthrough (Хост <имя хоста> не прошел внутренний фильтр HostDevice, поскольку он не поддерживает сквозной доступ устройств хоста) настройте сквозной доступ устройств на хосте и перезапустите виртуальную машину.

  • В ответ на сообщение The host <hostname> did not satisfy internal filter HostDevice because the host does not provide requested host devices (Хост <имя хоста> не прошел внутренний фильтр HostDevice, поскольку хост не предоставляет запрашиваемые устройства хоста) добавьте устройство на хост.

  • В ответ на сообщение Cannot add Host devices because the VM is in Up status (Невозможно добавить устройства хоста, поскольку виртуальная машина находится во включенном состоянии) выключите виртуальную машину перед добавлением устройства хоста.

  • Проверьте, что статус хоста Включено (Up) .

6.9.2. Удаление устройств хоста из виртуальной машины

Необязательно удалять все устройства хоста, непосредственно подключенные к виртуальной машине, чтобы добавить устройства с другого хоста. Достаточно добавить устройства с нужного хоста, при этом все устройства, уже подключенные к виртуальной машине, удалятся автоматически.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Устройства хоста (Host Devices), чтобы открыть список устройств хоста, подключенных к виртуальной машине.

  4. Выберите устройство хоста, которое необходимо отключить от виртуальной машины, или, зажав клавишу Ctrl, выберите несколько устройств и нажмите Удалить устройство (Remove device). Откроется окно Удалить устройство(-а) хоста (Remove Host Device(s)).

  5. Нажмите OK, чтобы подтвердить и отключить выбранные устройства от виртуальной машины.

6.9.3. Закрепление виртуальной машины на другом хосте

Можно открыть вкладку Устройства хоста (Host Devices) в подробном представлении виртуальной машины, чтобы закрепить ее на конкретном хосте. Если к виртуальной машине подключены какие-либо устройства хоста, то ее закрепление на другом хосте автоматически удаляет устройства хоста из виртуальной машины.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя виртуальной машины, чтобы открыть её подробное представление.

  3. Откройте вкладку Устройства хоста (Host Devices).

  4. Нажмите Прикрепить к другому хосту (Pin to another host). Откроется окно Прикрепить ВМ к хосту (Pin VM to Host).

  5. В выпадающем меню Хост (Host) выберите хост.

  6. Нажмите OK, чтобы закрепить виртуальную машину на выбранном хосте.

6.9.4. Устройства хоста NVDIMM

Устройства NVDIMM — это предварительная версия технологии, представленная только для оценки (Technology Preview) и не обеспечиваются технической поддержкой. OrionSoft не рекомендует использовать их в продуктивной среде.

Можно добавить эмулируемые устройства NVDIMM к виртуальным машинам. Этот тип памяти также известен под названием виртуальный NVDIMM (virtual NVDIMM) или vNVDIMM. Работу эмулируемого устройства NVDIMM, которое можно подключить к виртуальной машине, обеспечивает реальное устройство NVDIMM на том хосте, где работает виртуальная машина. Поэтому, прикрепление NVDIMM к виртуальной машине также привязывает виртуальную машину к определенному хосту. Можно перенастроить режим, разбиение на разделы и другие свойства эмулируемого устройства NVDIMM в виртуальной машине, не затрагивая настройки физического NVDIMM на устройстве хоста. Чтобы добавить эмулируемое устройство NVDIMM к виртуальной машине, см. раздел Добавление устройства хоста к виртуальной машине.

Ограничения

  • Моментальные снимки памяти отключены, когда устройство NVDIMM находится в виртуальной машине. Невозможно сделать моментальный снимок содержимого NVDIMM, а моментальный снимок памяти не может работать корректно без соответствующих данных NVDIMM.

  • В zVirt у каждого устройства NVDIMM, переданного на виртуальную машину, есть автоматически назначенная зона меток с фиксированным размером 128 КБ на оборудовании IBM POWER и, кроме того, 128 КБ — это минимальный размер метки, допустимый в QEMU.

  • По умолчанию виртуальная машина использует все устройство NVDIMM. Нельзя настроить размер NVDIMM через виртуальную машину. Для настройки размера необходимо на хосте разбить устройство NVDIMM на разделы и добавить раздел к виртуальной машине.

  • Размер устройства NVDIMM на виртуальной машине может быть несколько меньше, чем на хосте, чтобы подходить под скорректированные размер и соотношение libvirt и QEMU. Необходимо также очень точно подбирать размер, чтобы горячее подключение памяти нормально выполнялось.

  • libvirt и QEMU корректируют свой размер и размещение меток. Изменение этих внутренних соотношений может привести к потере данных.

  • Платформа не поддерживает горячее подключение NVDIMM.

  • Виртуальные машины с устройствами NVDIMM не могут мигрировать, потому что они закреплены на хосте.

  • SELinux на данный момент блокирует доступ к устройствам NVDIMM в режиме devdax.

  • Документация QEMU NVDIMM

6.10. Группы сходства

6.10.1. Группы сходства

Группы сходства (Affinity) помогают определить место работы выбранных виртуальных машин относительно друг друга и указанных хостов. Эта функциональность помогает управлять сценариями разных процессов, чтобы соблюдать лицензионные требования, обеспечивать высокую доступность и аварийное восстановление.

Правило сходства ВМ

Когда создается группу сходства, выбираются виртуальные машины, которые входят в эту группу. Чтобы задать место работы этих виртуальных машин относительно друг друга, включите Правило сходства ВМ (VM Affinity Rule): Положительное правило пытается запускать виртуальные машины вместе на одном хосте, а Отрицательное — отдельно на разных хостах. Если правило не может быть выполнено, результат зависит от того, включен ли модуль веса или фильтра.

Правило сходства хостов

При желании можно добавить хосты к группе сходства. Чтобы задать место работы виртуальных машин в такой группе относительно хостов в этой группе, включите Правило связности хоста (Host Affinity Rule): Положительное правило пытается запускать виртуальные машины на хостах в группе сходства, а Отрицательное — на хостах, которые не входят в группу сходства. Если правило не может быть выполнено, результат зависит от того, включен ли модуль веса или фильтра.

Веса модулей по умолчанию

По умолчанию оба правила обращаются к весу модулей в политике планирования кластера. Используя веса модулей, планировщик стремится выполнить правило, но в любом случае разрешает виртуальным машинам в группе сходства работать, если правило не может быть выполнено.

Например, при положительном Правиле сходства ВМ (VM Affinity Rule) и включенных весах модулей планировщик стремится запустить все виртуальные машины группы сходства на одном хосте. Однако если у одного хоста недостаточно ресурсов для этого, планировщик запускает виртуальные машины на нескольких хостах.

Чтобы этот модуль работал, в разделе Вес модулей (Weights Modules) политик планирования должны быть ключевые слова VmAffinityGroups и VmToHostsAffinityGroups.

Функция принудительного исполнения и модули фильтров

Оба правила предусматривают возможность Принудительного исполнения (Enforcing), которая применяет модуль фильтра в политике планирования кластера. Модули фильтров переопределяют веса модулей. При включенных модулях фильтров планировщик требует выполнения правила. Если правило не может быть выполнено, модули фильтров не дают запуститься виртуальным машинам в группе сходства.

Например, при положительном Правиле связности хостов (Host Affinity Rule) и включенной функции Принудительного исполнения (Enforcing) (модули фильтра включены) планировщик обязательно будет делать так, чтобы виртуальные машины группы сходства запускались на хостах из группы сходства. Однако если эти хосты выключены, то планировщик вообще не запускает виртуальные машины.

Чтобы этот модуль работал, в разделе Модули фильтров (Filter Modules) политик планирования должны быть ключевые слова VmAffinityGroups и VmToHostsAffinityGroups.

Дополнительные сведения о том, как эти правила и параметры можно сочетать, см. в разделе Примеры групп сходства.

  • По своей функции метка сходства аналогична группе сходства с положительным Правилом связности хостов (Host Affinity Rule) и включенной функцией Принудительно (Enforcing).

  • Чтобы метки сходства работали, в разделе Модули фильтров (Filter Modules) политик планирования должен быть включен хотя бы один фильтр.

  • Если между группой сходства и меткой сходства возникают противоречия, то затрагиваемые виртуальные машины не запускаются. Сведения о предотвращении, устранении и разрешении противоречий см. в разделе Поиск и устранение неполадок в группах сходства.

Веса модулей и Модули фильтров влияют на каждое правило в политике планирования кластера.

  • Чтобы Правило сходства ВМ (VM Affinity Rule) работало, в политике планирования должно быть ключевое слово VmAffinityGroups в разделах Вес модулей (Weights Modules) и Модули фильтров (Filter modules).

  • Чтобы Правило связности хостов (Host Affinity Rule) работало, в политике планирования должно быть ключевое слово VmToHostsAffinityGroups в разделах Вес модулей (Weights Modules) и Модули фильтра (Filter Modules).

  • Группы сходства применяются к виртуальным машинам в кластере. Перемещение виртуальной машины из одного кластера в другой удаляет ее из групп сходства в исходном кластере.

  • Виртуальные машины не нужно перезапускать, чтобы правила групп сходства вступили в силу.

6.10.2. Создание группы сходства

Новые группы сходства можно создавать на Портале администрирования.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы перейти к её подробному представлению.

  3. Откройте вкладку Группы сходства (Affinity Groups).

  4. Нажмите Новая (New).

  5. Введите Имя (Name) и Описание (Description) для группы сходства.

  6. Из выпадающего списка Правило сходства ВМ (VM Affinity Rule) выберите Положительно (Positive) для применения положительного правила сходства или Отрицательно (Negative) для применения отрицательного. Выберите Отключено (Disable), чтобы выключить правило сходства.

  7. Установите флажок Принудительно (Enforcing), чтобы обеспечить принудительное исполнение, или убедитесь, что флажок снят, чтобы принудительное исполнение не применялось.

  8. Из выпадающего списка выберите виртуальные машины, которые нужно добавить в группу сходства. Чтобы добавить или удалить дополнительные виртуальные машины, используйте кнопки и .

  9. Из выпадающего списка Правило связности хоста (Host Affinity Rule) выберите Положительно (Positive) для применения положительного правила сходства или Отрицательно (Negative) для применения отрицательного. Выберите Отключено (Disable), чтобы выключить правило сходства.

  10. Установите флажок Принудительно (Enforcing), чтобы обеспечить принудительное исполнение, или убедитесь, что флажок снят, чтобы принудительное исполнение не применялось.

  11. Из выпадающего списка выберите хосты, которые нужно добавить в группу сходства. Чтобы добавить или удалить дополнительные хосты, используйте кнопки и .

  12. Нажмите OK.

6.10.3. Изменение группы сходства

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы перейти к её подробному представлению.

  3. Откройте вкладку Группы сходства (Affinity Groups).

  4. Нажмите Изменить (Edit).

  5. Установите желаемые значения, используя выпадающие списки Правило сходства ВМ (VM Affinity Rule) и флажки Принудительно (Enforcing), и с помощью кнопок и добавляйте или удаляйте виртуальные машины и/или хосты в или из группы сходства.

  6. Нажмите OK.

6.10.4. Удаление группы сходства

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите на имя виртуальной машины, чтобы перейти к её подробному представлению.

  3. Откройте вкладку Группы сходства (Affinity Groups).

  4. Нажмите Удалить (Remove).

  5. Нажмите OK.

Политика сходства, применявшаяся к виртуальным машинам, которые входили в эту группу сходства, больше не применяется.

6.10.5. Примеры групп сходства

На примерах ниже показано, как применять правила сходства для разных сценариев, используя разные возможности групп сходства, описанные в этой главе.

Пример 2. Высокая доступность

Евгения работает инженером DevOps в стартапе. Для обеспечения высокой доступности две виртуальные машины определенной системы должны работать на разных хостах в кластере.

Евгения создает группу сходства с именем «high availability ABC» и делает следующее:

  • Добавляет эти две виртуальные машины: VM01 и VM02 в группу сходства.

  • Задает Правило сходства ВМ (VM Affinity Rule) как Отрицательно (Negative), чтобы виртуальные машины старались запускаться на разных хостах.

  • Оставляет флажок Принудительно (Enforcing) снятым (отключенным), чтобы обе виртуальные машины могли продолжить работу, если во время сбоя будет доступен только один хост.

  • Оставляет список Хосты (Hosts) пустым, чтобы виртуальные машины запускались на любом хосте в кластере.

Пример 3. Производительность

Сидор разрабатывает ПО и использует две виртуальные машины для сборки ПО и его многократного ежедневного тестирования. Между этими двумя виртуальными машинами идет интенсивный сетевой трафик. Благодаря работе машин на одном и том же хосте снижается как сетевой трафик, так и влияние задержки сети на процесс сборки и тестирования. Использование хостов с лучшими характеристиками (ЦП с более высокой скоростью, SSD, больший объем памяти) позволяет ускорить процесс.

Сидор создает группу сходства с именем «build and testing ABC» и делает следующее:

  • Добавляет виртуальные машины для сборки и тестирования VM01 и VM02 в группу сходства.

  • Добавляет хосты с лучшими характеристиками host03, host04 и host05 в группу сходства.

  • Задает Правило сходства ВМ (VM Affinity Rule) как Положительно (Positive), чтобы виртуальные машины старались запускаться на одном и том же хосте, что снизит сетевой трафик и влияние задержки.

  • Задает Правило связности хоста (Host affinity Rule) как Положительно (Positive), чтобы виртуальные машины старались запускаться на хостах с лучшими характеристиками для ускорения процесса.

  • Оставляет флажок Принудительно (Enforcing) снятым (отключенным) для обоих правил, чтобы виртуальные машины могли запускаться, если хосты с лучшими характеристиками не доступны.

Пример 4. Лицензирование

Афанасий — менеджер по программным активам, который помогает своей организации соблюдать требования вендорской ограничительной лицензии на ПО для 3D-визуализации. По условиям лицензии, виртуальные машины для сервера лицензий VM-LS и рабочие станции визуализации VM-WS# должны работать на одном и том же хосте. Кроме того, согласно модели лицензирования по физическим ЦП, требуется, чтобы рабочие станции работали на одном из двух GPU-хостов: основном host-gpu-primary или резервном host-gpu-backup.

Для удовлетворения этих требований Афанасий создает группу сходства с именем «seismic 3D images ABC» и делает следующее:

  • Добавляет ранее упомянутые виртуальные машины и хосты в группу сходства.

  • Задает Правило сходства ВМ (VM Affinity Rule) как Положительно (Positive) и ставит флажок Принудительно (Enforcing), чтобы сервер лицензий и рабочие станции обязательно запускались вместе на одном из хостов, а не на разных хостах.

  • Задает Правило связности хоста (Host affinity Rule) как Положительно (Positive) и ставит флажок Принудительно (Enforcing), чтобы виртуальные машины обязательно запускались на одном из двух GPU-хостов, а не на других хостах в кластере.

6.10.6. Поиск и устранение неполадок в группах сходства

Чтобы предотвратить возникновение проблем с группами сходства:

  • Спланируйте и задокументируйте ожидаемые сценарии и результаты от использования групп сходства

  • Проверьте и протестируйте результаты при разных условиях.

  • Применяйте передовые методы управления изменениями.

  • Используйте опцию Принудительно (Enforcing), если требуется.

При обнаружении остановки виртуальных машин:

  • Проверьте, что в кластере есть политика планирования, где разделы Вес модулей (Weights Modules) и Модули фильтров (Filter Modules) содержат VmAffinityGroups и VmToHostsAffinityGroups.

  • Проверьте наличие конфликтов между метками сходства и группами сходства.

При возможных конфликтах между метками сходства и группами сходства:

  • Учитывайте, что метка сходства — это эквивалент группы сходства, у которой Правило связности хоста (Host Affinity Rule) установлено как Положительно (Positive), а Принудительно (Enforcing) включено.

  • Учитывайте, что при конфликте между меткой сходства и группой сходства пересекающийся набор виртуальных машин работать не будет.

  • Определите, возможен ли конфликт:

    • Изучите раздел Модули фильтров (Filter Modules) в политиках планирования кластера. Они должны содержать ключевое слово VmAffinityGroups ИЛИ VmToHostsAffinityGroups. В противном случае конфликт невозможен. (Наличие VmAffinityGroups и VmToHostsAffinityGroups в разделе Вес модулей (Weights Modules) не имеет значения, так как ключевые слова в разделе Модули фильтров (Filter Modules) переопределят их).

    • Изучите группы сходства. В них должно содержаться правило с включенным Принудительно (Enforcing). В противном случае конфликт невозможен.

  • Если конфликт возможен, определите набор виртуальных машин, которые могут быть вовлечены:

    • Изучите метки сходства и группы сходства. Составьте список виртуальных машин, которые входят и в метку сходства, и в группу сходства, где опция Принудительное исполнение (Enforcing) включена.

    • Для каждого хоста и виртуальной машины в пересекающемся наборе проанализируйте условия, при которых может произойти конфликт.

  • Определите, совпадают ли неработающие виртуальные машины с виртуальными машинами в анализе.

  • Наконец, реструктурируйте группы сходства и метки сходства, чтобы избежать непреднамеренных конфликтов.

  • Проверьте, что любые изменения приводят к ожидаемым результатам в разных условиях.

  • При наличии перекрывающихся групп сходства и меток сходства их проще просматривать в одном месте как группы сходства. Рассмотрите возможность преобразования метки сходства в эквивалентную группу сходства, где Правило связности хоста (Host Affinity Rule) задано как Положительно (Positive) и включено Принудительно (Enforcing).

6.11. Метки сходства

6.11.1. О метках сходства

Метки сходства можно создавать и модифицировать на Портале администрирования.

Метки сходства (Affinity Labels) используются вместе с Группами сходства (Affinity Groups) для установки любого вида сходства между виртуальными машинами и хостами (жесткая, мягкая, положительная, отрицательная). Смотрите раздел Группы сходства для получения больше информации о степени сходства.

Метки сходства являются подмножеством групп сходства и могут с ними конфликтовать. В случае конфликта виртуальная машина не запустится.

6.11.2. Создание метки сходства

Метки сходства можно создать из подробного представления виртуальной машины, хоста или кластера. В данном конкретном случае используется подробное представление кластера.

Порядок действий:

  1. Нажмите и выберите соответствующий кластер.

  2. Нажмите на имя кластера, чтобы перейти к его подробному представлению.

  3. Откройте вкладку Метки сходства (Affinity Labels).

  4. Нажмите Новый (New).

  5. Введите Имя (Name) для метки сходства.

  6. Из выпадающих списков выберите виртуальные машины и хосты, которые будут ассоциированы с меткой. Для добавления дополнительных виртуальных машин и хостов используйте кнопку .

  7. Нажмите OK.

6.11.3. Изменение метки сходства

Метки сходства можно изменить из подробного представления виртуальной машины, хоста или кластера. В данном конкретном случае используется подробное представление кластера.

Порядок действий:

  1. Нажмите и выберите соответствующий кластер.

  2. Нажмите на имя кластера, чтобы перейти к его подробному представлению.

  3. Откройте вкладку Метки сходства (Affinity Labels).

  4. Выберите метку, которую хотите изменить.

  5. Нажмите Изменить (Edit).

  6. Для добавления или удаления виртуальных машин и хостов в или из метки сходства используйте кнопки и .

  7. Нажмите OK.

6.11.4. Удаление метки сходства

Метки сходства можно удалить только из подробного представления кластера.

Порядок действий:

  1. Нажмите и выберите соответствующий кластер.

  2. Нажмите на имя кластера, чтобы перейти к его подробному представлению.

  3. Откройте вкладку Метки сходства (Affinity Labels).

  4. Выберите метку, которую хотите удалить.

  5. Нажмите Изменить (Edit).

  6. Для удаления всех виртуальных машин и хостов из метки сходства используйте кнопку .

  7. Нажмите OK.

  8. Нажмите Удалить (Delete).

  9. Нажмите OK.

6.12. Экспортирование и импортирование виртуальных машин и шаблонов

Сущность «экспорт-домен» считается устаревшей. Экспорт-домены можно отключить от центра данных и импортировать в другой центр данных в той же или другой среде. Затем виртуальные машины, «плавающие» виртуальные диски и шаблоны можно выгрузить из импортированного домена хранения в подключенный центр данных.

Виртуальные машины и шаблоны можно экспортировать или импортировать в центр данных в той же или другой среде zVirt. Виртуальные машины можно экспортировать или импортировать, используя домен экспорта, домен данных или хост zVirt. При экспортировании или импортировании виртуальной машины или шаблона сохраняются свойства, включая основные сведения такие, как имя и описание, выделение ресурсов и настройки высокой доступности виртуальной машины или шаблона. Разрешения и роли пользователей виртуальных машин и шаблонов включены в OVF-файлы, поэтому когда домен хранения отключается от одного центра данных и подключается к другому, виртуальные машины и шаблоны могут быть импортированы со своими изначальными разрешениями и ролями пользователей. Чтобы разрешения были успешно зарегистрированы, пользователи и роли, связанные с разрешениями виртуальных машин или шаблонов, должны существовать в центре данных до начала процесса регистрации.

Функцию V2V можно использовать для импорта виртуальных машин от других провайдеров сервисов виртуализации (Xen или VMware) или импорта виртуальных машин Windows. Функция V2V преобразует виртуальные машины, обеспечивая возможность их размещения на хостах zVirt.

Виртуальные машины необходимо выключить перед импортированием.

6.12.1. Экспортирование виртуальной машины в домен экспорта

Экспортируйте виртуальную машину в домен экспорта, чтобы ее можно было импортировать в другой центр данных. Сначала обязательно убедитесь, что домен экспорта подключен к центру данных, в котором находится экспортируемая виртуальная машина.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите и затем Экспорт в экспорт-домен (Export to Export Domain).

  3. При желании установите следующие флажки в окне Экспорт ВМ (Export Virtual Machine):

    • Перезаписать принудительно (Force Override): перезаписывает существующие образы виртуальной машины в домене экспорта.

    • Свернуть снимки (Collapse Snapshots): создает единый том экспорта на каждый диск. Эта функция удаляет точки для восстановления с моментальных снимков и добавленные шаблоны в виртуальную машину, созданную на базе шаблона, а также удаляет любые зависимости виртуальной машины от шаблона. Для виртуальной машины, зависимой от шаблона, стоит либо выбрать эту функцию, экспортировать шаблон с виртуальной машиной, либо убедиться, что шаблон существует в центре данных, являющемся приемником.

    Создавая виртуальную машину из шаблона через и Новая ВМ (New VM), появится две опции выделения хранилища в разделе Тип диска (Storage Allocation) на вкладке Выделение ресурсов (Resource Allocation):

    • Если выбрана опция Клонированный (Clone), то виртуальная машина не зависит от шаблона. Шаблон не обязательно должен существовать в центре данных, являющемся приемником.

    • Если выбрана опция Тонкий (Thin), то виртуальная машина зависит от шаблона, поэтому шаблон должен существовать в центре данных, являющемся приемником, или быть экспортирован с виртуальной машиной. Либо установите флажок Свернуть снимки (Collapse Snapshots), чтобы свернуть диск шаблона и виртуальный диск в единый диск.

    Чтобы посмотреть, какая опция была выбрана, нажмите на имя виртуальной машины и откройте вкладку Общие (General) в подробном представлении.

  4. Нажмите OK.

Начнется экспорт виртуальной машины. Во время экспортирования виртуальная машина отображается в со статусом Образ заблокирован (Image Locked) . Процесс может длиться до часа в зависимости от размера образов жесткого диска виртуальной машины и оборудования хранилища. Откройте вкладку События (Events) для просмотра прогресса. По завершении процесса виртуальная машина экспортирована в домен экспорта и отображается на вкладке Импортировать ВМ (VM Import) подробного представления домена экспорта.

6.12.2. Экспортирование виртуальной машины в домен данных

Виртуальную машину можно экспортировать в домен данных для хранения клона виртуальной машины в качестве резервной копии.

При экспортировании виртуальной машины, зависимой от шаблона, в целевом домене хранения должен быть этот шаблон.

Создавая виртуальную машину из шаблона через и Новая ВМ (New VM), появится две опции выделения хранилища в разделе Тип диска (Storage Allocation) на вкладке Выделение ресурсов (Resource Allocation):

  • Если выбрана опция Клонированный (Clone), то виртуальная машина не зависит от шаблона. Шаблон не обязательно должен существовать в центре данных, являющемся приемником.

  • Если выбрана опция Тонкий (Thin), то виртуальная машина зависит от шаблона, поэтому шаблон должен существовать в центре данных, являющемся приемником, или быть экспортирован с виртуальной машиной. Либо установите флажок Свернуть снимки (Collapse Snapshots), чтобы свернуть диск шаблона и виртуальный диск в единый диск.

Чтобы посмотреть, какая опция была выбрана, нажмите на имя виртуальной машины и откройте вкладку Общие (General) в подробном представлении.

Предварительные условия:

  • Домен данных подключен к центру данных.

  • Виртуальная машина выключена.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Экспортировать (Export).

  3. Укажите имя экспортируемой виртуальной машины.

  4. Выберите Домен хранения (Storage domain) из списка.

  5. При желании установите флажок Удалить моментальные снимки (Collapse snapshots), чтобы экспортировать виртуальную машину без моментальных снимков.

  6. Нажмите OK.

Менеджер управления клонирует виртуальную машину, включая все ее диски, в целевой домен.

При перемещении диска из домена данных одного типа в домен данных другого формат диска меняется соответственно. Например, если диск в домене данных NFS и в формате динамического выделения/Тонкий (thin) перемещается в домен iSCSI, то его формат поменяется на предварительно размеченный. Процедура отличается от использования домена экспорта потому, что домен экспорта имеет тип NFS.

Во время экспортирования виртуальная машина отображается со статусом Образ заблокирован (Image Locked) . Процесс может длиться до часа в зависимости от размера образов жесткого диска виртуальной машины и оборудования хранилища. Откройте вкладку События (Events) для просмотра прогресса. По завершении процесса виртуальная машина экспортирована в домен данных и отображается в списке виртуальных машин.

Дополнительные ресурсы:

  • Создание виртуальной машины на основе шаблона.

6.12.3. Импортирование виртуальной машины из домена экспорта

В домене экспорта находится виртуальная машина. Прежде чем виртуальную машину можно будет импортировать в новый центр данных, домен экспорта должен быть подключен к центру данных, являющемуся приемником.

Порядок действий:

  1. Нажмите и выберите домен экспорта. У домена экспорта должен быть статус Активный (Active).

  2. Нажмите на имя домена экспорта, чтобы перейти к его подробному представлению.

  3. Откройте вкладку Импортировать ВМ (VM Import), чтобы вывести список виртуальных машин, доступных для импорта.

  4. Выберите одну или несколько виртуальных машин для импорта. При обнаружении в среде виртуализации виртуальных машин с такими же именами, одноимённые импортируемые виртуальные машины будут обозначены значком рядом с именем. Введите уникальные имена для каждой из них.

  5. Выберите Целевой кластер (Target Cluster).

  6. Установите флажок Свернуть снимки (Collapse Snapshots), чтобы удалить точки для восстановления с моментальных снимков и добавить шаблоны в виртуальную машину, созданную на основе шаблона.

  7. Нажмите на виртуальную машину, которую нужно импортировать, и откройте вложенную вкладку Диски (Disks). На этой вкладке можно использовать выпадающие списки Политика выделения (Allocation Policy) и Домен хранения (Storage Domain), чтобы выбрать, будет ли у диска, используемого виртуальной машиной, динамическое или предварительное выделение пространства, а также можно выбрать домен хранения на котором он будет храниться. Также отображается значок, обозначающий, какой из дисков на импорт ведет себя как загрузочный диск для виртуальной машины.

  8. Нажмите OK , чтобы импортировать виртуальные машины.

За одну операцию можно импортировать только виртуальные машины, у которых одна и та же архитектура. Если среди виртуальных машин, которые нужно импортировать, хотя бы у одной из них архитектура отличается, появится предупреждение, и система предложит изменить выбор, чтобы импортировались только виртуальные машины с одной и той же архитектурой.

6.12.4. Импортирование виртуальной машины из домена данных

Виртуальную машину можно импортировать в один или несколько кластеров из домена хранения данных.

Предварительное условие:

  • При импортировании виртуальной машины из импортированного домена хранения данных он должен быть подключен к центру данных и активирован.

Порядок действий:

  1. Нажмите .

  2. Нажмите на имя импортированного домена хранения, чтобы открыть его подробное представление.

  3. Откройте вкладку Импортировать ВМ (VM Import).

  4. Выберите одну или несколько виртуальных машин для импорта. При обнаружении в среде виртуализации виртуальных машин с такими же именами, одноимённые импортируемые виртуальные машины будут обозначены значком рядом с именем. Введите уникальные имена для каждой из них.

  5. При обнаружении конфликта с MAC-адресом появится восклицательный знак рядом с именем виртуальной машины. Наведите указатель мыши на значок для просмотра подсказки, которая отображает тип возникшей ошибки.

  6. Для каждой виртуальной машины в окне Импорт ВМ (Import Virtual Machine(s)) убедитесь, что в списке Кластер (Cluster) выбран правильный целевой кластер.

    vm import

  7. Сопоставьте внешние vNIC-профили виртуальных машин с профилями в целевом кластере (кластерах):

    1. Нажмите Сопоставление vNIC-профилей (vNic Profiles Mapping).

    2. Выберите vNIC-профиль в выпадающем списке Целевой профиль vNIC (Target vNic Profile).

    3. Если в окне Импортировать виртуальную(ые) машину(ы) (Import Virtual Machine(s)) выбрано несколько целевых кластеров, то выберите каждый целевой кластер в выпадающем списке Целевой кластер (Target Cluster) и убедитесь в корректности сопоставления.

  8. Нажмите OK.

    Если доступных адресов для переназначения нет, то выполнить операцию импортирования не удастся. Однако в случае с MAC-адресами, находящимися вне диапазона пула MAC-адресов кластера, виртуальную машину можно импортировать без повторного назначения нового MAC-адреса.
  9. Нажмите OK.

6.12.5. Импортирование виртуальной машины из провайдера VMware

Импортируйте виртуальные машины из провайдера VMware vCenter в среду zVirt. Для импорта из провайдера VMware необходимо ввести данные в окне Импорт ВМ (Import Virtual Machine(s)) в процессе каждой операции импорта или можно добавить провайдера VMware в качестве внешнего провайдера и выбрать предварительно сконфигурированного провайдера во время операций импорта.

zVirt использует инструмент v2v для импорта виртуальных машин VMware (предоставляется пакетом virt-v2v). Для файлов OVA zVirt поддерживает диски только в формате VMDK.

При неудачной попытке импорта см. подробные сведения в соответствующем файле журналов /var/log/vdsm/import/ и /var/log/vdsm/vdsm.log на прокси-хосте.

Предварительные условия:

  • Как минимум один домен данных должен быть подключены к центру данных.

    Мигрировать можно только в общие хранилища, например, NFS, iSCSI или FCP. Локальные хранилища не поддерживаются.

  • Файл образа virtio-win_version.iso для виртуальных машин Windows выгружается в домен хранения. Этот образ включает в себя гостевые инструменты, необходимые для миграции виртуальных машин Windows.

  • Виртуальную машину необходимо выключить перед импортом. Запуск виртуальной машины VMware в процессе импорта может привести к повреждению данных.

  • Импортировать можно только виртуальные машины с одинаковой архитектурой. Если у какой-либо импортируемой виртуальной машины другая архитектура, то появится предупреждение, и система предложит изменить выборку, чтобы в ней были только виртуальные машины с одинаковой архитектурой.

Порядок действий:

  1. Нажмите .

  2. Нажмите и выберите Импортировать (Import). Откроется окно Импорт ВМ (Import Virtual Machine(s)).

  3. Выберите VMware из списка Источник (Source).

  4. Если провайдер VMware настроен в качестве внешнего провайдера, то выберите его из списка Внешний провайдер (External Provider). Убедитесь, что учетные данные провайдера верны. Если при настройке внешнего провайдера вы не указали центр данных, являющийся приемником, или прокси-хост, то выберите эти параметры сейчас.

  5. Если провайдер VMware еще не настроен или данные импортируются из нового провайдера VMware, введите следующую информацию:

    1. Выберите из списка Центр данных (Data Center), в котором будет доступна виртуальная машина.

    2. Введите IP-адрес или FQDN экземпляра VMware vCenter в поле vCenter.

    3. Введите IP-адрес или FQDN хоста, из которого будут импортироваться виртуальные машины, в поле ESXi.

    4. Введите имя центра данных и кластера, в которых находится указанный хост ESXi, в поле Центр данных (Data Center).

    5. Если происходил обмен SSL-сертификатом между хостом ESXi и Менеджером управления, то оставьте флажок Проверка SSL-сертификата сервера (Verify server’s SSL certificate) установленным, чтобы проверять сертификат хоста ESXi. В противном случае снимите флажок.

    6. Введите Имя пользователя (Username) и Пароль (Password) для экземпляра VMware vCenter. Пользователь должен иметь доступ к центру данных VMware и хосту ESXi, на котором находятся виртуальные машины.

    7. Выберите хост в выбранном центре данных с установленным пакетом virt-v2v, который будет служить Прокси-хостом (Proxy Host) во время операций импорта виртуальных машин. Этот хост также должен быть способен подключаться к сети внешнего провайдера VMware vCenter.

  6. Нажмите Загрузить (Load), чтобы открыть список виртуальных машин на провайдере VMware, которые можно импортировать.

  7. Выберите одну или несколько виртуальных машин из списка Виртуальные машины на источнике (Virtual Machines on Source) и с помощью стрелок переместите их в список Виртуальные машины для импорта (Virtual Machines to Import). Нажмите Далее (Next).

    Если сетевое устройство виртуальной машины использует тип драйвера e1000 или rtl8139, то виртуальная машина будет использовать тот же тип драйвера после импорта в zVirt.

    При необходимости можно после импорта вручную изменить тип драйвера на VirtIO. Сведения о том, как изменить тип драйвера после импорта виртуальной машины, см. в разделе Изменение сетевого интерфейса. Если сетевое устройство использует другой тип драйвера (не e1000 или rtl8139), то этот тип драйвера автоматически меняется на VirtIO во время импорта. Параметр Подключить CD (Attach VirtIO-drivers) позволяет внедрить драйверы VirtIO в файлы импортированной виртуальной машины, чтобы при смене драйвера на VirtIO операционная система правильно обнаружила устройство.

  8. Выберите Целевой кластер (Target Cluster), на котором будут находиться виртуальные машины.

  9. Выберите Профиль ЦП (CPU Profile) для виртуальных машин.

  10. Установите флажок Свернуть моментальные снимки (Collapse Snapshots), чтобы убрать точки для восстановления с моментальных снимков и добавить шаблоны в виртуальные машины, созданные на основе шаблонов.

  11. Установите флажок Клонировать (Clone), чтобы изменить имена и MAC-адреса виртуальных машин, клонировать все диски и удалить все моментальные снимки. Если рядом с именем виртуальной машины появится знак предупреждения, необходимо клонировать виртуальную машину и изменить ее имя.

  12. Нажмите на каждую виртуальную машину, которую хотите импортировать и в списках Политика выделения (Allocation Policy) и Домен хранения (Storage Domain) выберите, какой диск будет использовать виртуальная машина: с динамическим или предварительным выделением пространства, а также выберите домен хранения, на котором будет храниться диск. Кроме того, во вложенной вкладке Диски (Disks) можно посмотреть какой из импортируемых дисков является загрузочным для выбранной виртуальной машины.

  13. Если установлен флажок Клонировать (Clone), измените имя виртуальной машины на вложенной вкладке Общее (General).

  14. Нажмите OK, чтобы импортировать виртуальные машины.

Тип ЦП виртуальной машины должен совпадать с типом ЦП кластера, на который ее импортируют. Чтобы посмотреть Тип ЦП (CPU Type) кластера на Портале администрирования:

  1. Нажмите .

  2. Выберите кластер.

  3. Нажмите Изменить (Edit).

  4. Откройте вкладку Общее (General).

Если тип ЦП виртуальной машины отличается, настройте тип ЦП импортируемой виртуальной машины:

  1. Нажмите .

  2. Выберите виртуальную машину.

  3. Нажмите Изменить (Edit).

  4. Откройте вкладку Система (System).

  5. Нажмите на стрелку Дополнительные параметры (Advanced Parameters).

  6. Выберите нужный тип ЦП из списка Тип ЦП (Custom CPU).

  7. Нажмите OK.

6.12.6. Экспортирование виртуальной машины на хост

Виртуальную машину можно экспортировать по конкретно заданному пути или в смонтированное общее NFS-хранилище на хосте в центре данных zVirt. В результате экспорта будет создан пакет открытого виртуального устройства (OVA).

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Дополнительные действия , а затем Экспорт в OVA (Export as OVA).

  3. Выберите хост в выпадающем списке Хост (Host).

  4. Введите абсолютный путь к каталогу экспорта в поле Путь (Directory), поставив в конце завершающий слэш. Например: /images2/ova/.

  5. При желании можно изменить имя файла по умолчанию в поле Имя (Name).

  6. Нажмите ОК.

Статус экспорта можно посмотреть на вкладке События (Events).

6.12.7. Импортирование виртуальной машины из хоста

Импортируйте файл виртуальной машины OVA в среду zVirt. Файл можно импортировать из любого хоста zVirt в центре данных.

На текущий момент можно импортировать только файлы zVirt и OVA, созданные VMware. KVM и Xen не поддерживаются. Расположение файла может быть локальным каталогом или удаленным подключением NFS, если оно не находится в каталоге «/root» или подкаталогах. Убедитесь, что достаточно места для размещения файла. Процесс импорта использует virt-v2v. Успешно импортировать можно только те виртуальные машины, которые работают на операционных системах, совместимых с virt-v2v.

Порядок действий:

  1. Скопируйте файл OVA на хост на вашем кластере в расположение файловой системы, например, /var/tmp.

  2. Убедитесь, что файл OVA имеет разрешения на чтение/запись для пользователя qemu (UID 36) и группы kvm (GID 36) или установите владельцев:

    chown 36:36 path_to_OVA_file/file.OVA
  3. Нажмите .

  4. Нажмите и выберите Импортировать (Import). Откроется окно Импорт ВМ (Import Virtual Machine(s)).

    1. Выберите Virtual Appliance (OVA) из списка Источник (Source).

    2. Выберите хост в списке Хост (Host).

    3. В поле Путь (Path) укажите абсолютный путь файла OVA.

    4. Нажмите Загрузить (Load), чтобы открыть список виртуальных машин для импорта.

    5. Выберите виртуальную машину из списка Виртуальные машины на источнике (Virtual Machines on Source) и с помощью стрелки переместите ее в список Виртуальные машины для импорта (Virtual Machines to Import).

  5. Нажмите Далее (Next).

    1. Выберите Домен хранения (Storage Domain) для виртуальной машины.

    2. Выберите Целевой кластер (Target Cluster), на котором будут находиться виртуальные машины.

    3. Выберите Профиль ЦП (CPU Profile) для виртуальных машин.

    4. Выберите Политику выделения (Allocation Policy) для виртуальных машин.

    5. При желании можно установить флажок Подключить CD (Attach VirtIO-drivers) и выбрать подходящий образ из списка, чтобы добавить драйверы VirtIO.

    6. Выберите виртуальную машину и на вкладке Общее (General) выберите Операционную систему (Operating System).

    7. На вкладке Сетевые интерфейсы (Network Interfaces) выберите Имя сети (Network Name) и Имя профиля (Profile Name).

    8. Откройте вкладку Диски (Disks), чтобы посмотреть Имя (Alias), Виртуальный размер (Virtual Size) и Фактический размер (Actual Size) виртуальной машины.

  6. Нажмите OK.

6.12.8. Импортирование виртуальной машины из хоста KVM

Импортируйте виртуальные машины из хоста KVM в среду zVirt. zVirt конвертирует виртуальные машины KVM в корректный формат перед их импортом. Необходимо включить аутентификацию по открытому ключу между хостом KVM и как минимум одним хостом в центре данных, являющимся приемником (этот хост в следующей процедуре называется прокси-хостом).

Виртуальную машину необходимо выключить перед импортом. Запуск виртуальной машины KVM в процессе импорта может привести к повреждению данных.
Импортировать можно только виртуальные машины с одинаковой архитектурой. Если у какой-либо импортируемой виртуальной машины другая архитектура, то появится предупреждение, и система предложит изменить выборку, чтобы в ней были только виртуальные машины с одинаковой архитектурой.
При неудачной попытке импорта см. подробные сведения в соответствующем файле журналов /var/log/vdsm/import/ и /var/log/vdsm/vdsm.log на прокси-хосте.

Порядок действий:

  1. Включите аутентификацию с открытым ключом между прокси-хостом и хостом KVM:

    1. Авторизуйтесь на прокси-хосте и сгенерируйте SSH-ключи для пользователя vdsm.

    2. Скопируйте открытый ключ пользователя vdsm на хост KVM. Файл known_hosts на прокси-хосте также обновится, и в нем появится хост-ключ хоста KVM.

      sudo -u vdsm ssh-copy-id root@kvmhost.example.com
    3. Авторизуйтесь на хосте KVM, чтобы убедиться, что вход в систему работает корректно.

      sudo -u vdsm ssh root@kvmhost.example.com
  2. Авторизуйтесь на Портале администрирования.

  3. Нажмите .

  4. Нажмите и выберите Импортировать (Import). Откроется окно Импорт ВМ (Import Virtual Machine(s)).

  5. Выберите Центр данных (Data Center), на котором содержится прокси-хост.

  6. Выберите KVM (через Libvirt) (KVM (via Libvirt)) из выпадающего списка Источник (Source).

  7. При желании можно выбрать провайдер KVM из выпадающего списка Внешний провайдер (External Provider). Корректный идентификатор URI будет уже проставлен. Дополнительные сведения см. в разделе Добавление хоста KVM в качестве провайдера виртуальных машин в Руководстве администратора.

  8. Введите URI хоста KVM в следующем формате:

    qemu+ssh://root@kvmhost.example.com/system
  9. Оставьте флажок Требуется авторизация (Requires Authentication) установленным.

  10. Введите root в поле Имя пользователя (Username).

  11. Введите Пароль (Password) пользователя root хоста KVM.

  12. Выберите Хост прокси (Proxy Host) в выпадающем списке.

  13. Нажмите Загрузить (Load), чтобы открыть список виртуальных машин на хосте KVM, которые можно импортировать.

  14. Выберите одну или несколько виртуальных машин из списка Виртуальные машины на источнике (Virtual Machines on Source) и с помощью стрелок и поместите их в список Виртуальные машины для импорта (Virtual Machines to Import).

  15. Нажмите Далее (Next).

  16. Выберите Кластер (Cluster), на котором будут находиться виртуальные машины.

  17. Выберите Профиль ЦП (CPU Profile) для виртуальных машин.

  18. При желании установите флажок Свернуть снимки (Collapse Snapshots), чтобы убрать точки для восстановления с моментальных снимков и добавить шаблоны в виртуальные машины, созданные на основе шаблонов.

  19. При желании установите флажок Клонировать (Clone), чтобы изменить имена и MAC-адреса виртуальных машин, клонировать все диски и удалить все моментальные снимки. Если рядом с именем виртуальной машины появится знак предупреждения или место для флажка в столбце ВМ в системе (VM in System), необходимо клонировать виртуальную машину и изменить ее имя.

  20. Нажмите на каждую виртуальную машину, которую хотите импортировать, и откройте вложенную вкладку Диски (Disks). В списках Политика выделения (Allocation Policy) и Домен хранения (Storage Domain) выберите, какой диск будет использовать виртуальная машина: с динамическим или предварительным выделением пространства, а также выберите домен хранения, на котором будет храниться диск. Кроме того, отображается значок, указывающий, какой из импортируемых дисков является загрузочным для выбранной виртуальной машины.

  21. Если установлен флажок Клонировать (Clone), измените имя виртуальной машины на вкладке Общее (General).

  22. Нажмите OK.

Тип ЦП виртуальной машины должен совпадать с типом ЦП кластера, на который ее импортируют. Чтобы посмотреть Тип ЦП (CPU Type) кластера на Портале администрирования:

  1. Нажмите .

  2. Выберите кластер.

  3. Нажмите Изменить (Edit).

  4. Откройте вкладку Общее (General).

Если тип ЦП виртуальной машины отличается, настройте тип ЦП импортируемой виртуальной машины:

  1. Нажмите .

  2. Выберите виртуальную машину.

  3. Нажмите Изменить (Edit).

  4. Откройте вкладку Система (System).

  5. Нажмите на стрелку Дополнительные параметры (Advanced Parameters).

  6. Выберите нужный тип ЦП из списка Тип ЦП (Custom CPU).

  7. Нажмите OK.

6.13. Миграция виртуальных машин между хостами

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

Виртуальную машину, которая использует виртуальный графический процессор (vGPU), нельзя переместить на другой хост.

6.13.1. Предварительные условия для живой миграции

Живая миграция используется для плавного перемещения виртуальных машин в рамках ряда типовых задач обслуживания. Среда zVirt должна быть заранее правильно настроена на поддержку живой миграции виртуальных машин. Для успешной живой миграции виртуальных машин должны быть выполнены как минимум следующие предварительные условия:

  • Статус хоста-источника и хоста-приемника: Включено (Up) .

  • У хоста-источника и хоста-приемника есть доступ к одним и тем же виртуальным сетям и VLAN.

  • У хоста-источника и хоста-приемника есть доступ к домену хранения данных, в котором находится виртуальная машина.

  • Хост-источник и хост приемник имеют ЦП одного производителя.

  • Мощности ЦП хоста-приемника достаточно для обеспечения работы виртуальной машины.

  • У хоста-приемника достаточно неиспользуемой оперативной памяти для обеспечения работы виртуальной машины.

  • На перемещаемой виртуальной машине не установлено пользовательское свойство viodiskcache (вкладка Доп. параметры в окне создания/изменения ВМ).

  • При наличии плавающих адресов у мигрируемой ВМ необходимо, чтобы кластер назначения был в составе SDN.

    Если кластер назначения имеет «Тип коммутатора» — «Мост», то миграция ВМ будет выполнена, но плавающий адрес не будет перенесен.

Живая миграция выполняется с помощью сети и предполагает передачу больших объемов данных между хостами. Одновременные миграции могут привести к перегрузке сети управления. Для достижения наилучшей производительности создайте отдельные логические сети для управления, хранения, отображения и миграции данных виртуальных машин, чтобы минимизировать риск перегрузки сети.

6.13.2. Настройка виртуальных машин с виртуальными сетевыми картами с включенным SR-IOV для уменьшения времени неработоспособности сети во время миграции

Виртуальные машины с виртуальными сетевыми картами, которые напрямую подключены к виртуальной функции сетевой карты хоста с включенным SR-IOV, можно дополнительно настроить для уменьшения времени неработоспособности сети во время живой миграции:

  1. Убедитесь, что у хоста-приемника есть доступная виртуальная функция.

  2. Установите параметры Passthrough и Мигрируемый (Migratable) в vNIC-профиле со сквозным доступом.

  3. Включите горячее подключение для сетевого интерфейса виртуальной машины.

  4. Убедитесь, что у виртуальной машины есть резервная виртуальная сетевая карта VirtIO в дополнение к виртуальной сетевой карте со сквозным доступом, чтобы поддерживать сетевое подключение виртуальной машины во время миграции.

  5. Перед настройкой bond-интерфейса установите параметр виртуальной сетевой карты VirtIO Без сетевых фильтров (No Network Filter) . См. раздел Описание настроек в окне «Профиль интерфейса (Interface Profile)» в Руководстве по администрированию ресурсов zVirt.

  6. Добавьте обе виртуальные сетевые карты в качестве ведомых в bond-интерфейс active-backup на виртуальной машине, при этом виртуальная сетевая карта со сквозным доступом будет основным интерфейсом.

    Профили bond-интерфейсов и виртуальных сетевых карт можно настроить одним из следующих способов:

    • На bond-интерфейсе не настроен fail_over_mac=active, а виртуальная функция виртуальной сетевой карты — основной ведомый (slave) (рекомендуется). Отключите фильтр спуфинга MAC-адресов в vNIC-профиле VirtIO, чтобы трафик, проходящий через виртуальную сетевую карту VirtIO, не отбрасывался из-за использования MAC-адреса виртуальной функции виртуальной сетевой карты.

    • На bond-интерфейсе настроено fail_over_mac=active. Такая политика обработки отказа гарантирует, что MAC-адрес bond-интерфейса всегда будет MAC-адресом активного ведомого. При обработке отказа MAC-адрес виртуальной машины меняется, что приводит к небольшому нарушению трафика.

6.13.3. Настройка виртуальных машин с виртуальными сетевыми картами с включенным SR-IOV и минимальным временем простоя

Чтобы настроить виртуальные машины для миграции с виртуальными сетевыми картами с включенным SR-IOV и минимальным временем простоя, следуйте описанной ниже процедуре.

Следующие шаги — это предварительная версия технологии, представленная только для оценки (Technology Preview).
  1. Создайте vNIC-профиль с виртуальными сетевыми картами с включенным SR-IOV. См. Создание или изменение профилей vNIC и Установка и настройка SR-IOV в руководстве администратора.

  2. На Портале администрирования перейдите в раздел , выберите vNIC-профиль, нажмите Изменить (Edit) и выберите vNIC-профиль аварийного переключения (Failover vNIC profile) из выпадающего списка.

  3. Нажмите OK, чтобы сохранить настройки профиля.

  4. Выполните горячее подключение сетевого интерфейса с созданным vNIC-профилем аварийного переключения к виртуальной машине или запустите виртуальную машину с подключенным сетевым интерфейсом.

    У виртуальной машины есть три сетевых интерфейса: интерфейс контроллера и два вспомогательных интерфейса. Интерфейс контроллера должен быть активным и подключенным, чтобы миграция прошла успешно.
  5. Для автоматического развертывания виртуальных машин с такой конфигурацией используйте следующее правило udev:

    SUBSYSTEM=="net",
    ACTION=="add|change",
    ENV{ID_NET_DRIVER}!="net_failover",
    NM_UNMANAGED}="1",
    RUN+="/bin/sh -c '/sbin/ip link set up $INTERFACE'"

    Это правило udev работает только в системах, которые управляют интерфейсами с помощью Менеджера сети (NetworkManager). Это правило гарантирует, что активирован только интерфейс контроллера.

6.13.4. Автоматическая миграция виртуальных машин

Когда хост переводят в режим обслуживания, Менеджер управления автоматически инициирует живую миграцию для всех работающих на этом хосте виртуальных машин. Хост-приемник для каждой виртуальной машины оценивается по мере ее миграции, чтобы распределить нагрузку по кластеру. Однако для высокопроизводительных и/или закрепленных виртуальных машин появляется окно Хост обслуживания (Maintenance Host) с запросом подтвердить действие, поскольку производительность целевого хоста может быть ниже производительности текущего хоста.

Менеджер управления автоматически инициирует живую миграцию виртуальных машин для поддержания уровней балансировки нагрузки или энергосбережения в соответствии с политикой планирования. Укажите политику планирования, которая наилучшим образом отвечает потребностям вашей среды. При необходимости для конкретных виртуальных машин можно отключить автоматическую или даже ручную живую миграцию. Если виртуальные машины настроены на высокую производительность, и/или если они были закреплены (Passthrough ЦП хоста (Pass-Through Host CPU), Привязкой ЦП (CPU Pinning) или Привязкой NUMA (NUMA Pinning)), режим миграции установлен в значение Разрешить только ручную миграцию (Allow manual migration only). Однако при необходимости его можно изменить на режим Разрешить ручную и автоматическую миграцию(Allow manual and automatic migration). При изменении параметров миграции по умолчанию следует соблюдать особую осторожность, чтобы не выполнить миграцию виртуальной машины на хост, который не поддерживает высокую производительность или закрепление.

6.13.5. Блокировка автоматической миграции виртуальной машины

В Менеджере управления можно отключить автоматическую миграцию виртуальных машин. Кроме того, можно отключить ручную миграцию виртуальных машин, настроив виртуальную машину так, чтобы она работала только на определенном хосте.

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

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Хост (Host).

  4. В разделе Запустить на (Start Running On) выберите Любом хосте в кластере (Any Host in Cluster) или Указанном хосте (Specific Host(s)), что позволяет выбрать несколько хостов.

    Прямое назначение виртуальной машины конкретному хосту и отключение миграции взаимно исключают друг друга при работе zVirt в режиме высокой доступности.
    Если к виртуальной машине напрямую подключены устройства хоста, но указан другой хост, то устройства хоста предыдущего хоста будут автоматически удалены из виртуальной машины.
  5. Выберите Разрешить только ручную миграцию (Allow manual migration only) или Не разрешать миграцию (Do not allow migration) в выпадающем списке Параметры миграции (Migration Options).

  6. Нажмите OK.

6.13.6. Ручная миграция виртуальных машин

Работающую виртуальную машину можно перенести на любой хост в центре данных без прерываний работы сервисов. Миграция виртуальных машин на другой хост особенно полезна при чрезмерной нагрузке на определенный хост. Предварительные условия для живой миграции см. в разделе Предварительные условия для живой миграции. У высокопроизводительных виртуальных машин и/или виртуальных машин с Passthrough ЦП хоста (Pass-Through Host CPU), Привязкой ЦП (CPU Pinning) или Привязкой NUMA (NUMA Pinning), режим миграции по умолчанию установлен в значение Разрешить только ручную миграцию (Allow manual mirgation only). Выберите Выбрать хост автоматически (Select Host Automatically), чтобы виртуальная машина мигрировала на хост с максимальной производительностью.

При переводе хоста в режим обслуживания виртуальные машины, работающие на этом хосте, автоматически переносятся на другие хосты в том же кластере. Переносить эти виртуальные машины вручную не требуется.

В zVirt 4.3 и выше для ручной миграции виртуальных машин используется визард миграции. Визард предоставляет следующие функции:

  • Живая миграция только виртуальных машин между хостами в пределах одного центра данных.

  • Миграция только дисков виртуальных машин между доменами хранения в пределах одного центра данных. (перед началом миграции внимательно изучите особенности миграции дисков.)

  • Миграция виртуальных машин и их дисков в пределах одного центра данных.

Порядок действий:

  1. Нажмите и выберите одну или несколько работающих виртуальных машин.

  2. В панели управления нажмите Мигрировать (Migrate).

  3. В открывшемся визарде:

    1. Выберите тип миграции:

      Типы миграции Переместить только диски ВМ и Переместить и ВМ и диски недоступны в случае:

      • Если пользователь не имеет прав на домен хранения;

      • Если домен хранения в кластере один.

      • При необходимости перемещения только виртуальной машины на другой хост, выберите Переместить только ВМ.

      • При необходимости перемещения виртуальной машины на другой хост и её дисков в другой домен хранения, выберите Переместить и ВМ, и диски.

    2. Нажмите Далее и на следующем этапе задайте параметры для миграции ВМ:

      Если выбранные виртуальные машины находятся на разных кластерах, то для миграции переместите их в один кластер или переносите отдельно.

      migration warning cluster 1

      Для исключения ВМ из задачи на миграцию нажмите в строке соответствующей ВМ.

  • Укажите кластер назначения.

    При выполнении миграции между кластерами настройка запуска ВМ на определенных хостах кластера сбрасывается на значение «Любом хосте кластера».

    settings hosts

  • Укажите хост назначения.

  • Если необходимо мигрировать все ВМ с положительной принудительной группой сходства с выбранными виртуальными машинами, активируйте соответствующую опцию.

  • Убедитесь, что список содержит все необходимые виртуальные машины.

migration wizard vm params

  1. Нажмите Далее. Если был выбран тип миграции Переместить и ВМ, и диски, на следующем этапе выберите необходимые диски и укажите параметры их перемещения:

    • При необходимости установите или измените домен аренды для высокодоступных виртуальных машин в столбце Домен аренды. Если необходимо назначить одинаковый домен аренды для всех выбранных виртуальных машин, воспользуйтесь соответствующим меню в верхней панели.

    • В строке нужного диска нажмите . Если целевой домен хранения и профиль одинаковый для нескольких дисков, выделите их и нажмите на в верхней панели.

    • В открывшейся панели укажите целевой домен хранения и профиль диска(ов). Нажмите Сохранить.

    migration wizard disk params

    При наличии большого количества дисков, можно воспользоваться формой поиска в верхней панели. Она позволяет фильтровать диски по:

    • Имени диска.

    • Имени виртуальной машины.

    Если заданы ошибочные параметры перемещения их можно удалить. Для этого нажмите в строке соответствующего диска или в верхней панели, предварительно выделив нужные диски.

  2. На этапе подтверждения информации убедитесь, что задание на миграцию содержит корректный список ВМ и/или дисков, для ВМ указаны правильные кластер и хост назначения, а для дисков целевой домен хранения и профиль.

  3. Нажмите Мигрировать.

Мониторинг задач на миграцию

Для мониторинга созданных задач на миграцию используется страница .

Страница содержит табличное представление списка операций, входящих в задачи на миграцию, с подробным описанием.

migration tasks

Каждая запись в списке содержит следующие параметры:

  • Имя задачи: имя формируется автоматически исходя из типа и количества мигрируемых компонентов (диски/ВМ) и времени запуска процедуры миграции. В списке может присутствовать несколько записей с одинаковым именем. Это указывает на то, что записи описывают разные этапы одной задачи на миграции.

  • Тип: тип задачи на миграцию. Возможны следующие значения:

    • Живая миграция ВМ — запись содержит сведения о миграции ВМ между хостами. Одна задача может содержать несколько записей такого типа, по одной записи на каждую мигрирующую ВМ.

    • Перемещение диска — запись содержит сведения о миграции диска между доменами хранения. Одна задача может содержать несколько записей такого типа, по одной записи на каждый мигрирующий диск.

    • Изменение ВМ — запись содержит сведения об изменении домена аренды ВМ. Одна задача может содержать несколько записей такого типа, по одной записи на каждую ВМ, для которой изменяется домен аренды.

  • Имя объекта: содержит имя связанного объекта (диска/ВМ).

  • Статус: указывает на статус операции. Возможны следующие значения:

    • Выполнена — операция успешно завершена.

    • Отменена — операция отменена пользователем.

    • Ошибка — операция завершилась ошибкой.

    • Выполняется — операция находится в стадии выполнения.

    • Создана — задание на выполнение создано, но операция еще не выполняется. На этом этапе операцию можно отменить (см. ниже).

  • Описание: Содержит подробное описание операции.

  • Пользователь: указывает полное имя пользователя, который инициировал соответствующую задачу на миграцию.

  • Дата начала: дата и время начала операции. Значение может быть пустым в случае отмены операции пользователем.

  • Дата окончания: дата и время окончания операции.

  • Длительность: длительность операции. Указывается только для операций со статусом Выполнена.

Каждая запись в таблице содержит подробное описание операции, а также список связанных событий. Для просмотра описания нажмите в строке с нужной записью.

Информация в подробном описании зависит от типа операции:

  • Для типа Живая миграция ВМ:

    • Кластер источник.

    • Хост источник.

    • Кластер назначения.

    • Хост назначения.

  • Для типа Перемещение диска:

    • Домен хранения источник.

    • Профиль диска источник.

    • Целевой домен хранения.

    • Целевой профиль диска.

  • Для типа Изменение ВМ:

    • Домен хранения для аренды ВМ источник.

    • Целевой домен хранения для аренды ВМ.

На странице просмотра задач на миграцию можно отменить операции, которые не начали выполняться. Для этого нажмите в строке соответствующей записи или выделите несколько записей и нажмите на кнопку отмены в верхней панели.

При отмене операций их восстановление в очереди задач невозможно.

Для облегчения поиска нужных записей в верхней панели доступны различные способы фильтрации:

  • По статусу операции.

  • По типу операции.

  • По имени задачи или объекта.

6.13.7. Настройка приоритета миграции

Менеджер управления ставит в очередь параллельные запросы на миграцию виртуальных машин с заданного хоста. Процесс балансировки нагрузки выполняется каждую минуту. Хосты, уже задействованные в миграции, не включаются в цикл миграции до тех пор, пока их событие миграции не завершится. Когда в очереди есть запрос на миграцию, а в кластере — доступные хосты для его выполнения, запускается событие миграции в соответствии с политикой балансировки нагрузки для кластера.

Порядок очереди миграции можно изменить, назначив приоритет каждой виртуальной машине; например, установить, что критически важные виртуальные машины будут перенесены раньше других. Миграции будут упорядочены по приоритету; виртуальные машины с наивысшим приоритетом будут перенесены в первую очередь.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Высокая доступность (High Availability).

  4. Выберите значение Низкий (Low), Средний (Medium) или Высокий (High) из выпадающего списка Приоритет (Priority).

  5. Нажмите OK.

6.13.8. Настройка параллельных соединений для миграции

libvirt и QEMU позволяют использовать несколько параллельных соединений для одной миграции (QEMU называет эту функцию multifd ). При наличии одного соединения для миграции и достаточной пропускной способности сети один поток миграции может стать узким местом из-за ограниченной мощности одного процессора. Используя несколько соединений, обслуживаемых несколькими потоками, выполняемыми несколькими процессорами, можно использовать полную мощность сети. Например, 8-16 соединений могут задействовать пропускную способность сети 100 Гбит/с.

Кроме того, реализация передачи данных multifd проще и эффективнее, чем традиционный механизм миграции, и может работать быстрее даже при более низкой пропускной способности сети.

  • Поскольку пропускную способность сети легче перегрузить несколькими соединениями, не рекомендуется одновременно переносить несколько виртуальных машин с одного хоста.

  • Закрепление ЦП виртуальной машины может ограничить количество ЦП, доступных для процесса QEMU, и, таким образом, наложить ограничение на значимое количество параллельных соединений.

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

Параллельные миграции можно настроить как на уровне Кластера (Изменить кластер > Политика миграции > Дополнительные свойства > Параллельные миграции), так и на уровне ВМ (Изменить/Новая ВМ > Хост > Параметры миграции > Параллельные миграции). По умолчанию правила параллельных миграций наследуются виртуальными машинами от кластера. Установка необходимых правил на уровне ВМ, позволяет переопределить наследуемые параметры.

Таблица 15. Описание значений параметра «Параллельные миграции»

Значение Описание

Auto

Использование параллельных соединений миграции и их количество определяется автоматически в зависимости от доступных ресурсов (пропускная способность сети и мощность процессора).

Auto Parallel

Параллельные соединения миграции используются всегда. Количество соединений определяется автоматически в зависимости от доступных ресурсов (пропускная способность сети и мощность процессора).

Disabled (значение по умолчанию для кластеров)

Параллельные соединения миграции не используются.

Custom

Параллельные соединения миграции используются всегда. Количество соединений устанавливается пользователем в поле Количество соединений ВМ миграций.

Минимальное количество соединений — 2. Максимальное количество — 255, но не рекомендуется использовать более 16, а фактическое количество соединений, используемых для конкретной миграции, ограничивается количеством потоков на исходном и целевом хостах (в зависимости от того, какое из них меньше).

Использовать кластер по умолчанию (только в окне создание/редактирование ВМ)

Использовать параллельные соединения, как указано в настройках кластера.

6.13.9. Миграция очень больших виртуальных машин

В zVirt 4.0 появилась новая функция — миграция без копирования.

Миграция без копирования еще больше повышает скорость миграции и может позволить мигрировать большие виртуальные машины (более 1ТБ ОЗУ).

Для использования данной функции внедрена новая политика миграции — Очень большие ВМ (Very large VMs).

Текущая реализация миграции без копирования в QEMU имеет некоторые ограничения:

  • Её можно использовать только с параллельной миграцией.

  • Её нельзя использовать с шифрованием миграции.

  • Функция доступна только в кластере с версией совместимости 4.7.

  • Vdsm, libvirt и QEMU на хосте-источнике миграции должны поддерживать эту функцию.

  • Это новая функция в QEMU/libvirt, которая может содержать ошибки. В данный момент рекомендуется использовать её, только если это действительно необходимо.

Для активации данной функции:

  1. На портале администрирования перейдите в .

  2. Выделите подходящий кластер (с версией совместимости 4.7) и нажмите Изменить.

  3. На вкладке Политика миграции в меню Политика миграции выберите Очень большие ВМ (Very large VMs).

  4. Настройте необходимые параметры для поддержки функции миграции без копирования:

    1. В дополнительных свойствах отключите шифрование при миграции.

    2. Настройте Параллельные миграции.

  5. Нажмите OK.

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

Если эта политика выбрана, а вышеуказанные ограничения не соблюдены, то:

  • Если параллельные миграции отключены или включены в режиме Auto, то они используются с автоматическим количеством параллельных соединений.

  • Если включено шифрование при миграции, функция миграции без копирования не работает.

Если политика выбрана, а хост не поддерживает эту функцию, то:

  • Если Vdsm не поддерживает эту функцию, регистрируется несоответствие вызовов API и функция миграции без копирования не включается.

Это возможно в том случае, если в конфигурации Менеджера включены параллельные миграции (на уровне кластера), но хост, находящийся в кластере, не обновлен.

Во всех указанных случаях миграция ВМ продолжается, хотя и с разными параметрами.

6.13.10. Отмена начатых миграций виртуальных машин

Миграция виртуальной машины занимает больше времени, чем ожидалось. Прежде чем вносить какие-либо изменения в среду, проверьте, где запущены все виртуальные машины.

Порядок действий:

  1. Выберите мигрирующую виртуальную машину. Она отображается в разделе со статусом Миграция с (Migrating from) и значком мигрирует .

  2. Нажмите , затем — Отменить миграцию (Cancel Migration).

Статус виртуальной машины изменится со значения Миграция с (Migrating from) на значение Работает (Up) и значок .

6.13.11. Уведомление о событиях и журнале при автоматической миграции виртуальных серверов с признаком высокой доступности

Когда из-за присвоенного признака высокой доступности виртуальный сервер переносится автоматически, подробные сведения об автоматической миграции записываются на вкладке События (Events) и в журнале Менеджера в ВМ, чтобы облегчить поиск и устранение ошибок, как показано в следующих примерах:

Пример 5. Уведомление на вкладке «События (Events)» на Портале администрирования

Highly Available Virtual_Machine_Name failed. It will be restarted automatically.
Virtual_Machine_Name was restarted on Host Host_Name

Пример 6. Уведомление в журнале Менеджера управления engine.log

Этот журнал находится в Менеджере управления по пути /var/log/ovirt-engine/engine.log:

Failed to start Highly Available VM. Attempting to restart. VM Name: Virtual_Machine_Name, VM Id:Virtual_Machine_ID_Number

6.14. Увеличение времени непрерывной работы с помощью высокой доступности виртуальной машины

6.14.1. Что такое высокая доступность?

Высокая доступность рекомендована для виртуальных машин, на которых запущены критически важные процессы. Виртуальная машина с признаком высокой доступности перезапускается автоматически либо на своем изначальном хосте, либо на другом хосте в кластере, если процесс прерван, например, в одной из следующих ситуаций:

  • Хост перестает работать из-за отказа оборудования.

  • Хост переведен в режим обслуживания на период плановой неработоспособности.

  • Хост становится недоступен из-за потери связи с внешним хранилищем.

Виртуальная машина с признаком высокой доступности не перезапускается, если она была прямо выключена, например, как в следующих ситуациях:

  • Виртуальная машина выключена с гостевой машины.

  • Виртуальная машина выключена из Менеджера управления.

  • Хост выключен администратором без предварительного перевода в режим обслуживания.

У виртуальных машин есть дополнительная возможность получить в аренду пространство на специальном томе хранилища, что позволяет виртуальной машине запуститься на другом хосте даже при отсутствии питания у изначального хоста. Функциональность также не позволяет виртуальной машине запуститься на двух разных хостах, что может привести к повреждению ее дисков.

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

Высокая доступность и ошибки ввода/вывода хранилища

При возникновении ошибки ввода/вывода хранилища виртуальная машина приостанавливается. Можно задать, что делать хосту с виртуальными машинами с признаком высокой доступности после того, как подключение к домену хранения будет восстановлено: хост может их вновь запустить, некорректно выключить (сбросить питание), или оставить на паузе. Дополнительную информацию об этих опциях см. в разделе Описание настроек высокой доступности виртуальной машины.

6.14.2. Пояснения относительно высокой доступности

Для хоста с признаком высокой доступности требуется устройство управления питанием и параметры изоляции, к тому же, чтобы виртуальная машина работала в режиме высокой доступности, когда ее хост перестает работать, ее нужно запустить на другом доступном хосте в кластере. Чтобы обеспечить миграцию виртуальных машин с признаком высокой доступности:

  • Для хостов, на которых работают виртуальные машины с признаком высокой доступности, должно быть настроено управление питанием.

  • Хост, на котором работает виртуальная машина с признаком высокой доступности, должен входить в кластер, в котором есть и другие доступные хосты.

  • Хост-приемник должен быть запущен.

  • У хоста-источника и хоста-приемника должен быть доступ к домену данных, на котором находится виртуальная машина.

  • У хоста-источника и хоста-приемника должен быть доступ к одним и тем же виртуальным сетям и сетям VLAN.

  • На хосте-приемнике должно быть достаточно ресурсов ЦП, которые не используются для обеспечения работы виртуальной машины.

  • На хосте-приемнике должен быть достаточный объем ОЗУ, который не используется для обеспечения работы виртуальной машины.

6.14.3. Конфигурирование виртуальной машины с признаком высокой доступности

Высокая доступность должна настраиваться отдельно для каждой виртуальной машины.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Высокая доступность (High Availability).

  4. Установите флажок Высокая доступность (Highly Available) для включения высокой доступности для виртуальной машины.

  5. Выберите домен хранения для сохранения аренды виртуальной машины или выберите Домен хранения не выбран (No VM Lease) в выпадающем списке Целевой домен хранения для аренды ВМ (Target Storage Domain for VM Lease), чтобы отключить эту функциональность. Для получения дополнительной информации об аренде виртуальных машин см. раздел Что такое высокая доступность?.

  6. Выберите Автовозобновление (Auto Resume), Оставить на паузе (Leave Paused) или Принудительно завершить (Kill) из выпадающего списка Действие (Resume Behavior). Если указана аренда виртуальной машины, то единственная доступная опция — Принудительно завершить (KILL). Дополнительную информацию см. в разделе Описание настроек высокой доступности виртуальной машины.

  7. Выберите значение Низкий (Low), Средний (Medium) или Высокий (High) из выпадающего списка Приоритет (Priority). В момент инициации миграции создается очередь, согласно которой сначала переносятся виртуальные машины с высоким приоритетом. Если у кластера мало ресурсов, то переносятся только виртуальные машины с высоким приоритетом.

  8. Нажмите OK.

6.15. Другие задачи, касающиеся виртуальных машин

6.15.1. Включение SAP-мониторинга

Включите SAP-мониторинг на виртуальной машине через Портал администрирования.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите Изменить (Edit).

  3. Откройте вкладку Доп. параметры (Custom Properties).

  4. Выберите sap_agent из выпадающего списка. Убедитесь, что во вторичном выпадающем меню установлено значение True.

    Если свойства уже были заданы, выберите знак для добавления нового правила свойства и выберите sap_agent.

  5. Нажмите OK.

6.15.2. Конфигурирование виртуальных машин Linux на использование SPICE

SPICE — протокол удаленного дисплея, предназначенный для виртуальных сред и позволяющий просматривать рабочее место или сервер виртуализации. SPICE обеспечивает удобство использования, низкое потребление ресурсов ЦП и передача потокового видео в высоком качестве. Использование SPICE на машине, работающей на Linux, значительно улучшает перемещение курсора мыши по консоли виртуальной машины. Чтобы использовать SPICE, системе X-Windows требуются дополнительные QXL-драйверы. QXL-драйверы распространяются производителями дистрибутивов, на виртуальные машины с ОС семейства Red Hat Enterprise Linux QXL-драйверы устанавливаются по умолчанию. После установки SPICE на виртуальной машине, производительность графического интерфейса пользователя значительно увеличивается.

Как правило, наиболее полезной эта функция оказывается, когда нужно задействовать графический интерфейс пользователя. Системные администраторы, создающие виртуальные серверы, могут и не настраивать SPICE, если обращаются к графическому интерфейсу пользователя по минимуму.

6.15.3. Добавление устройства доверенного платформенного модуля (TPM)

Устройства доверенного платформенного модуля (TPM-устройства) предоставляют безопасный криптопроцессор, предназначенный для выполнения таких криптографических операций, как генерирование криптографических ключей, случайных чисел и хэшей или для хранения данных, которые можно использовать для безопасной проверки конфигураций ПО. TPM-устройства обычно используются для шифрования дисков.

QEMU и libvirt реализуют совместимость с эмулируемыми TPM-устройствами версии 2.0, а это именно то, что использует zVirt для добавления TPM-устройств на виртуальные машины.

После того, как эмулируемое TPM-устройство добавлено на виртуальную машину, его можно использовать в гостевой ОС как обычное TPM-устройство версии 2.0.

Если имеются TPM-данные, которые хранятся для виртуальной машины, а TPM-устройство отключено на виртуальной машине, то TPM-данные удаляются без возможности восстановления.

Порядок действий:

  1. На экране Новая виртуальная машина (New Virtual Machine) или Изменить виртуальную машину (Edit Virtual Machine) нажмите Показать расширенные настройки (Show Advanced Options).

  2. На вкладке Выделение ресурсов (Resource Allocation) установите флажок Включить TPM (TPM Device Enabled).

Применяются следующие ограничения:

  • TPM-устройства можно использовать только на 64-разрядных машинах x86 с прошивкой UEFI.

  • У виртуальных машин с TPM-устройствами не может быть моментальных снимков с состоянием памяти.

  • Если Менеджер управления периодически извлекает и хранит TPM-данные, то нет гарантии, что у него всегда будет последняя версия TPM-данных.

    Процесс может занять 120 секунд и более, поэтому нужно дождаться окончания процесса, прежде чем работающую виртуальную машину можно будет клонировать, перенести или снять с нее моментальный снимок.
  • TPM-устройства можно включить только на виртуальных машинах, Linux c ядром 4.0 или более поздней версии и на Windows 8.1 или более поздней версии.

  • Виртуальные машины и шаблоны с TPM-данными нельзя экспортировать или импортировать.

7. Шаблоны

7.1. О шаблонах

Шаблон — это копия виртуальной машины, которую можно использовать для упрощения последующего многократного создания похожих виртуальных машин. Шаблоны фиксируют программную и аппаратную конфигурацию, а также программное обеспечение, установленное на виртуальной машине, взятой за основу для шаблона. Виртуальная машина, на которой основан шаблон, называется исходной виртуальной машиной. При создании шаблона на основе виртуальной машины создается доступная только для чтения копия диска виртуальной машины. Этот диск становится базовым образом диска нового шаблона и любых виртуальных машин, созданных на основе этого шаблона. Таким образом, шаблон нельзя удалить, пока в среде существуют виртуальные машины, созданные на его основе. Виртуальные машины, созданные на основе шаблона, используют тот же тип сетевой карты и драйвер, что и исходная виртуальная машина, но им назначаются отдельные уникальные MAC-адреса.

Виртуальную машину можно создать прямо в разделе , а также в разделе . В разделе выберите необходимый шаблон и нажмите Новая ВМ (New VM). Дополнительные сведения о выборе настроек и элементов управления для новой виртуальной машины см. в разделе Описание общих настроек виртуальной машины.

7.2. Фиксация виртуальных машин при подготовке к развертыванию в качестве шаблонов

В этом разделе описываются процедуры фиксации виртуальных машин Linux и Windows. Фиксация — это процесс удаления из виртуальной машины всех относящихся к системе сведений перед созданием шаблона на основе этой виртуальной машины. Фиксация позволяет не допустить появления одних и тех же сведений в нескольких виртуальных машинах, созданных из одного шаблона. Она также необходима, чтобы обеспечить работу других функций, таких как предсказуемый порядок vNIC.

7.2.1. Фиксация виртуальной машины Linux для развертывания в качестве шаблона

Чтобы зафиксировать виртуальную машину Linux в процессе создания шаблона, установите флажок Запечатать шаблон (только Linux) Seal Template (Linux only) в окне Новый шаблон (New Template). Подробности см. в разделе Создание шаблона.

7.2.2. Фиксация виртуальной машины Windows для развертывания в качестве шаблона

Шаблон, созданный для виртуальных машин Windows, должен быть зафиксирован перед использованием для развертывания виртуальных машин. Это гарантирует, что в шаблоне не будут воспроизводиться настройки, характерные для конкретной машины.

Sysprep используется для фиксации шаблонов Windows перед использованием. Sysprep генерирует полный файл ответов для автономной установки. Значения по умолчанию для нескольких операционных систем Windows доступны в каталоге /usr/share/ovirt-engine/conf/sysprep/ — эти файлы выступают в качестве шаблонов для Sysprep. Поля в этих файлах можно копировать, вставлять и менять при необходимости. Это определение настроек переопределит любые значения, введенные в поля Запуск инициализации (Initial Run) окна Изменить виртуальную машину (Edit Virtual Machine).

Файл Sysprep можно изменить, чтобы повлиять на различные аспекты виртуальных машин Windows, созданных на основе шаблона, к которому он подключен. Сюда относятся выделение виртуальных машин Windows, настройка необходимого членства в домене, доменного имени и политики безопасности.

Заменяющие строки можно использовать для замены значений, представленных в файлах по умолчанию в каталоге /usr/share/ovirt-engine/conf/sysprep/. Например, "<Domain><![CDATA[$JoinDomain$"]></Domain>" можно использовать для указания домена, к которому нужно присоединиться.

Предварительные условия для фиксации виртуальной машины Windows
Не перезагружайте виртуальную машину во время работы Sysprep.

Перед запуском Sysprep убедитесь, что заданы следующие настройки:

  • Параметры виртуальной машины Windows заданы корректно.

  • Если же нет, то нажмите Изменить (Edit) в разделе и введите необходимую информацию в поля Операционная система (Operating System) и Кластер (Cluster) закладки Общее (General).

  • Корректный ключ продукта задан в переопределяющем файле в Менеджере управления.

Переопределяющий файл должен быть создан в каталоге /etc/ovirt-engine/osinfo.conf.d/ под именем, которое помещает его после файла /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties и заканчивается на .properties. Например, /etc/ovirt-engine/osinfo.conf.d/10-productkeys.properties. Последний файл будет иметь приоритет и переопределит любой другой предыдущий файл. В противном случае скопируйте значения по умолчанию для ОС Windows из /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties в переопределяющий файл и введите собственные значения в поля productKey.value и sysprepPath.value.

Пример 7. Значения параметров конфигурации по умолчанию для Windows 7

# Windows7(11, OsType.Windows, false),false
os.windows_7.id.value = 11
os.windows_7.name.value = Windows 7
os.windows_7.derivedFrom.value = windows_xp
os.windows_7.sysprepPath.value = ${ENGINE_USR}/conf/sysprep/sysprep.w7
os.windows_7.productKey.value =
os.windows_7.devices.audio.value = ich6
os.windows_7.devices.diskInterfaces.value.3.3 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.4 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.5 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.isTimezoneTypeInteger.value = false
Фиксация виртуальной машины Windows для развертывания в качестве шаблона

Зафиксируйте виртуальную машину Windows, прежде чем создавать шаблон, который будет использоваться при развертывании виртуальных машин.

Порядок действий:

  1. На виртуальной машине Windows запустите Sysprep:

    C:\Windows\System32\sysprep\sysprep.exe
  2. Введите в Sysprep следующую информацию:

    • В разделе Действие по очистке системы (System Cleanup Action) выберите Войти в режим первоначальной настройки (OOBE) системы (Enter System Out-of-Box-Experience (OOBE)).

    • Установите флажок Обобщить (Generalize), если нужно изменить SID-идентификатор компьютера.

    • В разделе Параметры выключения (Shutdown Options) выберите Выключить (Shutdown).

  3. Нажмите OK, чтобы завершить процесс фиксации — виртуальная машина автоматически выключится после завершения.

Виртуальная машина Windows зафиксирована и готова к созданию шаблона, который будет использоваться при развертывании виртуальных машин.

7.3. Создание шаблона

Создайте из существующей виртуальной машины шаблон, который будет использоваться для создания дополнительных виртуальных машин.

При создании шаблона укажите формат диска: raw или QCOW2:

  • Диски QCOW2 — динамически выделяемые.

  • Raw-диски в файловом хранилище — динамически выделяемые.

  • Raw-диски в блочном хранилище — предварительно размечаемые.

Порядок действий:

  1. Нажмите и выберите исходную виртуальную машину.

  2. Убедитесь, что виртуальная машина выключена и имеет состояние Выключена (Down) и помечена значком .

  3. Нажмите , затем — Создать шаблон (Make Template). Дополнительные сведения обо всех полях в окне Новый шаблон (New Template) см. в разделе Описание настроек в окнах «Новый шаблон (New Template)» и «Изменить шаблон (Edit Template)».

  4. Введите Имя (Name), Описание (Description) и Комментарий (Comment) для шаблона.

  5. В выпадающем списке Кластер (Cluster) выберите кластер, с которым нужно ассоциировать шаблон. По умолчанию он будет тем же, что и для исходной виртуальной машины.

  6. При желании выберите профиль ЦП для шаблона в выпадающем списке Профиль ЦП (CPU Profile).

  7. При желании установите флажок Создать, как подверсию шаблона (Create as a Template Sub-Version), выберите Корневой шаблон (Root Template) и введите Название подверсии (Sub-Version Name), чтобы создать новый шаблон как подшаблон существующего шаблона.

  8. В разделе Выделение дискового пространства (Disks Allocation) введите имя для диска в поле Имя (Alias). В выпадающем списке Формат (Format) выберите формат диска, в выпадающем списке Цель (Target) — домен хранения, где будет размещаться диск, а в выпадающем списке Профиль диска (Disk Profile) — профиль диска. По умолчанию они будут теми же, что и для исходной виртуальной машины.

  9. Установите флажок Разрешить всем пользователям доступ к шаблону (Allow all users to access this Template), чтобы разрешить совместное использование шаблона.

  10. Установите флажок Копировать разрешения ВМ (Copy VM permissions), чтобы скопировать разрешения исходной виртуальной машины в шаблон.

  11. Установите флажок Запечатать шаблон (Seal Template) (только для Linux), чтобы зафиксировать шаблон.

    При запечатывании (фиксировании) с помощью команды virt-sysprep относящиеся к системе сведения удаляются из виртуальной машины перед созданием шаблона на основе этой виртуальной машины. В результате сведения исходной виртуальной машины не попадают в последующие виртуальные машины, создаваемые из этого же шаблона. Это также обеспечивает работу других функций, таких как предсказуемый порядок vNIC. Дополнительную информацию см. в Операции virt-sysprep.
  12. Нажмите OK.

Во время создания шаблона состояние виртуальной машины отображается как Образ заблокирован (Image Locked) и отмечено значком . Создание шаблона может занять до часа времени в зависимости от размера виртуального диска и возможностей оборудования для хранения. После завершения шаблон будет добавлен на вкладку Шаблоны (Templates). Теперь на основе этого шаблона можно создавать новые виртуальные машины.

Когда делается шаблон, виртуальная машина копируется, чтобы после создания шаблона можно было использовать и существующую виртуальную машину, и ее шаблон.

7.4. Изменение шаблона

После создания шаблона его свойства можно менять. Поскольку шаблон — это копия виртуальной машины, параметры, доступные при изменении шаблона, идентичны параметрам в окне Изменить виртуальную машину (Edit Virtual Machine).

Порядок действий:

  1. Нажмите и выберите шаблон.

  2. Нажмите Изменить (Edit).

  3. Измените необходимые свойства. Нажмите Показать расширенные настройки (Show Advanced Options) и измените настройки шаблона нужным образом. Настройки в окне Изменить шаблон (Edit Template) идентичны настройкам в окне Изменить виртуальную машину (Edit Virtual Machine) и отличаются лишь соответствующими полями. Подробности см. в разделе Описание настроек в окнах «Новая виртуальная машина (New Virtual Machine)» и «Изменить виртуальную машину (Edit Virtual Machine)».

  4. Нажмите OK.

7.5. Удаление шаблона

Если виртуальная машина создана из шаблона с динамическим выделением хранилища, то этот шаблон нельзя удалить, так как он нужен виртуальной машине для работы. Однако клонированные виртуальные машины не зависят от шаблона, из которого они были клонированы, так что этот шаблон можно удалить.

Порядок действий:

  1. Нажмите и выберите шаблон.

  2. Нажмите Удалить (Remove).

  3. Нажмите OK.

7.6. Экспортирование шаблонов

7.6.1. Перенос шаблонов в домен экспорта

Сущность «экспорт-домен» считается устаревшей. Домены хранения данных можно отключить от центра данных и импортировать в другой центр данных в той же или другой среде. Затем виртуальные машины, «плавающие» виртуальные диски и шаблоны можно выгрузить из импортированного домена хранения в подключенный центр данных.

Экспортируйте шаблоны в домен экспорта, чтобы переместить их в другой домен данных в той же среде zVirt или в другой среде. Эта процедура требует доступа к Порталу администрирования.

Порядок действий:

  1. Нажмите и выберите шаблон.

  2. Нажмите Экспортировать (Export).

  3. Установите флажок Перезаписать принудительно (Force Override), чтобы заменить любую более раннюю версию шаблона в домене экспорта.

  4. Нажмите OK, чтобы начать экспорт шаблона; процесс может занять до часа в зависимости от размера виртуального диска и оборудования хранилища.

Повторяйте эти шаги, пока в домене экспорта не будет всех переносимых шаблонов, и только потом начинайте импортирование.

  1. Нажмите и выберите домен экспорта.

  2. Нажмите имя домена, чтобы перейти к подробному представлению.

  3. Откройте вкладку Импортировать шаблон (Template Import) для просмотра всех экспортированных шаблонов в домене экспорта.

7.6.2. Копирование виртуальных жестких дисков шаблонов

В случае перемещения виртуальной машины, созданной из шаблона при выбранной опции динамического выделения хранилища, диски шаблона должны быть скопированы в тот же домен хранения, что и виртуальный диск. Для процедуры требуется доступ к Порталу администрирования.

Порядок действий:

  1. Нажмите .

  2. Выберите диск(и) шаблона для копирования.

  3. Нажмите Копировать (Copy).

  4. В выпадающем(их) списке(ах) выберите Целевой (Target) домен данных.

  5. Нажмите OK.

Копия виртуального жесткого диска шаблона создана на том же или на другом домене хранения. Если копирование диска шаблона происходило при подготовке к перемещению виртуального жесткого диска, то теперь можно переместить виртуальный жесткий диск.

7.7. Импортирование шаблонов

Сущность «экспорт-домен» считается устаревшей. Домены хранения данных можно отключить от центра данных и импортировать в другой центр данных в той же или другой среде. Затем виртуальные машины, «плавающие» виртуальные диски и шаблоны можно выгрузить из импортированного домена хранения в подключенный центр данных.

Импортируйте шаблоны из недавно подключенного домена экспорта. Для процедуры требуется доступ к Порталу администрирования.

Порядок действий:

  1. Нажмите и выберите недавно подключенный домен экспорта.

  2. Нажмите на имя домена, чтобы перейти к подробному представлению.

  3. Откройте вкладку Импортировать шаблон (Template Import) и выберите шаблон.

  4. Нажмите Импортировать (Import).

  5. Выберите Целевой кластер (Target Cluster) и Профиль ЦП (CPU Profile) из выпадающих списков.

  6. Выберите шаблон для просмотра подробного представления, затем откройте вкладку Диски (Disks) и выберите Домен хранения (Storage Domain), в который будет импортирован шаблон.

  7. Нажмите OK.

  8. Если появилось окно Конфликт при импорте шаблона (Import Template Conflict), введите Новое имя (New Name) для шаблона или установите флажок Применить ко всем (Apply to all) и введите Суффикс для добавления к клонированным шаблонам (Suffix to add to the cloned Templates). Нажмите OK.

  9. Нажмите Закрыть (Close).

Шаблон импортирован в центр данных, являющийся приемником. Процесс может занять до часа в зависимости от оборудования хранилища. Ход импортирования можно отслеживать на вкладке События (Events). По завершении процесса импорта шаблоны появятся в разделе . С помощью шаблонов создаются новые виртуальные машины или запускаются уже существующие импортированные виртуальные машины, созданные на базе этого шаблона.

7.8. Шаблоны и разрешения

7.8.1. Управление системными разрешениями для шаблона

Будучи Суперпользователем (SuperUser), системный администратор управляет всеми аспектами Портала администрирования. Другим пользователям могут быть назначены ограниченные административные роли. Ограниченные роли нужны, чтобы предоставить пользователю административные права, которые действуют только в отношении определенного ресурса. Например, роль Администратор центра данных (DataCenterAdmin) имеет права только на назначенный центр данных (кроме его хранилища), а роль Администратор кластера (ClusterAdmin) имеет права только на назначенный кластер.

Администратор шаблона — это системная административная роль для шаблонов в центре данных. Эту роль можно применять к конкретным виртуальным машинам, к центру данных или ко всей среде виртуализации, так можно разрешать различным пользователям управлять определенными виртуальными ресурсами.

Роль администратора шаблона разрешает выполнять следующие действия:

  • Создавать, изменять, экспортировать и удалять ассоциированные шаблоны.

  • Импортировать и экспортировать шаблоны.

Можно назначать роли и разрешения только существующим пользователям.

7.8.2. Описание ролей администратора шаблона

В приведенной ниже таблице описаны роли и права администратора, применимые к администрированию шаблонов.

Таблица 16. Роли системного администратора zVirt

Роль Права Примечания

TemplateAdmin

Может выполнять все операции над шаблонами.

Имеет права создавать, удалять и конфигурировать домен хранения шаблона и параметры сети, а также перемещать шаблоны между доменами.

NetworkAdmin

Администратор сети

Может конфигурировать и управлять сетями, подключенными к шаблонам.

7.8.3. Назначение роли администратора или пользователя в отношении ресурса

Назначайте роли администратора или пользователя в отношении ресурсов, чтобы пользователи могли получить доступ к этому ресурсу или управлять им.

Порядок действий:

  1. Используйте вкладки ресурса или функцию поиска, чтобы найти и выбрать ресурс в списке результатов.

  2. Нажмите на имя ресурса, чтобы открыть подробное представление.

  3. Откройте вкладку Разрешения (Permissions), чтобы вывести список назначенных пользователей с информацией об их ролях и унаследованных разрешениях в отношении выбранного ресурса.

  4. Нажмите Добавить (Add).

  5. Введите реальное или пользовательское имя существующего пользователя в текстовое поле и нажмите Поиск (GO). Выберите пользователя из появившегося списка возможных совпадений.

  6. Выберите роль из выпадающего списка Роль для связи (Role to Assign).

  7. Нажмите OK.

После назначения роли пользователю, унаследованные разрешения этой роли будут включены для него в отношении этого ресурса.

7.8.4. Удаление роли администратора или пользователя из ресурса

Когда роль администратора или пользователя удаляют из ресурса, пользователь лишается унаследованных разрешений, ассоциированных с этой ролью для этого ресурса.

Порядок действий:

  1. Используйте вкладки ресурса или функцию поиска, чтобы найти и выбрать ресурс в списке результатов.

  2. Нажмите на имя ресурса, чтобы открыть подробное представление.

  3. Откройте вкладку Разрешения (Permissions), чтобы вывести список назначенных пользователей с информацией об их ролях и унаследованных разрешениях в отношении выбранного ресурса.

  4. Выберите пользователя, которого необходимо удалить из ресурса.

  5. Нажмите Удалить (Remove). Откроется окно Удалить права (Remove Permission), чтобы подтвердить удаление разрешений.

  6. Нажмите OK.

Пользовательская роль и ассоциированные разрешения из ресурса удалены.

7.9. Использование инструмента cloud-init для автоматизации настройки виртуальных машин

Cloud-Init — это инструмент для автоматизации начальной настройки виртуальных машин, например, настройки доменного имени, сетевых интерфейсов и авторизованных ключей. Его можно использовать при предоставлении виртуальных машин, развернутых на основе шаблона, чтобы избежать конфликтов в сети.

Для использования этого инструмента необходимо сначала установить пакет cloud-init на виртуальную машину. После установки служба Cloud-Init запускается в процессе начальной загрузки для поиска инструкций по настройке. Затем можно использовать параметры в окне Однократный запуск (Run Once), чтобы предоставить эти инструкции только один раз, или параметры в окнах Новая виртуальная машина (New Virtual Machine), Изменить виртуальную машину (Edit Virtual Machine) и Изменить шаблон (Edit Template), чтобы предоставлять эти инструкции при каждом запуске виртуальной машины.

Можно настроить Cloud-Init с помощью Ansible, Python, Java или Ruby.

7.9.1. Сценарии использования Cloud-Init

Cloud-Init можно использовать в разных сценариях автоматизации настройки виртуальных машин. Ниже приведены несколько распространенных сценариев:

  • Виртуальные машины, созданные на основе шаблонов

    Можно воспользоваться Использовать sysprep (Use Cloud-Init) в разделе Cloud-Init (Initial Run) в окне Запустить ВМ (Run Virtual Machine(s)) после нажатия кнопки Однократный запуск (Run Once) для инициализации виртуальной машины, созданной на основе шаблона. Например, можно применить пользовательские настройки к виртуальной машине, когда она запускается первый раз.

  • Шаблоны виртуальных машин

    С помощью параметров, появляющихся после установки флажка Cloud-Init (Cloud-Init) во вкладке Запуск инициализации (Initial Run) в окне Изменить шаблон (Edit Template) можно выполнить пользовательскую настройку виртуальных машин, созданных на основе шаблона.

  • Пулы виртуальных машин

    С помощью параметров, появляющихся после установки флажка Cloud-Init (Cloud-Init) во вкладке Запуск инициализации (Initial Run) в окне Новый пул (New Pool) можно выполнить пользовательскую настройку виртуальных машин, взятых из пула виртуальных машин. Так можно задать набор стандартных параметров, которые будут применяться каждый раз, когда виртуальную машину забирают из пула виртуальных машин. Можно наследовать или переопределить параметры, заданные для шаблона, на котором основана виртуальная машина, или задать параметры для самого пула виртуальных машин.

7.9.2. Установка Cloud-Init

Далее описан процесс установки Cloud-Init на виртуальную машину. После установки Cloud-Init можно создать шаблон на основе этой виртуальной машины. Виртуальные машины, созданные на основе этого шаблона, могут при начальной загрузке задействовать функции Cloud-Init, например, настройку доменного имени, часового пояса, root-пароля, авторизованных ключей, сетевых интерфейсов, службы DNS и т.д.

Порядок действий:

  1. Авторизуйтесь на виртуальной машине.

  2. Включите репозитории.

  3. Установите пакет cloud-init и зависимости:

    или

    apt-get install cloud-init
    Для ОС семейства Red Hat Enterprise Linux версий ниже 8 используйте команду yum install cloud-init вместо dnf install cloud-init.

7.9.3. Использование Cloud-Init для подготовки шаблона

Как только пакет cloud-init установлен на виртуальной машине Linux, можно использовать эту виртуальную машину для создания шаблона с поддержкой cloud-init. Укажите набор стандартных настроек, которые должны быть включены в шаблон, как описано в процедуре ниже, либо пропустите шаги настройки параметров Cloud-Init и настройте их при создании виртуальной машины на основе этого шаблона.

Хотя в следующей процедуре описано, как использовать Cloud-Init при подготовке шаблона, эти же настройки доступны в окнах «Новая виртуальная машина (New Virtual Machine)», «Изменить шаблон (Edit Template)» и «Запустить ВМ (Run Virtual Machine(s))».

Порядок действий:

  1. Нажмите и выберите шаблон.

  2. Нажмите Изменить (Edit).

  3. Нажмите Показать расширенные настройки (Show Advanced Options).

  4. Перейдите на вкладку Запуск инициализации (Initial Run) и установите флажок Cloud-Init (Cloud-Init).

  5. Введите имя хоста в текстовое поле Имя хоста ВМ (VM Hostname).

  6. Установите флажок Настроить временную зону (Configure Time Zone) и выберите часовой пояс из выпадающего списка Часовой пояс (Time Zone).

  7. Разверните раздел Аутентификация (Authentication).

    • Установите флажок Пользователь уже установил пароль (Use already configured password), чтобы можно было использовать существующие учетные данные, или снимите его и введите root-пароль в текстовых полях Пароль (Password) и Подтвердите пароль (Verify Password), чтобы задать новый root-пароль.

    • Введите любые ключи SSH, которые будут добавлены к файлу с авторизованными хостами на виртуальной машине, в текстовое поле Ключи SSH-авторизации (SSH Authorized Keys).

    • Установите флажок Пересоздать ключи SSH (Regenerate SSH Keys), чтобы повторно сгенерировать ключи SSH для виртуальной машины.

  8. Разверните раздел Сети (Networks).

    • Укажите любые DNS-серверы в текстовом поле DNS-серверы (DNS Servers).

    • Укажите любые домены поиска DNS в текстовом поле Домен поиска DNS (DNS Search Domains).

    • Установите флажок Гостевой сетевой интерфейс (In-guest Network Interface) и используйте кнопки Добавить новый (Add new) и Удалить выбранные (Remove selected), чтобы добавить сетевые интерфейсы к виртуальной машине или удалить их с нее.

    Необходимо обязательно указать корректные имя и номер сетевого интерфейса (например, eth0, eno3, enp0s). В противном случае подключение интерфейса виртуальной машины будет активно, но cloud-init не произведёт настройки сетевой конфигурации.
  9. Разверните раздел Пользовательский скрипт (Custom Script) и введите любые пользовательские скрипты в текстовом поле Пользовательский скрипт (Custom Script).

  10. Нажмите OK.

Теперь можно предоставлять новые виртуальные машины на базе этого шаблона.

7.9.4. Использование Cloud-Init для инициализации виртуальной машины

Cloud-Init можно использовать для автоматизации начальной настройки виртуальной машины Linux. Можно использовать поля Cloud-Init для настройки доменного имени виртуальной машины, часового пояса, root-пароля, авторизованных ключей, сетевых интерфейсов и службы DNS. Кроме того, можно задать пользовательский скрипт, скрипт в формате YAML, который будет запускаться при начальной загрузке. Пользовательский скрипт позволяет выполнить дополнительную настройку Cloud-Init, которая поддерживается Cloud-Init, но не доступна в полях Cloud-Init. Дополнительные сведения о примерах пользовательских скриптов см. Примеры пользовательских скриптов конфигурации Cloud-init.

Процедура инициализации запускает виртуальную машину с набором настроек Cloud-Init. Если соответствующие настройки включены в шаблон, на базе которого создана виртуальная машина, то проверьте настройки, внесите изменения (при необходимости) и нажмите OK для запуска виртуальной машины.

Порядок действий:

  1. Нажмите и выберите виртуальную машину.

  2. Нажмите кнопку с выпадающим списком Запустить (Run) и выберите Однократный запуск (Run Once).

  3. Разверните раздел Cloud-Init (Initial Run) и установите флажок Cloud-Init.

  4. Введите имя хоста в текстовое поле Имя хоста ВМ (VM Hostname).

  5. Установите флажок Настроить временную зону (Configure Time Zone) и выберите часовой пояс из выпадающего списка Часовой пояс (Time Zone).

  6. Разверните раздел Аутентификация (Authentication).

    • Установите флажок Пользователь уже установил пароль (Use already configured password), чтобы можно было использовать существующие учетные данные, или снимите его и введите root-пароль в текстовых полях Пароль (Password) и Подтвердите пароль (Verify Password), чтобы задать новый root-пароль.

    • Введите любые ключи SSH, которые будут добавлены к файлу с авторизованными хостами на виртуальной машине, в текстовое поле Ключи SSH-авторизации (SSH Authorized Keys).

    • Установите флажок Пересоздать ключи SSH (Regenerate SSH Keys), чтобы повторно сгенерировать ключи SSH для виртуальной машины.

  7. Разверните раздел Сети (Networks).

    • Укажите любые DNS-серверы в текстовом поле DNS-серверы (DNS Servers).

    • Укажите любые домены поиска DNS в текстовом поле Домен поиска DNS (DNS Search Domains).

    • Установите флажок Гостевой сетевой интерфейс (In-guest Network Interface) и используйте кнопки Добавить новый (Add new) и Удалить выбранные (Remove selected), чтобы добавить сетевые интерфейсы к виртуальной машине или удалить их с нее.

    Необходимо обязательно указать корректные имя и номер сетевого интерфейса (например, eth0, eno3, enp0s). В противном случае подключение интерфейса виртуальной машины будет активно, но cloud-init не произведёт настройки сетевой конфигурации.
  8. Разверните раздел Пользовательский скрипт (Custom Script) и введите любые пользовательские скрипты в текстовом поле Пользовательский скрипт (Custom Script).

  9. Нажмите OK.

Чтобы проверить, установлен ли на виртуальной машине Cloud-Init, выберите виртуальную машину и откройте вложенную вкладку Приложения (Applications). Отображается, только если установлен гостевой агент.

7.10. Использование инструмента Sysprep для автоматизации настройки виртуальных машин

Sysprep — это инструмент для автоматизации настройки виртуальных машин Windows, например, настройки доменных имен, сетевых интерфейсов, авторизованных ключей, пользователей или подключения к Active Directory. Sysprep устанавливается с каждой версией Windows.

Используя технологию виртуализации, zVirt расширяет возможности инструмента Sysprep и тем самым позволяет развертывать виртуальные рабочие станции на базе единого шаблона. zVirt создает специальный файл автоответов для каждой виртуальной рабочей станции.

Инструмент Sysprep создает полный файл ответов для автоматической установки. Значения по умолчанию для нескольких операционных систем Windows доступны в каталоге /usr/share/ovirt-engine/conf/sysprep/. Кроме того, можно создать пользовательский файл Sysprep и сослаться на него из файла osinfo в каталоге /etc/ovirt-engine/osinfo.conf.d/. Эти файлы действуют как шаблоны для Sysprep. Поля в этих файлах можно копировать и изменять по мере необходимости. Это определение настроек переопределяет любые значения, введенные в поля Запуск инициализации (Initial Run) в окне Изменить виртуальную машину (Edit Virtual Machine).

Можно создать пользовательский файл sysprep при создании пула виртуальных машин Windows с учетом различных операционных систем и доменов. Переопределяющий файл должен быть создан в каталоге /etc/ovirt-engine/osinfo.conf.d/ под именем, которое помещает его после /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties и заканчивается на .properties. Например, /etc/ovirt-engine/osinfo.conf.d/10-productkeys.properties. У последнего файла будет приоритет, и он переопределит все предыдущие.

Скопируйте значения по умолчанию для вашей операционной системы Windows из файла /etc/ovirt-engine/osinfo.conf.d/00-defaults.properties в переопределяющий файл и введите свои значения в поля productKey.value и sysprepPath.value.

Пример 8. Значения конфигурации Windows 7 по умолчанию

# Windows7(11, OsType.Windows, false),false
os.windows_7.id.value = 11
os.windows_7.name.value = Windows 7
os.windows_7.derivedFrom.value = windows_xp
os.windows_7.sysprepPath.value = ${ENGINE_USR}/conf/sysprep/sysprep.w7
os.windows_7.productKey.value =
os.windows_7.devices.audio.value = ich6
os.windows_7.devices.diskInterfaces.value.3.3 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.4 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.devices.diskInterfaces.value.3.5 = IDE, VirtIO_SCSI, VirtIO
os.windows_7.isTimezoneTypeInteger.value = false

7.10.1. Настройка инструмента sysprep в шаблоне

Следуя этой процедуре, можно задать набор стандартных параметров Sysprep, которые будут включены в шаблон, либо можно настроить параметры Sysprep при создании виртуальной машины на основе этого шаблона. Заменяющие строки можно использовать для замены значений, предоставленных в файлах по умолчанию в каталоге /usr/share/ovirt-engine/conf/sysprep/. Например, "<Domain><![CDATA[$JoinDomain$"]></Domain>" можно использовать для указания домена, к которому нужно присоединиться.

Не перезагружайте виртуальную машину во время работы Sysprep.

Предварительные условия:

  • Параметры виртуальной машины Windows заданы корректно.

    Если нет, нажмите , нажмите Изменить (Edit) и введите необходимую информацию в поля Операционная система (Operating System) и Кластер (Cluster).

  • Корректный ключ продукта был задан в переопределяющем файле в Менеджере управления.

Порядок действий:

  1. Создайте виртуальную машину Windows с необходимыми патчами и программным обеспечением.

  2. Зафиксируйте виртуальную машину Windows. Дополнительные сведения см. в разделе Фиксация виртуальной машины Windows для развертывания в качестве шаблона.

  3. Создайте шаблон на основе виртуальной машины Windows Дополнительные сведения см. в разделе Создание шаблона.

  4. Обновите файл Sysprep в текстовом редакторе, если необходимо внести дополнительные изменения.

Теперь можно предоставлять новые виртуальные машины на базе этого шаблона.

7.10.2. Использование Sysprep для инициализации виртуальной машины

Sysprep можно использовать для автоматизации начальной настройки виртуальной машины Windows. Можно использовать поля Sysprep для настройки доменного имени виртуальной машины, часового пояса, root-пароля, авторизованных ключей, сетевых интерфейсов и службы DNS.

Эта процедура запускает виртуальную машину с набором настроек Sysprep. Если соответствующие настройки включены в шаблон, на котором основана виртуальная машина, то проверьте настройки и при необходимости внесите изменения.

Порядок действий:

  1. Создайте виртуальную машину Windows на основе шаблона нужной виртуальной машины Windows. См. раздел Создание шаблона.

  2. Нажмите и выберите виртуальную машину.

  3. Нажмите кнопку с выпадающим списком Запустить (Run) и выберите Однократный запуск (Run Once).

  4. Разверните раздел Параметры загрузки (Boot Options), установите флажок Прикрепить CD (Attach CD) и выберите необходимые образы Windows ISO из выпадающего списка.

  5. Переместите CD-привод (CD-ROM) в начало списка в поле Последовательность начальной загрузки (Boot Sequence).

  6. Разверните раздел Cloud-Init (Initial Run) и настройте параметры.

  7. Настройте любые дополнительные параметры в окне Запустить ВМ (Run Virtual Machine(s)) нужным образом. Дополнительные сведения см. в разделе Описание настроек в окне «Запустить ВМ (Run Virtual Machine(s))».

  8. Нажмите OK.

7.11. Создание виртуальной машины на основе шаблона

Создание виртуальной машины из шаблона позволяет на ней предварительно настроить операционную систему, сетевые интерфейсы, приложения и другие ресурсы.

  • Виртуальные машины, созданные на основе шаблона, зависят от этого шаблона, поэтому нельзя удалять шаблон из Менеджера управления, если виртуальная машина была создана на основе этого шаблона. Однако можно клонировать виртуальную машину из шаблона, чтобы убрать зависимость от этого шаблона.

  • Если тип BIOS виртуальной машины отличается от типа BIOS шаблона, то Менеджер управления может изменить устройства в виртуальной машине, что может помешать начальной загрузке операционной системы. Например, если в шаблоне используются диски IDE и чипсет i440fx, то изменение типа BIOS на чипсет Q35 автоматически меняет диски IDE на диски SATA. Поэтому следует настроить чипсет и тип BIOS так, чтобы они соответствовали чипсету и типу BIOS шаблона.

Порядок действий:

  1. Нажмите .

  2. Нажмите Создать (New).

  3. Выберите Кластер (Cluster), в котором будет работать виртуальная машина.

  4. Выберите шаблон из списка Шаблон (Template).

  5. Укажите Имя (Name), Описание (Description) и любые Комментарии (Comments) и примите значения по умолчанию, наследуемые у шаблона, в остальных полях. При необходимости их можно изменить.

  6. Откройте вкладку Выделение ресурсов (Resource Allocation).

  7. Нажмите кнопку-переключатель Тонкий (Thin) или Клонированный (Clone) в области Тип диска (Storage Allocation). Если выбрать Тонкий (Thin), формат диска будет QCOW2. Если выбрать Клонированный (Clone), можно использовать форматы диска QCOW2 или Raw.

  8. В выпадающем списке Цель (Target) выберите домен хранения, в котором будет размещен виртуальный диск виртуальной машины.

  9. Нажмите OK.

Виртуальная машина отобразится на вкладке Виртуальные машины (Virtual Machines).

7.12. Создание клонированной виртуальной машины на основе шаблона

Клонированные виртуальные машины основаны на шаблонах и наследуют настройки шаблона. После создания клонированная виртуальная машина не зависит от шаблона, на котором она была основана, это означает, что шаблон можно удалить, если нет других зависимостей.

При клонировании виртуальной машины из шаблона имя шаблона, на котором была основана эта виртуальная машина, отображается на вкладке Общее (General) в окне Изменить виртуальную машины (Edit Virtual Machine) для этой виртуальной машины. Если изменить имя этого шаблона, то имя шаблона на вкладке Общее (General) также обновится, однако если удалить шаблон из Менеджера управления, вместо него будет отображаться исходное имя шаблона.

Порядок действий:

  1. Нажмите .

  2. Нажмите Создать (New).

  3. Выберите Кластер (Cluster), в котором будет работать виртуальная машина.

  4. Выберите шаблон из списка Шаблон (Template).

  5. Укажите Имя (Name), Описание (Description) и любые Комментарии (Comments) и примите значения по умолчанию, наследуемые у шаблона, в остальных полях. При необходимости их можно изменить.

  6. Откройте вкладку Выделение ресурсов (Resource Allocation).

  7. Нажмите кнопку-переключатель Клонированный (Clone) в области Тип диска (Storage Allocation).

  8. Выберите формат диска в выпадающем списке Формат (Format). Это влияет на скорость клонирования и размер дискового пространства, изначально необходимого новой виртуальной машине.

    • QCOW2 (По умолчанию):

      • Операция клонирования выполняется быстрее.

      • Оптимизированное использование дискового пространства.

      • Дискового пространства выделяется лишь столько, сколько нужно.

    • Raw:

      • Операция клонирования выполняется медленнее.

      • Оптимизированные операции чтения и записи виртуальных машин.

      • Все дисковое пространство, затребованное в шаблоне, выделяется во время операции клонирования.

  9. В выпадающем списке Цель (Target) выберите домен хранения, в котором будет размещен виртуальный диск виртуальной машины.

  10. Нажмите OK.

Клонирование виртуальной машины может занять некоторое время — должна быть создана новая копия диска шаблона. В течение этого времени у виртуальной машины сначала будет Состояние (Status) Образ заблокирован (Image Locked) , а потом Выключена (Down) .

Виртуальная машина создается и отображается на вкладке Виртуальные машины (Virtual Machines). После завершения операции клонирования можно назначить пользователей виртуальной машине и начать ее использовать.

8. Описание настроек ВМ

8.1. Описание настроек в окнах «Создать ВМ (New Virtual Machine)» и «Изменить ВМ (Edit Virtual Machine)»

8.1.1. Описание общих настроек виртуальной машины

В следующей таблице описаны параметры на вкладке Общее (General) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 17. Виртуальная машина: общие настройки

Имя поля Описание Требуется ли выключение и включение питания?

Кластер (Cluster)

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

Да. Миграция между кластерами разрешается только в экстренных случаях. При перемещении между кластерами виртуальная машина должна быть выключена.

Шаблон (Template)

Шаблон, на котором основана виртуальная машина. По умолчанию значение этого поля Blank, поэтому можно создать виртуальную машину, на которой еще не установлена операционная система. Шаблоны отображаются в виде Имя / Имя подверсии (Номер подверсии) (Name / Sub-version name (Sub-version number)). Каждая новая версия отображается с номером в квадратных скобках, который указывает на относительный порядок версий, причем более высокий номер указывает на более новую версию. Имя версии отображается как base version, если это не корневой шаблон из цепочки версий шаблонов. Если виртуальная машина не сохраняет состояние, можно выбрать последний (latest) версию шаблона. Этот параметр означает, что каждый раз при создании новой версии этого шаблона виртуальная машина автоматически воссоздается при перезапуске на основе последней версии шаблона.

Не применимо. Этот параметр предназначен только для предоставления новых виртуальных машин.

Операционная система (Operating System)

Операционная система. Допустимые значения включают несколько вариантов Linux и Windows.

Да. Возможна смена виртуального оборудования.

Тип BIOS (Chipset/Firmware Type)

Здесь можно указать тип чипсета и микропрограммного обеспечения. Выставляет тип чипсета и микропрограммного обеспечения в значения, заданные по умолчанию для кластера. Доступны следующие параметры:

  • I440FX chipset with BIOS (устаревший).

  • Чипсет Q35 с BIOS (используется по умолчанию).

  • Чипсет Q35 с UEFI.

  • Чипсет Q35 с UEFI SecureBoot (UEFI с функцией SecureBoot, которая проверяет подлинность цифровых подписей загрузчика) .

Да

Профиль нагрузки (Optimized for)

Тип системы, для которого виртуальная машина должна быть оптимизирована. Возможны три варианта: Сервер (Server), Рабочая станция (Desktop) и Высокая производительность (High Performance); по умолчанию значение поля — Сервер (Server). Виртуальные машины оптимизированы для работы в качестве серверов без звуковой карты, используют клонированный образ диска и сохраняют состояние. Виртуальные машины, оптимизированные для работы в качестве рабочих станций, имеют звуковую карту, используют образ с динамическим выделением пространства и не сохраняют состояние. У виртуальных машин, оптимизированных для работы в режиме высокой производительности, есть несколько изменений в конфигурации. См. раздел Настройка высокопроизводительных виртуальных машин.

Да

Имя (Name)

Имя виртуальной машины, оно должно быть уникальным в пределах центра данных, без пробелов, и хотя бы один знак должен быть буквой латинского алфавита (A-Z) или цифрой от 0 до 9. Максимальная длина имени виртуальной машины — 255 знаков. Имя можно повторно использовать в разных центрах данных в одной среде.

Да

Описание (Description)

Содержательное описание новой виртуальной машины.

Нет

Комментарий (Comment)

Поле для добавления комментариев о виртуальной машине в виде обычного текста.

Нет

Идентификатор ВМ (Vm ID)

Идентификатор виртуальной машины. Создатель виртуальной машины может задать пользовательский идентификатор для конкретной виртуальной машины. Пользовательский идентификатор должен состоять исключительно из цифр в следующем формате: 00000000-0000-0000-0000-00000000. Если при создании не был указан идентификатор, то идентификатор UUID будет назначен автоматически. После создания виртуальной машины невозможно изменить ни пользовательский, ни автоматически сгенерированный идентификатор.

Да

Без запоминания состояния (Stateless)

Установите этот флажок, чтобы виртуальная машина работала в режиме без сохранения состояния. Это режим применяется в основном для виртуальных машин, используемых в качестве рабочих станций. При запуске рабочей станции или сервера без сохранения состояния создается новый слой COW на образе жесткого диска виртуальной машины, где хранятся новые и измененные данные. После выключения виртуальной машины без сохранения состояния удаляется новый слой COW, в том числе все изменения в данных и в конфигурации, а виртуальная машина возвращается в исходное состояние. Виртуальные машины без сохранения состояния стоит использовать, когда машины нужны ненадолго или временному персоналу.

Не применимо

Запустить в режиме приостановки (Start in Pause Mode)

Установите этот флажок, и виртуальная машина всегда будет запускаться в режиме паузы. Этот параметр подходит для виртуальных машин, на которых установка подключения SPICE занимает много времени, например, для виртуальных машин на удаленном объекте.

Не применимо

Защита от удаления (Delete Protection)

Установите флажок, чтобы виртуальную машину было невозможно удалить. Виртуальную машину можно удалить только, если этот флажок снят.

Нет

Запечатать (Sealed)

Установите этот флажок, чтобы зафиксировать созданную виртуальную машину. Эта опция позволяет исключить специфические для машины настройки из виртуальных машин, созданных на основе шаблона. Дополнительные сведения о процессе фиксации см. в разделе Фиксация виртуальных машин при подготовке к развертыванию в качестве шаблонов.

Нет

Копировать разрешения шаблона (Copy Template Permissions)

Установите этот флажок, чтобы установить для виртуальной машины такие же разрешения, как и у используемого шаблона.

Нет

Виртуальные диски (Instance Images)

Нажмите Прикрепить (Attach), чтобы подключить плавающий диск к виртуальной машине, или нажмите Создать (Create), чтобы добавить новый виртуальный диск. Чтобы добавить или удалить дополнительные виртуальные диски, нажимайте кнопки и . Нажмите Изменить (Edit), чтобы изменить конфигурацию виртуального диска, который уже был подключен или создан.

Нет

Сетевые интерфейсы (с привязкой к vNIC профилю) (Instantiate VM network interfaces by picking a vNIC profile)

Чтобы добавить сетевой интерфейс к виртуальной машине, необходимо выбрать vNIC-профиль из выпадающего списка nic1. Чтобы добавить или удалить дополнительные сетевые интерфейсы, нажимайте кнопки и .

Нет

8.1.2. Описание системных настроек виртуальной машины

Пояснения относительно ЦП:

  • Для процессов, не очень сильно загружающих ЦП, можно запускать виртуальные машины с общим количеством процессорных ядер, превышающим количество ядер хоста. Плюсы такого подхода следующие:

    • Можно запускать большее количество виртуальных машин, что снижает требования к оборудованию.

    • Это также позволяет конфигурировать виртуальные машины с топологиями ЦП, которые иначе были бы невозможны — например, когда количество виртуальных ядер находится в диапазоне между количеством ядер хоста и количеством потоков хоста.

  • Для достижения наилучшей производительности и особенно для процессов, сильно загружающих ЦП , на виртуальной машине следует использовать ту же топологию, что и на хосте, чтобы и для хоста, и для виртуальной машины ожидаемая работа кэша была одинаковой. Когда на хосте включена гиперпоточность, QEMU-процесс трактует гиперпотоки (hyperthreads) хоста как ядра, поэтому виртуальная машина не знает, что она работает на одном ядре с несколькими потоками. Такое поведение может повлиять на производительность виртуальной машины, поскольку виртуальное ядро, которое фактически соответствует гиперпотоку (hyperthread) в ядре хоста, может использовать один и тот же кэш вместе с другим гиперпотоком в том же ядре хоста, в то время как виртуальная машина трактует его как отдельное ядро.

В следующей таблице описаны параметры на вкладке Система (System) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine) (появляется при нажатии кнопки Показать расширенные настройки (Show Advanced Options)).

Таблица 18. Виртуальная машина: системные настройки

Имя поля Описание Требуется ли выключение и включение питания?

Оперативная память (разделяемая) (Memory Size)

Объем памяти, назначенной виртуальной машине. При выделении памяти следует учитывать потребности в обработке и хранении, имеющиеся у приложений, которые будут работать на виртуальной машине.

Если ОС поддерживает горячее подключение, то нет. В противном случае — да.

Максимум памяти (Maximum Memory)

Максимальный объем памяти, который может быть назначен виртуальной машине. Максимальный объем памяти также ограничен выбранной архитектурой гостевой машины и уровнем совместимости кластера.

Если ОС поддерживает горячее подключение, то нет. В противном случае — да.

Оперативная память (гарантированная) (Physical Memory Guaranteed)

Объём оперативной памяти, которую будет иметь виртуальная машина независимо от того, включено ли расширение (balooning).

Да

Всего ЦП (Total Virtual CPUs)

Вычислительная мощность, выделенная виртуальной машине, в виде ядер ЦП. Чтобы обеспечить высокую производительность, не следует назначать виртуальной машине ядер больше, чем есть на физическом хосте.

Если ОС поддерживает горячее подключение, то нет. В противном случае — да.

Виртуальные сокеты (Virtual Sockets)

Количество сокетов ЦП для виртуальной машины. Не следует назначать виртуальной машине сокетов больше, чем есть на физическом хосте.

Если ОС поддерживает горячее подключение, то нет. В противном случае — да

Ядра на виртуальном сокете (Cores per Virtual Socket)

Количество ядер, назначенных каждому виртуальному сокету.

Если ОС поддерживает горячее подключение, то нет. В противном случае — да

Потоков ЦП на ядро (Threads per Core)

Количество потоков, назначенных каждому ядру. При увеличении этого значения включается одновременная многопоточность (SMT). Для типов ЦП x86 и x86_64 (Intel и AMD) рекомендованное значение — 1, кроме случаев, когда требуется точная репликация топологии хоста, которую можно выполнить через закрепление ЦП. Дополнительные сведения см. в разделе Закрепление ЦП.

Если ОС поддерживает горячее подключение, то нет. В противном случае — да

Тип ВМ (Custom Emulated Machine)

Здесь можно задать тип машины. При изменении этого параметра виртуальная машина будет работать только на хостах, которые поддерживают указанный тип машины. По умолчанию получает значение, заданное для кластера.

Да

Тип ЦП (Custom CPU)

Здесь можно задать тип ЦП. При изменении этого параметра виртуальная машина будет работать только на хостах, которые поддерживают указанный тип ЦП. По умолчанию получает значение, заданное для кластера.

Да

Совместимая версия zVirt (Custom Compatibility Version)

Версия совместимости — определяет функции, поддерживаемые кластером, а также значения некоторых свойств и тип эмулируемой машины. По умолчанию виртуальная машина настроена на работу в том же режиме совместимости, что и кластер, поскольку это значение по умолчанию наследуется у кластера. В некоторых ситуациях режим совместимости по умолчанию необходимо изменить. Например, если кластер был обновлен до более новой версии совместимости, но виртуальные машины не были перезапущены. Эти виртуальные машины можно настроить на использование пользовательского режима совместимости, более старого, чем режим совместимости кластера.

Да

Тип экземпляра (Instance Type)

Тип экземпляра, на котором может быть основана аппаратная конфигурация виртуальной машины. По умолчанию значение этого поля — Пользовательский (Custom), а это значит, что виртуальная машина не подключена к типу экземпляра. Другие параметры, доступные в этом выпадающем меню: Large, Medium, Small, Tiny, XLarge и другие пользовательские типы экземпляров, созданные Администратором. Другие параметры, рядом с которыми отображается значок цепи , предварительно заполняются выбранным типом экземпляра. Если изменить одно из этих значений, то виртуальная машина будет отключена от типа экземпляра, а значок цепи будет выглядеть разорванным . Однако, если измененные параметры восстановлены до их исходных значений, виртуальная машина будет заново подключена к типу экземпляра, а разорванные звенья на значке цепи соединяться вновь .

Поддержка типов экземпляров признана устаревшей и будет удалена в одном из будущих релизов.

Да

Аппаратный часовой пояс (Hardware Clock Time Offset)

Здесь можно настроить смещение часового пояса на гостевых аппаратных часах. Для Windows оно должно соответствовать часовому поясу, заданному на гостевой машине. В большинстве установок Linux по умолчанию на аппаратных часах должно быть время GMT+00:00.

Да

Политика серийных номеров (Serial Number Policy)

Переопределите политик на уровне системы и кластера для назначения серийных номеров виртуальным машинам. Следует применять политику, уникальную для такой виртуальной машины:

  • Использовать кластер по умолчанию (Хост ID) (Cluster Default (Host ID)): Используйте системные значения по умолчанию, которые настраиваются в базе данных Менеджера управления и имена ключей DefaultSerialNumberPolicy и DefaultCustomSerialNumber. Значение по умолчанию для `DefaultSerialNumberPolic`y — это «Хост ID (Host ID)».

  • Хост ID (Host ID): Здесь можно установить серийный номер конкретной виртуальной машины в значение, соответствующее UUID хоста.

  • Код ВМ (Vm ID): Здесь можно установить серийный номер конкретной виртуальной машины в значение, соответствующее UUID этой виртуальной машины.

  • Настраиваемый серийный номер (Custom serial number): Выбор этого значения позволит установить серийный номер каждой виртуальной машины в значение, указанный в параметре Индивидуальный серийный номер (Custom serial number).

Да

Индивидуальный серийный номер (Custom serial number)

Здесь можно задать пользовательский серийный номер, который будет применен к этой виртуальной машине. Поле ввода активно только после выбора пункта Настраиваемый серийный номер (Custom serial number) из списка Политика серийных номеров (Serial Number Policy).

Да

8.1.3. Описание настроек первоначального запуска виртуальной машины

В следующей таблице описаны параметры на вкладке Запуск инициализации (Initial Run) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine). Параметры в этой таблице видны только при установленном флажке Cloud-Init/Sysprep, а некоторые параметры видны только если в списке Операционная система (Operating System) на вкладке Общее (General) выбран дистрибутив ОС на основе Linux или одна из версий Windows, как описано ниже.

В настоящей таблице не указано, требуется ли выключение и включение питания, так как эти настройки применяются к первому запуску виртуальной машины, при этом машина не работает во время настройки этих параметров.

Таблица 19. Виртуальная машина: параметры первого запуска

Имя поля Операционная система (Operating System) Описание

Cloud-Init/Sysprep

Linux, Windows

Этот флажок регулирует, будет ли Cloud-Init или Sysprep использоваться для инициализации виртуальной машины.

Имя хоста ВМ (VM Hostname)

Linux, Windows

Имя хоста виртуальной машины.

Домен (Domain)

Windows

Домен Active Directory, к которому относится виртуальная машина.

Название организации (Organization Name)

Windows

Название организации, к которой относится виртуальная машина. Этот параметр соответствует текстовому полю, где указывается название организации, которое отображается при первом запуске машины, работающей на Windows.

Организационная единица Active Directory (Active Directory OU)

Windows

Организационное подразделение в домене Active Directory, к которому относится виртуальная машина.

Настроить временную зону (Configure Time Zone)

Linux, Windows

Часовой пояс для виртуальной машины. Необходимо установить флажок и выбрать часовой пояс из списка Часовой пояс (Time Zone).

Пароль администратора (Admin Password)

Windows

Пароль пользователя с правами администратора для виртуальной машины. Необходимо нажать на раскрывающую стрелку , чтобы отобразились настройки этого параметра.

  • Пользователь уже установил пароль (Use already configured password): Этот флажок устанавливается автоматически в окне Изменить виртуальную машину (Edit Virtual Machine) после указания первоначального пароля пользователя с правами администратора при создании виртуальной машины в окне Новая виртуальная машина (New Virtual Machine). Необходимо снять этот флажок, чтобы стали активны поля Пароль (Admin Password) и Подтвердите пароль (Verify Admin Password), и появилась возможность задать новый пароль.

  • Пароль администратора (Admin Password): Пароль пользователя с правами администратора для виртуальной машины. Введите пароль в этом текстовом поле и в текстовом поле Проверить пароль администратора (Verify Admin Password), чтобы проверить правильность ввода пароля.

Аутентификация (Authentication)

Linux

Подробные сведения об аутентификации для виртуальной машины. Необходимо нажать на раскрывающую стрелку , чтобы отобразились настройки этого параметра.

  • Пользователь уже установил пароль (Use already configured password): Этот флажок устанавливается автоматически в окне Изменить виртуальную машину (Edit Virtual Machine) после указания первоначального пароля пользователя с правами администратора при создании виртуальной машины в окне Новая виртуальная машина (New Virtual Machine). Необходимо снять этот флажок, чтобы стали активны поля Имя пользователя (User Name), Пароль (Admin Password) и Подтвердите пароль (Verify Admin Password), и появилась возможность задать нового пользователя и его пароль.

  • Имя пользователя (User Name): имя пользователя с правами администратора.

  • Пароль (Password): Пароль этого пользователя для операционной системы виртуальной машины. Введите пароль в этом текстовом поле и в текстовом поле Проверить пароль (Verify Password), чтобы проверить правильность ввода пароля.

  • Ключи SSH-авторизации (SSH Authorized Keys): SSH-ключи добавятся в файл авторизованных ключей виртуальной машины. Можно указать несколько SSH-ключей: каждый SSH-ключ необходимо вводить на отдельной строке.

  • Пересоздать ключи SSH (Regenerate SSH Keys): Повторно сгенерировать SSH-ключи для виртуальной машины.

Пользовательская локализация (Custom Locale)

Windows

Пользовательские региональные настройки для виртуальной машины. Региональные настройки должны быть в формате en-US. Необходимо нажать на раскрывающую стрелку , чтобы отобразились настройки этого параметра.

  • Язык ввода (Input Locale): Региональные настройки для команд пользователя.

  • Язык интерфейса (UI Language): Язык пользовательского интерфейса, в частности таких элементов как кнопки и меню.

  • Язык системы (System Locale): Региональные настройки для всей системы.

  • Локаль пользователя (User Locale): Региональные настройки для пользователей.

Сети (Networks)

Linux

Связанные с сетью настройки для виртуальной машины. Необходимо нажать на раскрывающую стрелку , чтобы отобразились настройки этого параметра.

  • Сетевой протокол Cloud-Init: Протокол, используемый для создания конфигурации сети полезной нагрузки виртуальной машины (Opendtack Metadata и ENI).

  • DNS-серверы (DNS Servers): DNS-серверы, которые будет использовать виртуальная машина.

  • Домен поиска DNS (DNS Search Domains): домены поиска DNS, которые будет использовать виртуальная машина.

  • Гостевой сетевой интерфейс (In-guest Network Interface Name): здесь можно настроить сетевые интерфейсы для виртуальной машины. Установите этот флажок и кнопками или добавьте сетевые интерфейсы к виртуальной машине или удалите их из нее. После нажатия кнопки появится несколько полей, в которых можно указать, надо ли использовать DHCP или настроить IP-адрес, маску сети и шлюз, а также указать, будет ли запускаться сетевой интерфейс при начальной загрузке.

Пользовательский скрипт (Custom Script)

Linux

Пользовательские скрипты, которые будут выполняться на виртуальной машине во время ее запуска. Указанные в этом поле скрипты — это пользовательские разделы YAML, добавленные к тем, что предоставлены Менеджером управления, и позволяющие автоматизировать задачи, например, создание пользователей и файлов, настройку репозиториев dnf и выполнение команд.

Sysprep

Windows

Пользовательское определение настроек Sysprep. Определение настроек должно быть в формате полного файла ответов для автоматической установки. Можно скопировать и вставить файлы ответов по умолчанию в каталоге /usr/share/ovirt-engine/conf/sysprep/ на машине с Менеджером управления и изменить поля нужным образом. Дополнительные сведения см. в разделе Шаблоны.

Ignition 2.3.0

Red Hat Enterprise Linux CoreOS

Когда Red Hat Enterprise Linux CoreOS выбрана в качестве операционной системы, этот флажок регулирует, будет ли Ignition использоваться для инициализации виртуальной машины.

8.1.4. Описание настроек консоли виртуальной машины

В следующей таблице описаны параметры на вкладке Консоль (Console) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 20. Виртуальная машина: настройки консоли

Имя поля Дополнительный элемент Описание Требуется ли выключение и включение питания?

Графический адаптер (Graphical Console)

Группа настроек графического адаптера виртуальной машины

Да

Режим Headless (Headless Mode)

Установите этот флажок, если виртуальной машине не нужна графическая консоль и она работает без графического адаптера. Когда флажок установлен, все другие поля в разделе Графический адаптер (Graphical Console) будут неактивны. На Пользовательском портале значок Консоль (Console) в подробном представлении виртуальной машины тоже будет неактивным.

Дополнительные сведения и предварительные условия для использования фонового режима см. в разделе Настройка фоновых виртуальных машин (Headless Virtual Machines).

Да

Тип видеокарты (Video Type)

Здесь можно задать графическое устройство. QXL установлено по умолчанию и поддерживает оба графических протокола. VGA поддерживает только протокол VNC.

Да

Графический протокол (Graphics protocol)

Здесь можно задать, какой протокол отображения будет использоваться. SPICE — это протокол, который используется по умолчанию. VNC можно использовать в качестве альтернативы. Чтобы разрешить оба протокола, необходимо выбрать SPICE + VNC.

Да

Раскладка клавиатуры в VNC (VNC Keyboard Layout)

Здесь можно задать раскладку клавиатуры для виртуальной машины. Этот параметр доступен только при использовании протокола VNC.

Да

Действие при отключении консоли (Console Disconnect Action)

Здесь можно задать, что будет происходить при отключении консоли. Это относится только к подключениям консоли по протоколам SPICE и VNC. Этот параметр можно изменить во время работы виртуальной машины, но изменения вступят в силу, только когда будет установлено новое подключение консоли. Можно выбрать один из следующих вариантов:

  • Нет действий (No action): никакие действия не предпринимаются.

  • Блокировка экрана (Lock screen): это параметр по умолчанию. Для всех машин Linux и для рабочих станций Windows будет заблокирован сеанс активного на тот момент пользователя. На серверах Windows будет заблокирована рабочая станция и активный на тот момент пользователь.

  • Выход пользователя (Logout user): на всех машинах Linux и рабочих станциях Windows сеанс активных на тот момент пользователей будет завершен. На серверах Windows рабочие станции и активные на тот момент пользователи выйдут из системы.

  • Выключить виртуальную машину (Shutdown virtual machine): инициирует корректное завершение работы виртуальной машины.

  • Перезагрузка виртуальной машины (Reboot virtual machine): инициирует корректную перезагрузку виртуальной машины.

Для действий Выключить виртуальную машину (Shutdown virtual machine) и Перезагрузка виртуальной машины (Reboot virtual machine) также активируется поле Задержка действия Отключить в минутах, в котором можно указать задержку для выбранного действия.

Нет

Мониторы

Количество мониторов для виртуальной машины. Этот параметр доступен только для виртуальных рабочих станций, использующих протокол отображения SPICE. Можно выбрать 1, 2 или 4. Обратите внимание, что системы Windows с драйверами WDDMDoD не поддерживают больше одного монитора.

Да

Включить USB (USB Enabled)

Здесь можно задать USB-перенаправление для виртуальных машин, использующих протокол SPICE.По умолчанию флажок снят:

  • Отключен (флажок снят): устройства USB-контроллера добавляются согласно значению devices.usb.controller в файле конфигурации osinfo-defaults.properties. По умолчанию для всех операционных систем x86 и x86_64 — piix3-uhci.

  • Включен (флажок установлен): включает встроенную функцию USB-перенаправления KVM/SPICE для виртуальных машин Linux и Windows. Виртуальным машинам не нужны никакие внутригостевые агенты или драйверы для встроенной функции USB-перенаправления.

Да

Поддержка смарт-карт (Smartcard Enabled)

Смарт-карты — это внешнее аппаратное средство защиты, которое используется многими компаниями в качестве токенов аутентификации. Смарт-карты можно использовать для защиты виртуальных машин. Поставьте или снимите этот флажок, чтобы активировать или деактивировать аутентификацию по смарт-карте для отдельных виртуальных машин.

Да

SSO (единый вход) (Single Sign On method)

При включении единого входа пользователи могут авторизоваться в гостевой операционной системе, когда с помощью гостевого агента подключаются к виртуальной машине через Пользовательский портал.

  • Отключить единый вход (Disable Single Sign On): выберите этот параметр, если не хотите, чтобы гостевой агент пытался авторизоваться на виртуальной машине.

  • Использовать гостевой агент (Use Guest Agent): включение единого входа: гостевому агенту разрешается авторизовать вас на виртуальной машине.

Если выбран параметр Использовать гостевой агент (Use Guest Agent), то нет. В противном случае — да.

Раздел Дополнительные параметры (Advanced Parameters)

Группа настроек

Отключить строгую проверку пользователей (Disable strict user checking)

Нажмите на стрелку и установите флажок, чтобы использовать этот параметр. Если этот флажок стоит, виртуальную машину не нужно перезагружать, когда к ней подключается другой пользователь.

По умолчанию строгая проверка включена, поэтому только один пользователь может подключиться к консоли виртуальной машины. Ни один другой пользователь не сможет открыть консоль той же виртуальной машины, пока ее не перезагрузят. Исключение: пользователь с ролью SuperUser может подключиться в любое время и заменить существующее подключение. После подключения пользователя с ролью SuperUser ни один обычный пользователь не сможет подключиться снова, пока виртуальную машину не перезагрузят.

Отключать строгую проверку следует с осторожностью, поскольку можно раскрыть сессию предыдущего пользователя новому пользователю.

Нет

Включить звуковую карту (Soundcard Enabled)

Устройство звуковой карты необязательно для всех вариантов использования виртуальной машины. Если звуковая карта необходима, ее можно включить здесь.

Да

Включить передачу файлов SPICE (Enable SPICE file transfer)

Здесь можно задать, сможет ли пользователь перетаскивать файлы с внешнего хоста в консоль SPICE виртуальной машины. Этот параметр доступен только для виртуальных машин, использующих протокол SPICE. Флажок установлен по умолчанию.

Нет

Включить буфер обмена SPICE (Enable SPICE clipboard copy and paste)

Здесь можно задать, сможет ли пользователь копировать и вставлять контент с внешнего хоста в консоль SPICE виртуальной машины. Этот параметр доступен только для виртуальных машин, использующих протокол SPICE. Флажок установлен по умолчанию.

Нет

Раздел последовательной консоли (Serial Console Section)

Группа настроек

Консольный порт VirtIO-serial (Enable VirtIO serial console)

Последовательная консоль VirtIO эмулируется через каналы VirtIO с помощью SSH и пар ключей и позволяет получить доступ к последовательной консоли виртуальной машины напрямую из командной строки клиентской машины, чтобы не открывать консоль через Портал администрирования или Пользовательский портал. Последовательной консоли требуется прямой доступ к Менеджеру управления, поскольку Менеджер управления выступает в качестве прокси для подключения, предоставляет информацию о размещении виртуальных машин и хранит ключи аутентификации. Установите этот флажок, чтобы включить консоль VirtIO на виртуальной машине. Требуется правило межсетевого экрана. См. раздел Открытие последовательной консоли виртуальной машины.

Да

no con open

Рисунок 1. Отсутствие возможности выбора графической консоли, работающей с включённым режимом Headless (Headless Mode) виртуальной машине на стартовой странице Пользовательского портала

vm con disactive portal

Рисунок 2. Неактивная кнопка графической консоли, работающей с включённым режимом Headless (Headless Mode) виртуальной машине в подробном представлении на Пользовательском портале

vm con disactive admin

Рисунок 3. Неактивная кнопка графической консоли, работающей с включённым режимом Headless (Headless Mode) виртуальной машине на Портале администратора

8.1.5. Описание настроек хоста виртуальных машин

В следующей таблице описаны параметры на вкладке Хост (Host) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 21. Виртуальная машина: настройки хоста

Имя поля Дополнительный элемент Описание Требуется ли выключение и включение питания?

Запустить на (Start Running On)

Здесь указывается предпочтительный хост, на котором следует запустить виртуальную машину. Можно выбрать один из следующих вариантов:

  • Любом хосте в кластере (Any Host in Cluster) — виртуальная машина может запускаться и работать на любом из доступных хостов кластера.

  • Указанном хосте (Specific Host(s)) — виртуальная машина будет запускаться на конкретном хосте кластера. Однако Менеджер управления или администратор может перенести виртуальную машину на другой хост кластера в зависимости от настроек миграции и высокой доступности виртуальной машины. Выберите конкретный хост или группу хостов из списка доступных хостов.

Нет. Виртуальная машина может мигрировать на такой хост в процессе работы.

Параметры ЦП (CPU options)

Passthrough ЦП хоста (Pass-Through Host CPU)

Если выбрана эта опция, то виртуальные машины могут использовать флаги ЦП хоста. Если выбрана эта опция, то Параметры миграции (Migration Options) устанавливаются в значение Разрешить только ручную миграцию (Allow manual migration only).

Да

Миграция только на хосты с одинаковой частотой TSC (Migrate only to hosts with the same TSC frequency)

Если выбрана эта опция, то эта виртуальная машина может быть перенесена только на хост с такой же частотой TSC. Эта опция подходит только для виртуальных машин с признаком высокой доступности.

Да

Параметры миграции (Migration Options)

Режим миграции (Migration mode)

Здесь можно выбрать параметры запуска и миграции виртуальной машины. Если эти параметры не заданы, то запуск или перенос виртуальной машины будут осуществляться в соответствии с политикой соответствующего кластера.

  • Разрешить ручную и автоматическую миграцию (Allow manual and automatic migration) — миграция виртуальной машины с одного хоста на другой может выполняться автоматически в соответствии со статусом среды или вручную администратором.

  • Разрешить только ручную миграцию (Allow manual migration only) — миграция виртуальной машины с одного хоста на другой может выполняться только вручную администратором.

  • Не разрешать миграцию (Do not allow migration) — автоматическая и ручная миграция виртуальной машины запрещены.

Нет

Политика миграции (Migration policy)

Здесь задается политика синхронизации состояния памяти при миграции.

  • Использовать кластер по умолчанию (Minimal downtime) (Cluster default (Minimal downtime)) — переопределения в vdsm.conf все еще применяются. Гостевой хук-механизм выключен.

  • Minimal downtime: миграция виртуальных машин в типичных ситуациях разрешена. У виртуальных машин не должно быть значительного простоя. Процесс миграции будет прерван, если синхронизация состояния памяти слишком затянулась (зависит от итераций QEMU, максимум 500 миллисекунд). Гостевой хук-механизм включен.

  • Post-copy migration: когда применяется эта политика, она приостанавливает виртуальные ЦП мигрирующей виртуальной машины на хосте-источнике, переносит только минимальное количество страниц памяти, активирует виртуальные ЦП виртуальной машины на хосте-приемнике и переносит оставшиеся страницы памяти, пока виртуальная машина работает на хосте-приемнике.

Политика миграции с пост-копированием сначала пытается провести предварительное копирование, чтобы убедиться, что синхронизация состояния памяти пройдет успешно. Миграция переключается в режим с пост-копированием, если при миграции виртуальной машины затянулась синхронизация состояния памяти.

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

Недостаток этой политики заключается в том, что на этапе пост-копирования виртуальная машина может сильно замедлиться из-за переноса недостающих частей памяти между хостами.

Если сетевое соединение прерывается до завершения процесса пост-копирования, то Менеджер управления приостанавливает, а затем выключает работающую виртуальную машину. Не прибегайте к миграции с пост-копированием, если доступность виртуальной машины критически важна или если сеть миграции нестабильна.
  • Suspend workload if needed: Эта политика разрешает миграцию виртуальных машин в большинстве случаев, включая перенос виртуальных машин, на которых запущены ресурсоемкие процессы, но из-за этого могут происходить более длительные простои ВМ, чем при других настройках. Миграция, тем не менее, может быть прервана при экстремальных нагрузках. Гостевой хук-механизм включен.

  • Very large VMs: Эта политика включает функцию миграции без копирования и переопределяет политику, заданную на уровне кластера. Подробнее об этой функции см. в разделе Миграция очень больших виртуальных машин.

Нет

Включить шифрование при миграции (Enable migration encryption)

Эта политика позволяет шифровать виртуальную машину в процессе миграции.

  • Использовать кластер по умолчанию (Не шифровать) (Cluster default (Don’t encrypt)).

  • Шифровать (Encrypt).

  • Не шифровать (Don’t encrypt).

Нет

Параллельные миграции (Parallel Migrations)

Позволяет включить функцию параллельных соединений для миграции. Подробнее см. в разделе Настройка параллельных соединений для миграции.

Нет

Количество соединений ВМ миграций (Количество соединений ВМ миграций)

Позволяет указать количество соединений для параллельных миграций. Активируется при выборе Custom в поле Параллельные миграции (Parallel Migrations). Допустимые значения от 2 до 255.

Нет

Настройки NUMA (Configure NUMA)

Количество узлов NUMA (NUMA Node Count)

Количество виртуальных узлов NUMA, доступных на хосте, которые можно назначить виртуальной машине.

Нет

Привязка NUMA (NUMA Pinning)

Здесь открывается окно Топология NUMA (NUMA Topology). В окне отображается общее количество ЦП, памяти и узлов NUMA хоста, а также виртуальные узлы NUMA виртуальной машины. Можно вручную закрепить виртуальные узлы NUMA на узлах NUMA хоста, перетащив каждый виртуальный узел vNUMA из поля справа на узел NUMA слева.

Можно также установить Режим тонкой настройки (Tune Mode) для выделения памяти:

  • С чередованием (Interleave): память выделяется из нескольких узлов по циклическому алгоритму (round-robin).

  • Предпочтительный (Preferred): память выделяется из одного предпочтительного узла. Если памяти недостаточно, то она может быть выделена из других узлов.

  • Строгий (Strict): выделение памяти не будет выполнено, если память не может быть выделена на целевом узле.

Если задано закрепление NUMA, то Режим миграции (Migration mode) в Параметрах миграции (Migration Options) установлены в значение Разрешить только ручную миграцию (Allow manual migration only).

Да

Рекомендации по автоматическому закреплению (Auto Pinning Policy)

Здесь можно установить автоматическое закрепление NUMA.

  • Отсутствует (None): не вносит изменений в виртуальную машину.

  • Изменить размер и прикрепить (Resize and Pin): максимально расширяет топологию ЦП и создает настройки закрепления ЦП и NUMA.

Нет

8.1.6. Описание настроек высокой доступности виртуальной машины

В следующей таблице описаны параметры на вкладке Высокая доступность (High Availability) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 22. Виртуальная машина: настройки высокой доступности

Имя поля Описание Требуется ли выключение и включение питания?

Высокая доступность (Highly Available)

Установите этот флажок, чтобы у виртуальной машины был признак высокой доступности. Например, во время обслуживания хоста все виртуальные машины автоматически мигрируют на лету на другой хост. Если хост выходит из строя и перестает отвечать на запросы, то только виртуальные машины с признаком высокой доступности перезапускаются на другом хосте. Если системный администратор выключил хост вручную, то виртуальная машина не будет автоматически перенесена на лету на другой хост.

Да

Целевой домен хранения для аренды ВМ (Target Storage Domain for VM Lease)

Здесь можно выбрать домен хранения для сохранения аренды виртуальной машины или параметр Домен хранения не выбран (No VM Lease), чтобы отключить эту функцию. Если выбран домен хранения, он будет удерживать аренду виртуальной машины на специальном томе, который позволяет запустить виртуальную машину на другом узле, если исходный узел остается без питания или перестает отвечать на запросы.

Если аренда задана, то единственным доступным Действием (при возобновлении) (Resume Behavior) будет Принудительно завершить (Kill).

Да

Действие (Resume Behavior)

Здесь указывается, какие действия виртуальная машина, приостановленная из-за ошибок ввода-вывода хранилища, должна делать после восстановления соединения с хранилищем. Можно задать требуемое действие при возобновлении работы, даже если у виртуальной машины нет признака высокой доступности.

Доступны следующие опции:

  • Автовозобновление (Auto Resume): работа виртуальной машины возобновляется автоматически, без вмешательства пользователя. Этот вариант рекомендуется для виртуальных машин, у которых нет признака высокой доступности и которым не нужно вмешательство пользователя, чтобы выйти из состояния паузы.

  • Оставить на паузе (Leave Paused): виртуальная машина остается в режиме паузы до тех пор, пока ее работу не возобновят или ее не перезапустят вручную.

  • Принудительно завершить (Kill): виртуальная машина автоматически возобновит работу, если ошибку ввода-вывода устранят в течение 80 секунд. Однако если пройдет более 80 секунд, то виртуальная машина будет принудительно выключена. Этот вариант рекомендуется для виртуальных машин с признаком высокой доступности, чтобы Менеджер управления мог перезапустить их на другом хосте, где нет ошибки ввода-вывода хранилища.

Принудительно завершить (Kill) — единственный доступный вариант при использовании аренды виртуальных машин.

Нет

Приоритет запуска/очередь миграции (Priority for Run/Migration queue)

Здесь виртуальным машинам назначаются уровни приоритета, согласно которым они будут мигрировать или перезапускаться на другом хосте.

Нет

Watchdog

Пользователи могут подключить карту сторожевого сервиса к виртуальной машине. Сторожевой сервис — это таймер, который используется для автоматического обнаружения сбоев и восстановления после них. Когда сторожевой таймер установлен, он непрерывно отсчитывает время до нуля, пока система работает, и периодически перезапускается системой, чтобы не допустить его обнуления. Если таймер достигает нуля, это означает, что система не смогла сбросить таймер, и, следовательно, в ней произошел сбой. Затем предпринимаются корректирующие действия для устранения сбоя. Эта функция особенно полезна для серверов, которым нужна высокая доступность.

Модель (Watchdog Model): Модель карты сторожевого сервиса, которая будет назначена виртуальной машине. В настоящее время поддерживается только модель i6300esb.

Действие (Watchdog Action)

8.1.7. Описание настроек выделения ресурсов виртуальных машин

В следующей таблице описаны параметры на вкладке Выделение ресурсов (Resource Allocation) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 23. Виртуальная машина: настройки выделения ресурсов

Имя поля Дополнительный элемент Описание Требуется ли выключение и включение питания?

Выделение ЦП (CPU Allocation)

Профиль ЦП (CPU Profile)

Профиль ЦП, назначенный виртуальной машине. Профили ЦП определяют максимальную вычислительную мощность, которую виртуальная машина может получить на хосте, на котором она работает, выраженную в процентах от общей вычислительной мощности, доступной этому хосту. Профили ЦП определяются на уровне кластера в зависимости от качества записей службы, созданных для центров данных.

Нет

Общие ЦП (CPU Shares)

Здесь можно настроить уровень ресурсов ЦП, которые виртуальная машина может запросить, относительно других виртуальных машин:

  • Выключено (Disabled).

  • Низкий (Low) = 512.

  • Средний (Medium) = 1 024.

  • Высокий (High) = 2 048.

  • Пользовательский (Custom) = пользовательский уровень долей ЦП определяет пользователь.

Нет

Политика Закрепления ЦПУ (CPU Pinning Policy)

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

  • None — закрепление ЦП не используется.

  • Manual — запускает указанный вручную виртуальный процессор на определенном физическом процессоре на определенном хосте. Доступно только при закреплении ВМ за определённым хостом. При выборе необходимо определить топологию закрепления в поле Топология привязки ЦП (CPU Pinning topology).

  • Resize and Pin NUMA — изменяет размеры виртуального ЦП и топологии NUMA виртуальной машины в соответствии с хостом, а также закрепляет их за ресурсами хоста.

  • Dedicated — виртуальные процессоры строго привязаны к набору физических процессоров хоста. Набор физических процессоров выбирается таким образом, чтоб соответствовать требуемой топологии виртуальных процессоров. Если виртуальная машина настроена с узлами NUMA, они будут закреплены автоматически.

  • Isolate Threads — каждый виртуальный процессор размещается на отдельном физическом ядре. Если виртуальная машина настроена с узлами NUMA, они будут закреплены автоматически.

Да

Топология привязки ЦП (CPU Pinning topology)

Позволяет виртуальному процессору виртуальной машины (vCPU) работать на определенном физическом процессоре (pCPU) на определенном хосте. Синтаксис закрепления процессора: v#p[_v#p], например:

  • 0#0 для закрепления vCPU 0 на pCPU 0.

  • 0#0_1#3 для закрепления vCPU 0 на pCPU 0, а vCPU 1 на pCPU 3.

  • 1#1-4,^2 для закрепления vCPU 1 на одном из pCPU в диапазоне от 1 до 4, кроме pCPU 2.

Топология привязки ЦП (CPU Pinning Topology) заполняется автоматически, когда активировано автоматическое закрепление NUMA. Чтобы закрепить виртуальную машину на хосте, необходимо также выбрать следующие параметры на вкладке Хост (Host):

  • Запустить на (Start Running On): Указанном хосте (Specific Host(s)).

  • Passthrough ЦП хоста (Pass-Through Host CPU)

Если настроено закрепление ЦП и изменен параметр Запустить на (Start Running On): Указанном хосте (Specific Host(s)), то после нажатия OK появится окно «Топология закрепления ЦП будет потеряна (CPU pinning topology will be lost)». Если задан этот параметр, то Параметры миграции (Migration Options) на вкладке Хост (Host) будут установлены в значение Разрешить только ручную миграцию (Allow manual migration only).

Да

Выделение памяти (Memory Allocation)

Включить Ballooning (Memory Balloon Enabled)

Этот параметр включает устройство балунинга памяти для виртуальной машины. Для того, чтобы устройство при этом работало, в кластере должно быть разрешено перераспределение памяти (memory overcommitment). Этот параметр следует включить для приложений, которые внезапно выделяют большой объем памяти, но при этом необходимо установить одинаковое значение гарантированной и заданной памяти. Балунинг следует использовать для приложений и нагрузок, которые медленно потребляют память, периодически освобождают память или долгое время находятся в спящем режиме, например, виртуальные рабочие станции.

Да

Модуль ТРМ (Trusted Platform Module)

Включить TPM (TPM Device Enabled)

Этот параметр разрешает добавление эмулируемого устройства TPM. Установите этот флажок, чтобы добавить эмулируемое устройство TPM к виртуальной машине. Устройства TPM можно использовать только на машинах x86_64 с микропрограммным обеспечением UEFI и машинах PowerPC с установленным микропрограммным обеспечением pSeries. Дополнительные сведения см. в разделе Добавление устройства доверенного платформенного модуля (TPM).

Да

Потоки ввода-вывода (IO Threads)

Количество потоков I/O (IO Threads Enabled)

Этот параметр включает потоки ввода-вывода. Установите этот флажок, чтобы повысить скорость дисков с интерфейсом VirtIO, закрепив их на потоке отдельно от других функций виртуальной машины. Повышение производительности диска увеличивает общую производительность виртуальной машины. Диски с интерфейсами VirtIO закреплены на потоке ввода-вывода по циклическому алгоритму (round-robin).

Да

Очереди (Queues)

Включить мульти-очерёдность (Multi Queues Enabled)

Этот параметр разрешает несколько очередей. Флажок установлен по умолчанию. Можно создать до четырех очередей на каждой виртуальной сетевой карте в зависимости от количества доступных виртуальных ЦП. Можно задать другое количество очередей на каждой виртуальной сетевой карте через следующее пользовательское свойство:

engine-config -s "CustomDeviceProperties={type=interface;prop={other-nic-properties;queues=[1-9][0-9]*}}"

Здесь other-nic-properties — это список из уже настроенных пользовательских свойств сетевой карты, перечисленных через точку с запятой.

Да

Тип диска (Storage Allocation)

Параметр Тип диска (Storage Allocation) доступен, только когда виртуальная машина создана из шаблона.

Не применимо

Тонкий (Thin)

Оптимизированное использование пространства хранилища. Дисковое пространство выделяется только тогда, когда в нем возникает необходимость. Если выбран этот параметр, формат дисков будет обозначен как QCOW2, и его нельзя будет изменить.

Не применимо

Клонированный (Clone)

Оптимизированная скорость гостевых операций чтения и записи. Все дисковое пространство, затребованное в шаблоне, выделяется во время клонирования. Возможные форматы дисков: QCOW2 или Raw.

Не применимо

VirtIO-SCSI (VirtIO-SCSI Enabled)

Пользователь может включить или выключить использование VirtIO-SCSI на виртуальных машинах.

Не применимо

Включить VirtIO-SCSI мульти-очередность (VirtIO-SCSI Multi Queues Enabled)

Параметр доступен только при установленном флажке VirtIO-SCSI (VirtIO-SCSI Enabled). Установите этот флажок, чтобы включить несколько очередей в драйвере VirtIO-SCSI. Этот параметр может повысить пропускную способность ввода/вывода, когда несколько потоков на одной виртуальной машине обращаются к виртуальным дискам. Он создает до четырех очередей на каждый контроллер VirtIO-SCSI в зависимости от того, сколько дисков подключено к контроллеру и сколько виртуальных ЦП доступно.

Не применимо

Выделение дискового пространства (Disk Allocation)

Параметр доступен, только когда виртуальная машина создана из шаблона.

Не применимо

Имя (Alias)

Псевдоним виртуального диска. По умолчанию псевдоним будет совпадать со значением, указанным в шаблоне.

Не применимо

Виртуальный размер (Virtual Size)

Общий объем дискового пространства, который может использовать виртуальная машина, созданная на основе шаблона. Это значение нельзя изменить. Оно приводится только для справки.

Не применимо

Формат (Format)

Формат виртуального диска. Доступные параметры: QCOW2 и Raw. Когда Тип диска (Storage Allocation) установлено в значение Тонкий (Thin), формат диска будет QCOW2. Когда Тип диска (Storage Allocation) установлено в значение Клонированный (Clone), можно выбрать либо QCOW2, либо Raw.

Не применимо

Цель (Target)

Домен хранения, в котором будет храниться виртуальный диск. По умолчанию для домена хранения будет задано то же значение, что указано в шаблоне.

Не применимо

Профиль диска (Disk Profile)

Профиль диска, который будет назначен виртуальному диску. Профили дисков создаются на основе профилей хранения, заданных в центрах данных.

Не применимо

8.1.8. Описание параметров начальной загрузки виртуальной машины

В следующей таблице описаны параметры на вкладке Параметры загрузки (Boot Options) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 24. Виртуальная машина: параметры загрузки

Имя поля Описание Требуется ли выключение и включение питания?

Первое устройство (First Device)

После установки новой виртуальной машины она должна переключиться в режим начальной загрузки, прежде чем на нее будет подано питание. Необходимо выбрать первое устройство, с которого виртуальная машина будет выполнять начальную загрузку:

  • Жесткий диск (Hard Disk).

  • CD-ROM.

  • Сеть PXE (Network (PXE)).

Да

Вторичное устройство (Second Device)

Необходимо выбрать второе устройство, с которого виртуальная машина будет выполнять начальную загрузку, если первое устройство недоступно. Первое устройство, выбранное в предыдущем варианте, не отображается в параметрах.

Да

Подключить CD (Attach CD)

Если в качестве загрузочного устройства выбран CD-ROM, то необходимо установить этот флажок и выбрать образ CD-ROM в выпадающем меню. Образы должны быть доступны в домене хранения.

Да

Включить меню для выбора загрузочного устройства (Enable menu to select boot device)

Этот параметр включает меню для выбора загрузочного устройства. После запуска виртуальной машины и подключения к консоли, но до того, как виртуальная машина начнет начальную загрузку, появится меню, где можно выбрать загрузочное устройство. Этот параметр следует включить перед начальной загрузкой, чтобы можно было выбрать нужный носитель с дистрибутивом.

Да

8.1.9. Описание настроек генератора случайных чисел для виртуальных машин

В следующей таблице описаны параметры на вкладке ГСЧ (Random Generator) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 25. Виртуальная машина: настройки генератора случайных чисел

Имя поля Описание Требуется ли выключение и включение питания?

Генератор случайных чисел (Random Generator enabled)

Установка этого флажка включает паравиртуализованное PCI-устройство генератора случайных чисел (virtio-rng). Это устройство позволяет передавать энтропию от хоста к виртуальной машине для генерации более сложного случайного числа. Обратите внимание, что установить этот флажок можно, только если на хосте есть устройство генератора случайных чисел (RNG) и оно включено в кластере хоста.

Да

Длительность периода (мс) (Period duration (ms))

Здесь можно указать продолжительность «полного цикла» или «полного периода» RNG в миллисекундах. Если не указывать, то значение libvirt по умолчанию будет равно 1 000 миллисекунд (1 секунда). Если это поле заполнено, необходимо также заполнить поле Байт один период (Bytes per period).

Да

Байт один период (Bytes per period)

Здесь можно указать, сколько байт разрешено потреблять за один период.

Да

Источник устройства: (Device source:)

Источник генератора случайных чисел. Он выбирается автоматически в зависимости от источника, который поддерживает кластер хоста.

  • /dev/urandom (/dev/urandom source) — генератор случайных чисел, предоставляемый Linux.

  • /dev/hwrng (/dev/hwrng source) — внешний аппаратный генератор.

Да

8.1.10. Описание настроек пользовательских свойств виртуальных машин

В следующей таблице описаны параметры на вкладке Доп.параметры (Custom Properties) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

Таблица 26. Настройки пользовательских свойств виртуальных машин

Имя поля Описание Рекомендации и ограничения Требуется ли выключение и включение питания?

sndbuf

Введите размер буфера для отправки исходящих данных виртуальной машины через сокет. Значение по умолчанию — 0

Да

hugepages

Введите размер большой страницы в КБ.

Задайте для большой страницы максимальный размер, который поддерживает закрепленный хост.

  • Рекомендуемый размер для x86_64 — это 1 ГБ

  • Размер большой страницы у виртуальной машины должен быть таким же, что и у большой страницы закрепленного хоста.

  • Объем памяти виртуальной машины должен соответствовать выбранному размеру свободных больших страниц закрепленного хоста. Размер узла NUMA должен быть в несколько раз больше, чем выбранный размер большой страницы.

Да

vhost

Отключает vhost-net (сетевой драйвер virtio на базе ядра) на виртуальных сетевых картах, подключенных к виртуальной машине. Для отключения vhost у этого свойства должен быть формат — LogicalNetworkName: false. После этого виртуальная машина запустится без настройки vhost-net на виртуальной сетевой карте, подключенной к LogicalNetworkName.

vhost-net обеспечивает лучшую производительность по сравнению с virtio-net и при наличии включается по умолчанию на всех сетевых картах виртуальных машин. При выключении этого свойства легче изолировать и диагностировать проблемы производительности или решить проблемы, связанные с vhost-net; например, в случае неудачной миграции тех виртуальных машин, на которых vhost не существует.

Да

nvram_template

Позволяет указать путь к файлу шаблона NVRAM. Может потребоваться для включения функции SecureBoot

Да

sap_agent

Включение SAP-мониторинга на виртуальной машине Задайте значение true или false.

Да

viodiskcache

Режим кэширования для диска virtio.

  • writethrough параллельно записывает данные в кэш хоста виртуализации и на физический диск, работает медленнее и подвержен проблемам с масштабированием, использовать лучше для небольшого числа пользователей с низкими требованиями к вводу-выводу

  • writeback не копирует изменения из кэша на диск, кэшируется на хосте виртуализации

  • none — Ввод-вывод от гостя не кэшируется на хосте, но может храниться в кэше диска с обратной записью. Используйте эту опцию для пользователей с большими требованиями к вводу-выводу. Этот вариант, как правило, является лучшим выбором и единственным вариантом поддержки миграции.

Чтобы обеспечить целостность данных на случай, если во время миграции произойдет сбой в хранилище, сети или на хосте, не переносите виртуальные машины с включенным viodiskcache, кроме случаев, когда также включена кластеризация ВМ или кластеризация на уровне приложения.

Да

extra_cpu_flags

Позволяет указать дополнительные флаги ЦП

Да

scsi_hostdev

Если добавить SCSI-устройство хоста на виртуальную машину, то можно указать оптимальный драйвер SCSI-устройства хоста. Подробности см. в разделе Добавление устройства хоста к виртуальной машине.

  • scsi_generic: (По умолчанию) Дает гостевой операционной системе доступ к SCSI-устройствам хоста, которые поддерживаются ОС и подключены к хосту. Используйте этот драйвер для SCSI-чейнджеров, которым нужен raw-доступ (например, для CD-чейнджеров или чейнджеров лент).

  • scsi_block: Аналогичен scsi_generic, но быстрее и надежнее. Используйте для дисковых устройств SCSI. Если для базового устройства (и это жесткий диск) желательна функция trim или discard, то используйте этот драйвер.

  • scsi_hd: Обеспечивает производительность и снижение накладных расходов. Поддерживает большое количество устройств. Использует стандартную схему наименования устройств SCSI. Может использоваться с aio-native. Используйте этот драйвер для твердотельных накопителей с высокой производительностью.

  • virtio_blk_pci: Обеспечивает наибольшую производительность без накладных расходов SCSI. Поддерживает идентификацию устройств по серийному номеру.

Если не уверены, попробуйте использовать scsi_hd.

Да

Чем выше значение пользовательского свойства sndbuf, тем больше происходит сбоев связи между хостами и не отвечающими виртуальными машинами.

8.1.11. Описание настроек значков виртуальных машин

На виртуальные машины и шаблоны можно добавить пользовательские значки. С помощью пользовательских значков легче различать виртуальные машины на Пользовательском портале. В следующей таблице описаны параметры на вкладке Значок (Icon) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

В данную таблицу не включена информация о том, требуется ли выключение и включение питания, так как эти настройки применяются к представлению виртуальной машины на Портале администрирования, а не к ее конфигурации.

Таблица 27. Виртуальная машина: настройки значков

Имя кнопки Описание

Загрузить (Upload)

Нажмите на эту кнопку, чтобы выбрать пользовательское изображение в качестве значка виртуальной машины.

Применяются следующие ограничения:

  • Поддерживаемые форматы: jpg, png, gif.

  • Максимум 24 КБ.

  • Максимум 150 (Ш) * 120 (В) пикселей.

По умолчанию (Use default)

Используются значение по умолчанию.

8.1.12. Описание настроек групп и меток сходства

На виртуальные машины можно добавить метки и группы сходства, чтобы определить место работы виртуальных машин относительно друг друга и указанных хостов. В следующей таблице описаны параметры на вкладке Группы сходства (Affinity) окон Новая виртуальная машина (New Virtual Machine) и Изменить виртуальную машину (Edit Virtual Machine).

В данную таблицу не включена информация о том, требуется ли выключение и включение питания.

Таблица 28. Виртуальная машина: группы сходства

Имя кнопки Описание

Выберите группу сходства (Select an affinity group)

Из выпадающего списка можно выбрать существующие, ранее сделанные группы сходства, чтобы применить к виртуальной машине

Выбранные группы сходства (Selected Affinity Groups)

Здесь можно удалить группы сходства, добавленные к виртуальной машине

Выберите метку сходства (Select an affinity label)

Из выпадающего списка можно выбрать существующие, ранее сделанные метки сходства, чтобы применить к виртуальной машине

Выбранные метки сходства (Selected Affinity Labels)

Здесь можно удалить метки сходства, добавленные к виртуальной машине

8.2. Описание настроек в окне «Запустить ВМ (Run Virtual Machine(s))»

В окне Запустить ВМ (Run Virtual Machine(s)), появляющемся после выбора , задаются параметры разовой начальной загрузки для виртуальной машины. Для параметров постоянной начальной загрузки используйте вкладку Параметры начальной загрузки (Boot Options) в окне Новая виртуальная машина (New Virtual Machine). Окно Запустить ВМ (Run Virtual Machine(s)) содержит несколько конфигурируемых разделов.

run once

Отдельная опция Откат конфигурации при перезагрузке (Rollback this configuration during reboots) указывает, какими параметры будут после перезагрузки:

  • Если опция активирована, после перезагрузки виртуальная машина запускается с постоянной конфигурацией, заданной в окне создания/изменения ВМ.

  • Если опция деактивирована, после перезагрузки виртуальная машина сохранит конфигурацию, заданную в оснастке Однократный запуск (Run Once).

    В этом случае сброс конфигурации, заданной в оснастке Однократный запуск (Run Once), выполняется путем выключения ВМ средствами zVirt:

    run once reset

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

8.2.1. Раздел «Параметры загрузки»

В разделе Параметры загрузки (Boot Options) задается последовательность начальной загрузки виртуальной машины, параметры запуска и исходные образы для установки операционной системы и требуемых драйверов.

Таблица 29. Раздел «Параметры загрузки»

Имя поля Описание

Прикрепить CD (Attach CD)

Подключает образ ISO к виртуальной машине. Используйте параметр для установки операционной системы виртуальной машины и приложений. Образ CD должен находиться в домене хранения.

Прикрепить CD c гостевыми дополнениями для Windows (Attach Windows guest tools CD)

Подключает второй виртуальный CD-привод к виртуальной машине с ISO-образом virtio-win. Используйте параметр для установки драйверов Windows. Параметр доступен, только если виртуальная машина имеет значение в Операционная система (Operating System) из семейства Windows.

Включить меню для выбора загрузочного устройства (Enable menu to select boot device)

Этот параметр включает меню для выбора загрузочного устройства. После запуска виртуальной машины и подключения к консоли, но до начала загрузки, появится меню, где можно выбрать загрузочное устройство. Этот параметр следует включить перед начальной загрузкой, чтобы можно было выбрать нужный носитель с дистрибутивом.

Запустить в режиме приостановки (Start in Pause Mode)

Запускает виртуальную машину, а затем ставит ее на паузу для обеспечения подключения к консоли. Подходит для виртуальных машин на удаленных объектах.

Предпочитаемая последовательность загрузки (Predefined Boot Sequence)

Определяет порядок использования загрузочных устройств для начальной загрузки виртуальной машины. Выберите Жесткий диск (Hard Disk), CD-ROM или Сеть (PXE) (Network (PXE)) и переместите параметр вверх или вниз в списке, используя кнопки Выше (Up) и Ниже (Down).

Запустить без запоминания состояния (Run Stateless)

Удаляет все изменения в данных и конфигурации, внесенные на виртуальной машине после выключения. Эта опция доступна только, если виртуальный диск подключен к виртуальной машине.

8.2.2. Раздел параметров загрузки Linux

В разделе Параметры загрузки Linux (Linux Boot Options) содержатся поля для начальной загрузки ядра Linux напрямую, а не через загрузчик BIOS.

Таблица 30. Раздел параметров начальной загрузки Linux

Имя поля Описание

Путь к ядру (kernel path)

Полный путь к образу ядра для начальной загрузки виртуальной машины. Образ ядра должен храниться на локальном домене хранения хоста (имя пути в формате /data/images).

Путь к initrd (initrd path)

Полный путь к образу ramdisk, который будет использоваться с ранее указанным ядром. Образ ramdisk должен храниться на локальном домене хранения хоста (имя пути в формате /data/images).

Параметры ядра (kernel parameters)

8.2.3. Раздел «Cloud-Init (Initial Run)» (Виртуальные машины Linux)

В разделе Первоначальный запуск (Initial Run) указывается, будет ли Cloud-Init или Sysprep использоваться для инициализации виртуальной машины. Для просмотра доступных опций на виртуальных машинах Linux нужно установить флажок Использовать Cloud-Init (Use Cloud-Init) на вкладке Cloud-Init (Initial Run).

Параметры, доступные в разделе Использовать Cloud-Init (Use Cloud-Init), разнятся в зависимости от операционной системы, на базе которой работает виртуальная машина.

Таблица 31. Раздел «Cloud-Init (Initial Run)» (Виртуальные машины Linux)

Имя поля Дополнительный элемент Описание

Имя хоста ВМ (VM Hostname)

Имя хоста виртуальной машины.

Настроить временную зону (Configure Time Zone)

Часовой пояс виртуальной машины. Установите флажок и выберите часовой пояс из списка Часовой пояс (Time Zone).

Аутентификация (Authentication)

Подробности аутентификации виртуальной машины. Нажмите раскрывающую стрелку , чтобы увидеть настройки для этого параметра.

Имя пользователя (User Name)

Создает новую учетную запись пользователя на виртуальной машине. Если поле не заполнено, то пользователь по умолчанию root.

Пользователь уже установил пароль (Use already configured password)

Флажок устанавливается автоматически после ввода изначального пароля пользователя с правами администратора при создании или изменении параметров виртуальной машины на закладке Запуск инициализации (Initial Run) окон Новая виртуальная машина (New virtual machine) или Изменить виртуальную машину (Edit Virtual Machine). Снимите этот флажок, чтобы поля Пароль (Password) и Проверить пароль (Verify Password) стали активны, и укажите новый пароль.

Пароль (Password)

Root-пароль для виртуальной машины. Введите пароль в этом текстовом поле и в текстовом поле Подтвердите пароль (Verify Password), чтобы подтвердить правильность ввода пароля.

Ключи SSH-авторизации (SSH Authorized Keys)

Ключи SSH, которые должны быть добавлены в файл авторизованных ключей на виртуальной машине.

Пересоздать ключи SSH (Regenerate SSH Keys)

Повторно генерирует ключи SSH для виртуальной машины.

Сети (Networks)

Связанные с сетью настройки для виртуальной машины. Нажмите раскрывающую стрелку , чтобы отобразить настройки для этого параметра.

Сетевой протокол Cloud-Init (Cloud-Init Network Protocol)

Протокол, используемый для создания полезной нагрузки сетевой конфигурации виртуальной машины.

DNS-серверы (DNS Servers)

DNS-серверы, которые должны использоваться виртуальной машиной.

Домены поиска DNS (DNS Search Domains)

Домены поиска DNS, которые должны использоваться виртуальной машиной.

Гостевой сетевой интерфейс (In-guest Network Interface Name)

Конфигурирует сетевые интерфейсы для виртуальной машины. Установите этот флажок и кнопками или — добавьте сетевые интерфейсы к виртуальной машине или удалите их из нее. При нажатии набор полей становится видимым, и можно настроить IP-адрес, маску сети и шлюз, а также указать, требуется ли использование DHCP и запуск сетевого интерфейса при загрузке.

Пользовательский скрипт (Custom Script)

Пользовательские скрипты, которые будут работать на виртуальных машинах при запуске. Скрипты, вводимые в этом поле, являются пользовательскими разделами на YAML, которые добавляются к тем, что созданы Менеджером управления, и позволяют автоматизировать такие задачи, как создание пользователей и файлов, конфигурирование репозиториев dnf и выполнение команд.

8.2.4. Раздел «Cloud-Init (Initial Run)» (Виртуальные машины на Windows)

Параметры, доступные в разделе «Cloud-Init (Initial Run)», разнятся в зависимости от операционной системы, на базе которой работает виртуальная машина.

Таблица 32. Раздел «Cloud-Init (Initial Run)» (Виртуальные машины на Windows)

Имя поля Дополнительный элемент Описание

Имя хоста ВМ (VM Hostname)

Имя хоста виртуальной машины.

Домен (Domain)

Домен Active Directory, к которому относится виртуальная машина.

Название организации (Organization Name)

Название организации, которой принадлежит виртуальная машина. Этот параметр соотносится с текстовым полем, где можно задать название организации, которое отображается при первом запуске машины Windows.

Организационная единица в Active Directory (Active Directory OU)

Организационное подразделение в домене Active Directory, к которому относится виртуальная машина. Должно быть указано отличительное имя, например, CN=Users,DC=lab,DC=local

Настроить временную зону (Configure Time Zone)

Часовой пояс виртуальной машины. Установите флажок и выберите часовой пояс из списка Часовой пояс (Time Zone).

Пароль администратора (Admin Password)

Пароль пользователя с правами администратора для виртуальной машины. Нажмите раскрывающую стрелку , чтобы отобразить настройки для этого параметра.

Пользователь уже установил пароль (Use already configured password)

Флажок устанавливается автоматически после ввода изначального пароля пользователя с правами администратора при создании или изменении параметров виртуальной машины на закладке Запуск инициализации (Initial Run) окон Новая виртуальная машина (New virtual machine) или Изменить виртуальную машину (Edit Virtual Machine). Снимите этот флажок, чтобы поля Пароль администратора (Admin Password) и Проверить пароль администратора (Verify Admin Password) стали активны, и укажите новый пароль.

Пароль администратора (Admin Password)

Пароль пользователя с правами администратора для виртуальной машины. Введите пароль в этом текстовом поле и в текстовом поле Подтверждение пароля администратора (Verify Admin Password), чтобы проверить правильность ввода пароля.

Пользовательская локализация (Custom Locale)

Региональные настройки должны быть в формате ru-Ru. Нажмите раскрывающую стрелку , чтобы отобразить настройки для этого параметра.

Язык ввода (Input Locale)

Региональные настройки для команд пользователя.

Язык интерфейса (UI Language)

Язык пользовательского интерфейса, в частности таких элементов как кнопки и меню.

Язык системы (System Locale)

Региональные настройки для всей системы.

Локаль пользователя (User Locale)

Региональные настройки для пользователей.

Sysprep

Пользовательское определение настроек Sysprep. Определение настроек должно быть в формате полного файла ответов для автоматической установки. Можно скопировать и вставить файлы ответов по умолчанию в каталоге /usr/share/ovirt-engine/conf/sysprep/ на машине с Менеджером управления и изменить поля нужным образом. Определение настроек перепишет любые значения, введенные в поля Запуск инициализации (Initial Run) при создании или редактировании виртуальной машины.

Домен (Domain)

Домен Active Directory, к которому относится виртуальная машина. Если поле оставлено пустым, то используется значение из предыдущего поля Домен (Domain).

Альтернативные учетные данные (Alternate Credentials)

При установке этого флажка можно задать Имя пользователя (User Name) и Пароль (Password) как альтернативные учетные данные.

8.2.5. Раздел «Система (System)»

С помощью раздела Система (System) можно задать поддерживаемый тип машины или тип ЦП.

Таблица 33. Раздел «Система (System)»

Имя поля Описание

Тип ВМ (Custom Emulated Machine)

Здесь можно задать тип машины. При изменении этого параметра виртуальная машина будет работать только на хостах, которые поддерживают указанный тип машины. Выставляет тип машины в значение, заданное для кластера по умолчанию.

Тип ЦП (Custom CPU Type)

Здесь можно задать тип ЦП. При изменении этого параметра виртуальная машина будет работать только на хостах, которые поддерживают указанный тип ЦП. Выставляет тип ЦП в значение, заданное для кластера по умолчанию.

8.2.6. Раздел «Хост (Host)»

С помощью раздела Хост (Host) можно задать хост виртуальной машины.

Таблица 34. Раздел «Хост (Host)»

Имя поля Описание

Любом хосте в кластере (Any host in cluster)

Распределяет виртуальные машины на любой доступный хост.

Указанном хосте (Specific Host(s))

Указывает для виртуальной машины хост, определенный пользователем.

8.2.7. Раздел «Консоль (Console)»

В разделе Консоль (Console) задается протокол для подключения виртуальных машин.

Таблица 35. Раздел «Консоль (Console)»

Имя поля Описание

Режим Headless (Headless Mode)

Выберите эту опцию, если при первом запуске машины не требуется графическая консоль. Для получения дополнительной информации см. раздел Настройка фоновых виртуальных машин (Headless Virtual Machines).

VNC

Требуется VNC-клиент для подключения к виртуальной машине с помощью VNC. При желании из выпадающего списка выберите Раскладка клавиатуры в VNC (VNC Keyboard Layout).

SPICE

Рекомендуемый протокол для виртуальных машин на Linux и Windows. Использование протокола SPICE вместе с драйверами QXLDOD поддерживается на виртуальных машинах с Windows 10, Windows Server 2016 и более поздними версиями. Дополнительно при использовании этого протокола можно включить:

  • Включить передачу файлов SPICE (Enable SPICE file transfer) — разрешает перетаскивание файлов с внешнего хоста в консоль SPICE виртуальной машины. Флажок установлен по умолчанию.

  • Включить буфер обмена SPICE (Enable SPICE clipboard copy and paste) — разрешает вставлять контент с внешнего хоста в консоль SPICE виртуальной машины. Флажок установлен по умолчанию.

8.2.8. описание настроек в разделе «Доп. параметры (Custom Properties)»

В разделе Доп. параметры (Custom Properties) содержатся дополнительные опции VDSM для работы виртуальных машин. Для получения дополнительной информации см. раздел Описание настроек пользовательских свойств виртуальных машин.

8.3. Описание настроек в окнах «Новый сетевой интерфейс (New Network Interface)» и «Изменить сетевой интерфейс (Edit Network Interface)»

Эти настройки применяются при добавлении или изменении сетевого интерфейса виртуальной машины. Если к виртуальной машине подключено несколько сетевых интерфейсов, то виртуальную машину можно поместить в несколько логических сетей.

Таблица 36. Настройки сетевого интерфейса

Имя поля Описание Требуется ли выключение и включение питания?

Имя

Имя сетевого интерфейса. Длина этого текстового поля ограничена 21 знаками. Имя должно быть уникальным и представлять собой любую комбинацию латинских букв в верхнем или нижнем регистре, цифр, дефисов или знаков подчеркивания.

Нет

Профиль (Profile)

vNIC-профиль или логическая сеть, на которых находится сетевой интерфейс. По умолчанию все сетевые интерфейсы находятся на сети управления ovirtmgmt.

Нет

Тип (Type)

Виртуальный интерфейс, который сетевой интерфейс отображает для виртуальных машин.

  • Драйверы устройств rtl8139 и e1000 входят в состав большинства операционных систем.

  • VirtIO быстрее, но для него требуются драйверы VirtIO. В в подавляющем большинстве современных дистрибутивов Linux драйверы VirtIO уже есть. В Windows драйверов VirtIO нет, но их можно установить из ISO-образа инструментов гостевой машины.

  • PCI Passthrough позволяет карте vNIC напрямую подключаться к виртуальной функции сетевой карты с включенной технологией SR-IOV. В этом случае карта vNIC будет обходить программную виртуализацию сети и подключаться непосредственно к виртуальной функции для прямого назначения устройства. У выбранного vNIC-профиля также должен быть включен Passthrough.

Да.

Пользовательский MAC-адрес (Custom MAC address)

Выберите этот параметр, чтобы задать пользовательский MAC-адрес. Менеджер управления автоматически генерирует уникальный для среды MAC-адрес, чтобы идентифицировать сетевой интерфейс. Если в одной и той же сети находятся онлайн два устройства с одинаковым MAC-адресом, то возникнут конфликты в сети.

Да

Состояние соединения (Link State)

Подключен сетевой интерфейс к логической сети или нет.

  • Включено (Up): Сетевой интерфейс находится в своем слоте.

    • Если Состояние карты (Card Status)Подключена (Plugged), то сетевой интерфейс подключен к сетевому кабелю и активен.

    • Если Состояние карты (Card Status)Не подключена (Unplugged), то сетевой интерфейс будет автоматически подключен к сети и станет активным, когда карта будет вставлена.

  • Выключено (Down): Сетевой интерфейс находится в своем слоте, но не подключен ни к одной сети. В таком состоянии виртуальные машины запуститься не смогут.

Нет

Состояние карты (Card Status)

Задан сетевой интерфейс на виртуальной машине или нет.

  • Подключена (Plugged): Сетевой интерфейс задан на виртуальной машине.

    • Если его Состояние соединения (Link State)Подключено (Up), то сетевой интерфейс подключен к сетевому кабелю и активен.

    • Если его Состояние соединения (Link State)Выключено (Down), то сетевой интерфейс не подключен к сетевому кабелю.

  • Не подключена (Unplugged): Сетевой интерфейс задается только на Менеджере управления и не ассоциируется с виртуальной машиной.

    • Если его Состояние соединения (Link State)Включено (Up), то сетевой интерфейс автоматически будет подключен к сетевому кабелю и станет активным, когда сетевая карта вставлена.

    • Если его Состояние соединения (Link State)Выключено (Down), то сетевой интерфейс не подключен ни к одной сети, пока не будет задан на виртуальной машине.

Нет

8.4. Описание настроек в окнах «Новый диск (New Virtual Disk)» и «Изменить виртуальный диск (Edit Virtual Disk)»

В данном приложении описаны элементы интерфейса при создании нового или изменении существующего виртуального диска.

Все таблицы приложения не содержат информацию о необходимости выключения и включения питания, так как эта информация не применима к этим сценариям.

8.4.1. Описание настроек на вкладке Образ (Image) в окнах «Создать виртуальный диск (New Virtual Disk) и «Изменить виртуальный диск (Edit Virtual Disk)»

Таблица 37. Настройки в окнах «Создать виртуальный диск (New Virtual Disk) и «Изменить виртуальный диск (Edit Virtual Disk)»: Образ (Image)

Имя поля Описание

Размер (GiB) (Size(GiB))

Размер нового виртуального диска в ГиБ.

Увеличить размер на (GiB) (Extend size by (GiB))

Позволяет задать на сколько ГиБ будет увеличен существующий виртуальный диск. Доступно только в окне Изменить виртуальный диск (Edit Virtual Disk).

Имя (Alias)

Имя виртуального диска (не более 40 знаков).

Описание

Описание виртуального диска. Это поле является рекомендованным, но не обязательным.

Интерфейс (Interface)

Виртуальный интерфейс, который диск представляет виртуальным машинам. Virtio-SCSI — виртуальный SCSI HBA, обеспечивает наибольшую производительность из всех виртуальных блочных устройств, но для него требуются драйверы. В подавляющем большинстве современных дистрибутивов Linux драйверы VirtIO уже есть. В Windows драйверов VirtIO нет, но их можно установить из ISO-образа инструментов гостевой машины. VirtIO — предшественник устройства Virtio-SCSI, менее производительный, не эмулирует SCSI, тоже требует драйверов в ОС Windows. Для устройств SATA никаких особых драйверов не требуется. Тип интерфейса можно обновить после остановки всех виртуальных машин, к которым подключен диск.

Центр данных (Data Center)

Центр данных, в котором будет доступен виртуальный диск. Доступно только при создании плавающих дисков из .

Домен хранения (Storage Domain)

Домен хранения, в котором будет храниться виртуальный диск. В раскрывающемся списке показаны все домены хранения, доступные в конкретном центре данных, а также общее и доступное сейчас дисковое пространство в домене хранения.

Политика выделения (Allocation Policy)

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

  • Предварительно размеченный (Preallocated): при создании виртуального диска ему выделяется все пространство диска в домене хранения. У диска с предварительно выделенным пространством виртуальный размер и фактический размер совпадают. Создание виртуальных дисков с предварительно выделенным пространством занимает больше времени, чем создание виртуальных дисков с динамическим выделением пространства, но они обеспечивают более высокую скорость операций чтения и записи. Виртуальные диски с предварительно выделенным пространством рекомендуются для серверов и других виртуальных машин с интенсивным потоком операций ввода-вывода. Если виртуальная машина способна записывать более 1 ГБ каждые четыре секунды, то по возможности используйте диски с предварительно выделенным пространством.

  • Динамически расширяемый (Thin Provision): при создании виртуального диска ему выделяется 1 ГБ и устанавливается максимально допустимый размер, до которого может увеличиваться его емкость. Виртуальный размер диска равен максимально допустимому размеру; фактический размер диска — это пространство, выделенное по состоянию на сейчас. Диски с динамическим выделением пространства создаются быстрее, чем диски с предварительно выделенным пространством, и допускают избыточное выделение ресурсов хранилища. Виртуальные диски с динамическим выделением пространства рекомендуются для рабочих станций.

Профиль диска (Disk Profile)

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

Включение дисков (Activate Disk(s))

Активируйте виртуальный диск сразу после создания. Этот параметр недоступен при создании плавающего диска.

Очистить после удаления (Wipe After Delete)

Позволяет включить повышенную защиту для удаления конфиденциальных материалов при удалении виртуального диска.

Загрузочный (Bootable)

Включает на виртуальном диске флаг «загрузочный (bootable)». Доступен, только если у виртуальной машины ещё нет загрузочных дисков.

Может быть общим (Shareable)

Позволяет подключать виртуальный диск одновременно к нескольким виртуальным машинам.

Только для чтения (Read Only)

Позволяет для диска установить атрибут «только для чтения». Один и тот же диск можно подключить к одной виртуальной машине как доступный только для чтения, а к другой — как перезаписываемый. Этот параметр недоступен при создании плавающего диска.

Включить Discard (Enable Discard)

Позволяет уменьшать размер диска с динамическим выделением пространства во время работы виртуальной машины. Для блочного хранилища базовое устройство хранения должно поддерживать вызовы функции discard, и этот параметр нельзя использовать с параметром Очистить после удаления (Wipe After Delete), если базовое хранилище не поддерживает свойство discard_zeroes_data. Для хранилища файлов базовая файловая система и блочное устройство должны поддерживать вызовы функции discard. Если все требования удовлетворены, то QEMU передает команды SCSI UNMAP с гостевых виртуальных машин в базовое хранилище для высвобождения неиспользуемого пространства.

Включить инкрементное резервное копирование (Enable Incremental Backup)

Создаёт образ диска формата qcow, что позволяет делать инкрементное резервное копирование.

8.4.2. Описание настроек на вкладке Прямой LUN (Direct LUN) в окнах «Создать виртуальный диск (New Virtual Disk) и «Изменить виртуальный диск (Edit Virtual Disk)»

Чтобы показать настройки Direct LUN, выберите Цели (Targets) → LUNs или LUNs → Цели (Targets). Если выбрать Цели (Targets) → LUNs, то доступные LUN ​​будут отсортированы в соответствии с хостом, на котором они обнаружены, а если выбрать LUNs → Цели (Targets), то будет показан один общий список LUN.

Таблица 38. Настройки в окнах «Создать виртуальный диск (New Virtual Disk) и «Изменить виртуальный диск (Edit Virtual Disk)»: Direct LUN

Имя поля Описание

Имя (Alias)

Имя виртуального диска (не более 40 знаков).

Описание

Описание виртуального диска. Это поле является рекомендованным, но не обязательным.

Интерфейс (Interface)

Виртуальный интерфейс, который диск представляет виртуальным машинам. Virtio-SCSI — виртуальный SCSI HBA, обеспечивает наибольшую производительность из всех виртуальных блочных устройств, но для него требуются драйверы. В подавляющем большинстве современных дистрибутивов Linux драйверы VirtIO уже есть. В Windows драйверов VirtIO нет, но их можно установить из ISO-образа инструментов гостевой машины. VirtIO — предшественник устройства Virtio-SCSI, менее производительный, не эмулирует SCSI, тоже требует драйверов в ОС Windows. Для устройств SATA никаких особых драйверов не требуется. Тип интерфейса можно обновить после остановки всех виртуальных машин, к которым подключен диск.

Центр данных (Data Center)

Центр данных, в котором будет доступен виртуальный диск. Доступно только при создании плавающих дисков из .

Хост (Host)

Хост, на который будет смонтирован LUN. Можно выбрать любой хост в центре данных.

Тип хранилища (Storage Type)

Тип внешнего LUN для добавления. Можно выбрать либо iSCSI, либо Fibre Channel.

Обнаружение целей (Discover Targets)

Этот раздел можно развернуть, когда используются внешние LUN ​​iSCSI и выбрано Цели (Targets) → LUNs.

  • Адрес (Address) — имя хоста или IP-адрес целевого сервера.

  • Порт (Port) — порт, через который нужно попытаться подключиться к целевому серверу. Порт по умолчанию — 3260.

  • Аутентификация пользователей (User Authentication) — для сервера iSCSI требуется аутентификация пользователя. Поле Аутентификация пользователя (User Authentication) отображается при использовании внешних LUN iSCSI.

  • Имя пользователя CHAP (CHAP user name) — имя пользователя, которому разрешен вход в LUN. Это поле доступно, если установлен флажок Аутентификация пользователя (User Authentication).

  • Пароль CHAP (CHAP password) — пароль пользователя, которому разрешен вход в LUN. Это поле доступно, если установлен флажок Аутентификация пользователя (User Authentication).

Включение дисков (Activate Disk(s))

Активируйте виртуальный диск сразу после создания. Этот параметр недоступен при создании плавающего диска.

Загрузочный (Bootable)

Включает на виртуальном диске флаг «загрузочный (bootable)». Доступен, только если у виртуальной машины ещё нет загрузочных дисков.

Может быть общим (Shareable)

Позволяет подключать виртуальный диск одновременно к нескольким виртуальным машинам.

Только для чтения (Read Only)

Позволяет для диска установить атрибут «только для чтения». Один и тот же диск можно подключить к одной виртуальной машине как доступный только для чтения, а к другой — как перезаписываемый. Этот параметр недоступен при создании плавающего диска.

Включить Discard (Enable Discard)

Позволяет уменьшать размер диска с динамическим выделением пространства во время работы виртуальной машины. Если этот параметр включен, то QEMU передает команды SCSI UNMAP с гостевых виртуальных машин в базовое хранилище для высвобождения неиспользуемого пространства.

Включить интерфейс SCSI (Enable SCSI Pass-Through)

Доступно, когда для параметра Интерфейс (Interface) установлено значение VirtIO-SCSI. Установка этого флажка включает сквозной доступ с физического устройства SCSI на виртуальный диск. Интерфейс VirtIO-SCSI с включенным сквозным доступом SCSI автоматически включает поддержку функции discard для SCSI. Только для чтения (Read-Only) не поддерживается, когда установлен этот флажок.

Если этот флажок не установлен, то виртуальный диск использует эмулируемое устройство SCSI. Только для чтения (Read-Only) поддерживается на эмулируемых дисках VirtIO-SCSI.

Разрешить привилегированный ввод-вывод SCSI (Allow Privileged SCSI I/O)

Доступно, если установлен флажок Включить интерфейс SCSI (Enable SCSI Pass-Through). Установка этого флажка включает нефильтруемый доступ SCSI Generic I/O (SG_IO) и разрешает использование привилегированных команд SG_IO на диске. Это необходимо для постоянных резервирований.

Используется резервирование SCSI (Using SCSI Reservation)

Доступно, если установлены флажки Включить интерфейс SCSI (Enable SCSI Pass-Through) и Разрешить привилегированный ввод-вывод SCSI (Allow Privileged SCSI I/O). Установка этого флажка отключает миграцию для всех виртуальных машин, использующих этот диск, чтобы виртуальные машины, использующие резервирование SCSI, не утратили доступ к диску.

Заполните поля в разделе Обнаружение целей (Discover Targets) и нажмите Обнаружение (Discover), чтобы обнаружить целевой сервер. Затем нажмите кнопку Войти везде (Login All), чтобы просмотреть список доступных LUN на целевом сервере, и нажатием кнопки-переключателя рядом с каждым LUN выберите LUN для добавления.

Использование LUN непосредственно в качестве образов жестких дисков виртуальных машин устраняет слой абстракции между виртуальными машинами и их данными.

При использовании Direct LUN в качестве образа жесткого диска виртуальной машины нужно учитывать следующее:

  • Миграция хранилища на лету не поддерживается для образов жестких дисков Direct LUN.

  • Диски Direct LUN не включаются в экспорт виртуальных машин.

  • Диски Direct LUN не включаются в моментальные снимки виртуальных машин.

Для монтирования журналируемой файловой системы требуется доступ с правами на чтение и запись. Использование параметра Только для чтения (Read Only) не подходит для виртуальных дисков, содержащих файловые системы EXT3, EXT4 или XFS.

8.5. Описание настроек в окнах «Новый шаблон (New Template)» и «Изменить шаблон (Edit Template)»

В приведенной ниже таблице подробно описаны настройки окна Новый шаблон (New Template).

Следующая таблица не содержат информацию о необходимости выключения и включения питания, так как эта информация не применима к этому сценарию.

Таблица 39. Настройки окна «Новый шаблон»

Поле Описание/действие

Имя (Name)

Имя шаблона. Это то имя, под которым шаблон отображается на вкладке Шаблоны (Templates) на Портале администрирования и под которым он доступен через REST API. Длина этого текстового поля ограничена 40 знаками. Имя должно быть уникальным в пределах центра данных и представлять собой любую комбинацию латинских букв в верхнем или нижнем регистре, цифр, дефисов или знаков подчеркивания. Имя можно повторно использовать в разных центрах данных в пределах среды.

Описание (Description)

Описание шаблона. Это поле является рекомендованным, но не обязательным.

Комментарий (Comment)

Поле для добавления комментариев о шаблоне в виде обычного текста.

Кластер

Кластер, с которым ассоциирован шаблон. По умолчанию он будет тем же, что и у исходных виртуальных машин. Можно выбрать любой кластер в центре данных.

Профиль ЦП (CPU Profile)

Профиль ЦП, назначенный шаблону. Профили ЦП определяют максимальную вычислительную мощность, которую виртуальная машина может получить на хосте, на котором она работает, выраженную в процентах от общей вычислительной мощности, доступной этому хосту. Профили ЦП определяются для кластера, исходя из записей о качестве обслуживания, созданных для центров данных.

Создать как подверсию шаблона (Create as a Template Sub-Version)

Указывает, создается ли шаблон как новая версия существующего шаблона. Установите этот флажок, чтобы получить доступ к настройкам этого параметра.

  • Корневой шаблон (Root Template): Шаблон, под которым добавляется подшаблон.

  • Название подверсии (Sub-Version Name): Имя шаблона. Это имя, используемое для доступа к шаблону при создании новой виртуальной машины на основе шаблона. Если состояние виртуальной машины не сохраняется, то список подверсий будет содержать параметр последний (latest), а не имя последней подверсии. Этот параметр автоматически применяет последнюю подверсию шаблона к виртуальной машине после перезагрузки. Подверсии особенно полезны при работе с пулами виртуальных машин без сохранения состояния.

Выделение дискового пространства: (Disk Allocation)

  • Имя (Alias) — псевдоним для виртуального диска, используемого шаблоном. По умолчанию псевдоним будет тем же, что и для исходной виртуальной машины.

  • Виртуальный размер (Virtual Size) — это общий объем дискового пространства, который может использовать виртуальная машина, созданная на базе шаблона. Это значение нельзя изменить — оно указывается только в информационных целях. Это значение соответствует размеру в ГиБ, указанному при создании или изменении диска.

  • Формат (Format) — формат виртуального диска, используемого шаблоном. Доступные варианты: QCOW2 и Raw. Значение по умолчанию — Raw.

  • Цель (Target) — домен хранения, в котором находится виртуальный диск, используемый шаблоном. По умолчанию домен хранения будет тем же, что и для исходной виртуальной машины. Можно выбрать любой домен хранения в кластере.

  • Профиль диска (Disk Profile) — профиль диска, который нужно назначить виртуальному диску, используемому шаблоном. Профили дисков создаются на основе профилей хранения, определенных в центрах данных.

Разрешить всем пользователям доступ к шаблону (Allow all users to access this Template)

Указывает, является ли шаблон общедоступным или частным. К общедоступному шаблону могут получить доступ все пользователи, тогда как к частному — только пользователи с ролями TemplateAdmin или SuperUser.

Копировать разрешения ВМ (Copy VM permissions)

Копирует явные разрешения, установленные на исходной виртуальной машине, в шаблон.

Запечатать шаблон (Seal Template) (только Linux)

Указывает, зафиксирован ли шаблон. «Фиксация» — это операция, которая стирает из файловой системы все конфигурации, характерные для конкретной машины, включая SSH-ключи, правила UDEV, MAC-адреса, идентификатор системы и доменное имя. Эта настройка не позволяет виртуальной машине, основанной на этом шаблоне, наследовать конфигурацию исходной виртуальной машины.

9. Операции virt-sysprep

Команда virt-sysprep удаляет сведения, касающиеся конкретной системы и подготавливает образ ВМ для создания шаблона.

Часть из этих операций выполняется при запечатывании шаблона Linux.

Не нужно выполнять эти операции вручную.

Таблица 40. Список возможных операций над образом виртуальной машины

Операция Описание Операция выполняется по умолчанию?

abrt-data

Удалить данные о сбое, сгенерированные ABRT

Да

backup-files

Удалить файлы резервных копий редактора из гостевой ОС

Да

bash-history

Удалить файлы резервных копий редактора из гостевой ОС

Да

blkid-tab

Удалить данные blkid в гостевой ОС

Да

ca-certificates

Удалить сертификаты ЦС в гостевой OC

Нет

crash-data

Удалить данные о сбое, сгенерированные kexec-tools

Да

cron-spool

Удалить данные о сбое, сгенерированные kexec-tools

Да

customize

Настроить гостевую ОС

Да

dhcp-client-state

Удалить аренду DHCP-клиента

Да

dhcp-server-state

Удалить аренду DHCP-сервера

Да

dovecot-data

Удалить данные Dovecot (почтового сервера)

Да

firewall-rules

Удалить правила брандмауэра

Нет

flag-reconfiguration

Пометить систему на перенастройку

Нет

fs-uuids

Изменить UUID файловой системы

Нет

ipa-client

Удалить файлы IPA

Да

kerberos-data

Удалить данные Kerberos в гостевой ОС

Нет

kerberos-hostkeytab

Удалите файл keytab хоста Kerberos в гостевой ОС

Да

logfiles

Удалить файлы системы журналирования событий из гостевой ОС

Да

lvm-uuids

Изменить LVM2 PV и VG UUID

Да

machine-id

Удалить идентификатор локальной машины

Да

mail-spool

Удаление электронной почты из локального почтового каталога

Да

net-hostname

Удалить HOSTNAME и DHCP_HOSTNAME в конфигурации сетевого интерфейса

Да

net-hwaddr

Удалить конфигурацию HWADDR (жестко запрограммированный MAC-адрес)

Да

pacct-log

Удалить файлы журнала учета процессов

Да

package-manager-cache

Удалить кеш менеджера пакетов

Да

pam-data

Удалить данные PAM в гостевой

Да

passwd-backups

Удалить /etc/passwd- и подобные файлы резервных копий

Да

puppet-data-log

Удалить данные и файлы журналов puppet

Да

rh-subscription-manager

Удалите файлы менеджера подписки RH

Да

rhn-systemid

Удалить идентификатор системы RHN

Да

rpm-db

Удалить специфичные для хоста файлы базы данных RPM

Да

samba-db-log

Удалить базу данных и лог-файлы Samba

Да

script

Запускать произвольные скрипты в гостевой ОС

Да

smolt-uuid

Удалите аппаратный UUID Smolt

Да

ssh-hostkeys

Удалите ключи хоста SSH в гостевой

Да

ssh-userdir

Удалить каталоги «.ssh» в гостевой

Да

sssd-db-log

Удалите файлы базы данных и журналов sssd

Да

tmp-files

Удалить временные файлы

Да

udev-persistent-net

Удалить постоянные сетевые правила udev

Да

user-account

Удалить учетные записи пользователей в гостевой ОС

Нет

utmp

Удалить файл utmp

Да

yum-uuid

Удалить UUID yum

Да

10. Примеры скриптов Cloud-init

10.1. Добавление пользователей и групп

#cloud-config
# Add groups to the system
# The following example adds the 'admingroup' group with members 'root' and 'sys'
# and the empty group cloud-users.
groups:
  - admingroup: [root,sys]
  - cloud-users

# Add users to the system. Users are added after groups are added.
# Note: Most of these configuration options will not be honored if the user
#       already exists. Following options are the exceptions and they are
#       applicable on already-existing users:
#       - 'plain_text_passwd', 'hashed_passwd', 'lock_passwd', 'sudo',
#         'ssh_authorized_keys', 'ssh_redirect_user'.
users:
  - default
  - name: foobar
    gecos: Foo B. Bar
    primary_group: foobar
    groups: users
    selinux_user: staff_u
    expiredate: '2032-09-01'
    ssh_import_id:
      - lp:falcojr
      - gh:TheRealFalcon
    lock_passwd: false
    passwd: $6$j212wezy$7H/1LT4f9/N3wpgNunhsIqtMj62OKiS3nyNwuizouQc3u7MbYCarYeAHWYPYb2FT.lbioDm2RrkJPb9BZMN1O/
  - name: barfoo
    gecos: Bar B. Foo
    sudo: ALL=(ALL) NOPASSWD:ALL
    groups: users, admin
    ssh_import_id:
      - lp:falcojr
      - gh:TheRealFalcon
    lock_passwd: true
    ssh_authorized_keys:
      - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDSL7uWGj8cgWyIOaspgKdVy0cKJ+UTjfv7jBOjG2H/GN8bJVXy72XAvnhM0dUM+CCs8FOf0YlPX+Frvz2hKInrmRhZVwRSL129PasD12MlI3l44u6IwS1o/W86Q+tkQYEljtqDOo0a+cOsaZkvUNzUyEXUwz/lmYa6G4hMKZH4NBj7nbAAF96wsMCoyNwbWryBnDYUr6wMbjRR1J9Pw7Xh7WRC73wy4Va2YuOgbD3V/5ZrFPLbWZW/7TFXVrql04QVbyei4aiFR5n//GvoqwQDNe58LmbzX/xvxyKJYdny2zXmdAhMxbrpFQsfpkJ9E/H5w0yOdSvnWbUoG5xNGoOB csmith@fringe
  - name: cloudy
    gecos: Magic Cloud App Daemon User
    inactive: '5'
    system: true
  - name: fizzbuzz
    sudo: false
    shell: /bin/bash
    ssh_authorized_keys:
      - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDSL7uWGj8cgWyIOaspgKdVy0cKJ+UTjfv7jBOjG2H/GN8bJVXy72XAvnhM0dUM+CCs8FOf0YlPX+Frvz2hKInrmRhZVwRSL129PasD12MlI3l44u6IwS1o/W86Q+tkQYEljtqDOo0a+cOsaZkvUNzUyEXUwz/lmYa6G4hMKZH4NBj7nbAAF96wsMCoyNwbWryBnDYUr6wMbjRR1J9Pw7Xh7WRC73wy4Va2YuOgbD3V/5ZrFPLbWZW/7TFXVrql04QVbyei4aiFR5n//GvoqwQDNe58LmbzX/xvxyKJYdny2zXmdAhMxbrpFQsfpkJ9E/H5w0yOdSvnWbUoG5xNGoOB csmith@fringe
  - snapuser: joe@joeuser.io
  - name: nosshlogins
    ssh_redirect_user: true

# Valid Values:
#   name: The user's login name
#   expiredate: Date on which the user's account will be disabled.
#   gecos: The user name's real name, i.e. "Bob B. Smith"
#   homedir: Optional. Set to the local path you want to use. Defaults to
#           /home/<username>
#   primary_group: define the primary group. Defaults to a new group created
#           named after the user.
#   groups:  Optional. Additional groups to add the user to. Defaults to none
#   selinux_user:  Optional. The SELinux user for the user's login, such as
#           "staff_u". When this is omitted the system will select the default
#           SELinux user.
#   lock_passwd: Defaults to true. Lock the password to disable password login
#   inactive: Number of days after password expires until account is disabled
#   passwd: The hash -- not the password itself -- of the password you want
#           to use for this user. You can generate a hash via:
#               mkpasswd --method=SHA-512 --rounds=4096
#           (the above command would create from stdin an SHA-512 password hash
#           with 4096 salt rounds)
#
#           Please note: while the use of a hashed password is better than
#               plain text, the use of this feature is not ideal. Also,
#               using a high number of salting rounds will help, but it should
#               not be relied upon.
#
#               To highlight this risk, running John the Ripper against the
#               example hash above, with a readily available wordlist, revealed
#               the true password in 12 seconds on a i7-2620QM.
#
#               In other words, this feature is a potential security risk and is
#               provided for your convenience only. If you do not fully trust the
#               medium over which your cloud-config will be transmitted, then you
#               should not use this feature.
#
#   no_create_home: When set to true, do not create home directory.
#   no_user_group: When set to true, do not create a group named after the user.
#   no_log_init: When set to true, do not initialize lastlog and faillog database.
#   ssh_import_id: Optional. Import SSH ids
#   ssh_authorized_keys: Optional. [list] Add keys to user's authorized keys file
#                        An error will be raised if no_create_home or system is
#                        also set.
#   ssh_redirect_user: Optional. [bool] Set true to block ssh logins for cloud
#       ssh public keys and emit a message redirecting logins to
#       use <default_username> instead. This option only disables cloud
#       provided public-keys. An error will be raised if ssh_authorized_keys
#       or ssh_import_id is provided for the same user.
#
#   sudo: Defaults to none. Accepts a sudo rule string, a list of sudo rule
#         strings or False to explicitly deny sudo usage. Examples:
#
#         Allow a user unrestricted sudo access.
#             sudo:  ALL=(ALL) NOPASSWD:ALL
#
#         Adding multiple sudo rule strings.
#             sudo:
#               - ALL=(ALL) NOPASSWD:/bin/mysql
#               - ALL=(ALL) ALL
#
#         Prevent sudo access for a user.
#             sudo: False
#
#         Note: Please double check your syntax and make sure it is valid.
#               cloud-init does not parse/check the syntax of the sudo
#               directive.
#   system: Create the user as a system user. This means no home directory.
#   snapuser: Create a Snappy (Ubuntu-Core) user via the snap create-user
#             command available on Ubuntu systems.  If the user has an account
#             on the Ubuntu SSO, specifying the email will allow snap to
#             request a username and any public ssh keys and will import
#             these into the system with username specified by SSO account.
#             If 'username' is not set in SSO, then username will be the
#             shortname before the email domain.
#

# Default user creation:
#
# Unless you define users, you will get a 'ubuntu' user on Ubuntu systems with the
# legacy permission (no password sudo, locked user, etc). If however, you want
# to have the 'ubuntu' user in addition to other users, you need to instruct
# cloud-init that you also want the default user. To do this use the following
# syntax:
#   users:
#     - default
#     - bob
#     - ....
#  foobar: ...
#
# users[0] (the first user in users) overrides the user directive.
#
# The 'default' user above references the distro's config:
# system_info:
#   default_user:
#     name: Ubuntu
#     plain_text_passwd: 'ubuntu'
#     home: /home/ubuntu
#     shell: /bin/bash
#     lock_passwd: True
#     gecos: Ubuntu
#     groups: [adm, audio, cdrom, dialout, floppy, video, plugdev, dip, netdev]

10.2. Записть в произвольные файлы

#cloud-config
# vim: syntax=yaml
#
# This is the configuration syntax that the write_files module
# will know how to understand. Encoding can be given b64 or gzip or (gz+b64).
# The content will be decoded accordingly and then written to the path that is
# provided.
#
# Note: Content strings here are truncated for example purposes.
write_files:
- encoding: b64
  content: CiMgVGhpcyBmaWxlIGNvbnRyb2xzIHRoZSBzdGF0ZSBvZiBTRUxpbnV4...
  owner: root:root
  path: /etc/sysconfig/selinux
  permissions: '0644'
- content: |
    # My new /etc/sysconfig/samba file

    SMBDOPTIONS="-D"
  path: /etc/sysconfig/samba
- content: !!binary |
    f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAwARAAAAAAABAAAAAAAAAAJAVAAAAAAAAAAAAAEAAOAAI
    AEAAHgAdAAYAAAAFAAAAQAAAAAAAAABAAEAAAAAAAEAAQAAAAAAAwAEAAAAAAADAAQAAAAAAAAgA
    AAAAAAAAAwAAAAQAAAAAAgAAAAAAAAACQAAAAAAAAAJAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAA
    ....
  path: /bin/arch
  permissions: '0555'
- encoding: gzip
  content: !!binary |
    H4sIAIDb/U8C/1NW1E/KzNMvzuBKTc7IV8hIzcnJVyjPL8pJ4QIA6N+MVxsAAAA=
  path: /usr/bin/hello
  permissions: '0755'

10.3. Добавление yum-репозитория

#cloud-config
# vim: syntax=yaml
#
# Add yum repository configuration to the system
#
# The following example adds the file /etc/yum.repos.d/epel_testing.repo
# which can then subsequently be used by yum for later operations.
yum_repos:
  # The name of the repository
  epel-testing:
    # Any repository configuration options
    # See: man yum.conf
    #
    # This one is required!
    baseurl: http://download.fedoraproject.org/pub/epel/testing/5/$basearch
    enabled: false
    failovermethod: priority
    gpgcheck: true
    gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL
    name: Extra Packages for Enterprise Linux 5 - Testing

10.4. Настройка экземпляров доверенных сертификатов CA

#cloud-config
#
# This is an example file to configure an instance's trusted CA certificates
# system-wide for SSL/TLS trust establishment when the instance boots for the
# first time.
#
# Make sure that this file is valid yaml before starting instances.
# It should be passed as user-data when starting the instance.

ca_certs:
  # If present and set to True, the 'remove_defaults' parameter will remove
  # all the default trusted CA certificates that are normally shipped with
  # Ubuntu.
  # This is mainly for paranoid admins - most users will not need this
  # functionality.
  remove_defaults: true

  # If present, the 'trusted' parameter should contain a certificate (or list
  # of certificates) to add to the system as trusted CA certificates.
  # Pay close attention to the YAML multiline list syntax.  The example shown
  # here is for a list of multiline certificates.
  trusted:
  - |
   -----BEGIN CERTIFICATE-----
   YOUR-ORGS-TRUSTED-CA-CERT-HERE
   -----END CERTIFICATE-----
  - |
   -----BEGIN CERTIFICATE-----
   YOUR-ORGS-TRUSTED-CA-CERT-HERE
   -----END CERTIFICATE-----

10.5. Настройка и запуск рецептов chef

#cloud-config
#
# This is an example file to automatically install chef-client and run a
# list of recipes when the instance boots for the first time.
# Make sure that this file is valid yaml before starting instances.
# It should be passed as user-data when starting the instance.

# The default is to install from packages.

# Key from https://packages.chef.io/chef.asc
apt:
  sources:
    source1:
      source: "deb http://packages.chef.io/repos/apt/stable $RELEASE main"
      key: |
        -----BEGIN PGP PUBLIC KEY BLOCK-----
        Version: GnuPG v1.4.12 (Darwin)
        Comment: GPGTools - http://gpgtools.org

        mQGiBEppC7QRBADfsOkZU6KZK+YmKw4wev5mjKJEkVGlus+NxW8wItX5sGa6kdUu
        twAyj7Yr92rF+ICFEP3gGU6+lGo0Nve7KxkN/1W7/m3G4zuk+ccIKmjp8KS3qn99
        dxy64vcji9jIllVa+XXOGIp0G8GEaj7mbkixL/bMeGfdMlv8Gf2XPpp9vwCgn/GC
        JKacfnw7MpLKUHOYSlb//JsEAJqao3ViNfav83jJKEkD8cf59Y8xKia5OpZqTK5W
        ShVnNWS3U5IVQk10ZDH97Qn/YrK387H4CyhLE9mxPXs/ul18ioiaars/q2MEKU2I
        XKfV21eMLO9LYd6Ny/Kqj8o5WQK2J6+NAhSwvthZcIEphcFignIuobP+B5wNFQpe
        DbKfA/0WvN2OwFeWRcmmd3Hz7nHTpcnSF+4QX6yHRF/5BgxkG6IqBIACQbzPn6Hm
        sMtm/SVf11izmDqSsQptCrOZILfLX/mE+YOl+CwWSHhl+YsFts1WOuh1EhQD26aO
        Z84HuHV5HFRWjDLw9LriltBVQcXbpfSrRP5bdr7Wh8vhqJTPjrQnT3BzY29kZSBQ
        YWNrYWdlcyA8cGFja2FnZXNAb3BzY29kZS5jb20+iGAEExECACAFAkppC7QCGwMG
        CwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRApQKupg++Caj8sAKCOXmdG36gWji/K
        +o+XtBfvdMnFYQCfTCEWxRy2BnzLoBBFCjDSK6sJqCu0IENIRUYgUGFja2FnZXMg
        PHBhY2thZ2VzQGNoZWYuaW8+iGIEExECACIFAlQwYFECGwMGCwkIBwMCBhUIAgkK
        CwQWAgMBAh4BAheAAAoJEClAq6mD74JqX94An26z99XOHWpLN8ahzm7cp13t4Xid
        AJ9wVcgoUBzvgg91lKfv/34cmemZn7kCDQRKaQu0EAgAg7ZLCVGVTmLqBM6njZEd
        Zbv+mZbvwLBSomdiqddE6u3eH0X3GuwaQfQWHUVG2yedyDMiG+EMtCdEeeRebTCz
        SNXQ8Xvi22hRPoEsBSwWLZI8/XNg0n0f1+GEr+mOKO0BxDB2DG7DA0nnEISxwFkK
        OFJFebR3fRsrWjj0KjDxkhse2ddU/jVz1BY7Nf8toZmwpBmdozETMOTx3LJy1HZ/
        Te9FJXJMUaB2lRyluv15MVWCKQJro4MQG/7QGcIfrIZNfAGJ32DDSjV7/YO+IpRY
        IL4CUBQ65suY4gYUG4jhRH6u7H1p99sdwsg5OIpBe/v2Vbc/tbwAB+eJJAp89Zeu
        twADBQf/ZcGoPhTGFuzbkcNRSIz+boaeWPoSxK2DyfScyCAuG41CY9+g0HIw9Sq8
        DuxQvJ+vrEJjNvNE3EAEdKl/zkXMZDb1EXjGwDi845TxEMhhD1dDw2qpHqnJ2mtE
        WpZ7juGwA3sGhi6FapO04tIGacCfNNHmlRGipyq5ZiKIRq9mLEndlECr8cwaKgkS
        0wWu+xmMZe7N5/t/TK19HXNh4tVacv0F3fYK54GUjt2FjCQV75USnmNY4KPTYLXA
        dzC364hEMlXpN21siIFgB04w+TXn5UF3B4FfAy5hevvr4DtV4MvMiGLu0oWjpaLC
        MpmrR3Ny2wkmO0h+vgri9uIP06ODWIhJBBgRAgAJBQJKaQu0AhsMAAoJEClAq6mD
        74Jq4hIAoJ5KrYS8kCwj26SAGzglwggpvt3CAJ0bekyky56vNqoegB+y4PQVDv4K
        zA==
        =IxPr
        -----END PGP PUBLIC KEY BLOCK-----

chef:

  # Valid values are 'accept' and 'accept-no-persist'
  chef_license: "accept"

  # Valid values are 'gems' and 'packages' and 'omnibus'
  install_type: "packages"

  # Boolean: run 'install_type' code even if chef-client
  #          appears already installed.
  force_install: false

  # Chef settings
  server_url: "https://chef.yourorg.com"

  # Node Name
  # Defaults to the instance-id if not present
  node_name: "your-node-name"

  # Environment
  # Defaults to '_default' if not present
  environment: "production"

  # Default validation name is chef-validator
  validation_name: "yourorg-validator"
  # if validation_cert's value is "system" then it is expected
  # that the file already exists on the system.
  validation_cert: |
    -----BEGIN RSA PRIVATE KEY-----
    YOUR-ORGS-VALIDATION-KEY-HERE
    -----END RSA PRIVATE KEY-----

  # A run list for a first boot json, an example (not required)
  run_list:
    - "recipe[apache2]"
    - "role[db]"

  # Specify a list of initial attributes used by the cookbooks
  initial_attributes:
    apache:
      prefork:
        maxclients: 100
      keepalive: "off"

  # if install_type is 'omnibus', change the url to download
  omnibus_url: "https://www.chef.io/chef/install.sh"

  # if install_type is 'omnibus', pass pinned version string
  # to the install script
  omnibus_version: "12.3.0"

  # If encrypted data bags are used, the client needs to have a secrets file
  # configured to decrypt them
  encrypted_data_bag_secret: "/etc/chef/encrypted_data_bag_secret"

# Capture all subprocess output into a logfile
# Useful for troubleshooting cloud-init issues
output: {all: '| tee -a /var/log/cloud-init-output.log'}

10.6. Установка и запуск ansible-pull

#cloud-config
packages_update: true
packages_upgrade: true

# if you're already installing other packages, you may
# wish to manually install ansible to avoid multiple calls
# to your package manager
packages:
  - git
ansible:
  install_method: pip
  pull:
    url: "https://github.com/holmanb/vmboot.git"
    playbook_name: ubuntu.yml

10.7. Настройка экземпляра для управления Ansible

#cloud-config
#
# A common use-case for cloud-init is to bootstrap user and ssh
# settings to be managed by a remote configuration management tool,
# such as ansible.
#
# This example assumes a default Ubuntu cloud image, which should contain
# the required software to be managed remotely by Ansible.
#
ssh_pwauth: false

users:
- name: ansible
  gecos: Ansible User
  groups: users,admin,wheel
  sudo: ALL=(ALL) NOPASSWD:ALL
  shell: /bin/bash
  lock_passwd: true
  ssh_authorized_keys:
    - "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDRCJCQ1UD9QslWDSw5Pwsvba0Wsf1pO4how5BtNaZn0xLZpTq2nqFEJshUkd/zCWF7DWyhmNphQ8c+U+wcmdNVcg2pI1kPxq0VZzBfZ7cDwhjgeLsIvTXvU+HVRtsXh4c5FlUXpRjf/x+a3vqFRvNsRd1DE+5ZqQHbOVbnsStk3PZppaByMg+AZZMx56OUk2pZCgvpCwj6LIixqwuxNKPxmJf45RyOsPUXwCwkq9UD4me5jksTPPkt3oeUWw1ZSSF8F/141moWsGxSnd5NxCbPUWGoRfYcHc865E70nN4WrZkM7RFI/s5mvQtuj8dRL67JUEwvdvEDO0EBz21FV/iOracXd2omlTUSK+wYrWGtiwQwEgr4r5bimxDKy9L8UlaJZ+ONhLTP8ecTHYkaU1C75sLX9ZYd5YtqjiNGsNF+wdW6WrXrQiWeyrGK7ZwbA7lagSxIa7yeqnKDjdkcJvQXCYGLM9AMBKWeJaOpwqZ+dOunMDLd5VZrDCU2lpCSJ1M="


# use the following passwordless demonstration key for testing or
# replace with your own key pair
#
# -----BEGIN OPENSSH PRIVATE KEY-----
# b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
# NhAAAAAwEAAQAAAYEA0QiQkNVA/ULJVg0sOT8LL22tFrH9aTuIaMOQbTWmZ9MS2aU6tp6h
# RCbIVJHf8wlhew1soZjaYUPHPlPsHJnTVXINqSNZD8atFWcwX2e3A8IY4Hi7CL0171Ph1U
# bbF4eHORZVF6UY3/8fmt76hUbzbEXdQxPuWakB2zlW57ErZNz2aaWgcjIPgGWTMeejlJNq
# WQoL6QsI+iyIsasLsTSj8ZiX+OUcjrD1F8AsJKvVA+JnuY5LEzz5Ld6HlFsNWUkhfBf9eN
# ZqFrBsUp3eTcQmz1FhqEX2HB3POuRO9JzeFq2ZDO0RSP7OZr0Lbo/HUS+uyVBML3bxAztB
# Ac9tRVf4jq2nF3dqJpU1EivsGK1hrYsEMBIK+K+W4psQysvS/FJWiWfjjYS0z/HnEx2JGl
# NQu+bC1/WWHeWLao4jRrDRfsHVulq160Ilnsqxiu2cGwO5WoEsSGu8nqpyg43ZHCb0FwmB
# izPQDASlniWjqcKmfnTrpzAy3eVWawwlNpaQkidTAAAFgGKSj8diko/HAAAAB3NzaC1yc2
# EAAAGBANEIkJDVQP1CyVYNLDk/Cy9trRax/Wk7iGjDkG01pmfTEtmlOraeoUQmyFSR3/MJ
# YXsNbKGY2mFDxz5T7ByZ01VyDakjWQ/GrRVnMF9ntwPCGOB4uwi9Ne9T4dVG2xeHhzkWVR
# elGN//H5re+oVG82xF3UMT7lmpAds5VuexK2Tc9mmloHIyD4BlkzHno5STalkKC+kLCPos
# iLGrC7E0o/GYl/jlHI6w9RfALCSr1QPiZ7mOSxM8+S3eh5RbDVlJIXwX/XjWahawbFKd3k
# 3EJs9RYahF9hwdzzrkTvSc3hatmQztEUj+zma9C26Px1EvrslQTC928QM7QQHPbUVX+I6t
# pxd3aiaVNRIr7BitYa2LBDASCvivluKbEMrL0vxSVoln442EtM/x5xMdiRpTULvmwtf1lh
# 3li2qOI0aw0X7B1bpatetCJZ7KsYrtnBsDuVqBLEhrvJ6qcoON2Rwm9BcJgYsz0AwEpZ4l
# o6nCpn5066cwMt3lVmsMJTaWkJInUwAAAAMBAAEAAAGAEuz77Hu9EEZyujLOdTnAW9afRv
# XDOZA6pS7yWEufjw5CSlMLwisR83yww09t1QWyvhRqEyYmvOBecsXgaSUtnYfftWz44apy
# /gQYvMVELGKaJAC/q7vjMpGyrxUPkyLMhckALU2KYgV+/rj/j6pBMeVlchmk3pikYrffUX
# JDY990WVO194Dm0buLRzJvfMKYF2BcfF4TvarjOXWAxSuR8www050oJ8HdKahW7Cm5S0po
# FRnNXFGMnLA62vN00vJW8V7j7vui9ukBbhjRWaJuY5rdG/UYmzAe4wvdIEnpk9xIn6JGCp
# FRYTRn7lTh5+/QlQ6FXRP8Ir1vXZFnhKzl0K8Vqh2sf4M79MsIUGAqGxg9xdhjIa5dmgp8
# N18IEDoNEVKUbKuKe/Z5yf8Z9tmexfH1YttjmXMOojBvUHIjRS5hdI9NxnPGRLY2kjAzcm
# gV9Rv3vtdF/+zalk3fAVLeK8hXK+di/7XTvYpfJ2EZBWiNrTeagfNNGiYydsQy3zjZAAAA
# wBNRak7UrqnIHMZn7pkCTgceb1MfByaFtlNzd+Obah54HYIQj5WdZTBAITReMZNt9S5NAR
# M8sQB8UoZPaVSC3ppILIOfLhs6KYj6RrGdiYwyIhMPJ5kRWF8xGCLUX5CjwH2EOq7XhIWt
# MwEFtd/gF2Du7HUNFPsZGnzJ3e7pDKDnE7w2khZ8CIpTFgD769uBYGAtk45QYTDo5JroVM
# ZPDq08Gb/RhIgJLmIpMwyreVpLLLe8SwoMJJ+rihmnJZxO8gAAAMEA0lhiKezeTshht4xu
# rWc0NxxD84a29gSGfTphDPOrlKSEYbkSXhjqCsAZHd8S8kMr3iF6poOk3IWSvFJ6mbd3ie
# qdRTgXH9Thwk4KgpjUhNsQuYRHBbI59Mo+BxSI1B1qzmJSGdmCBL54wwzZmFKDQPQKPxiL
# n0Mlc7GooiDMjT1tbuW/O1EL5EqTRqwgWPTKhBA6r4PnGF150hZRIMooZkD2zX6b1sGojk
# QpvKkEykTwnKCzF5TXO8+wJ3qbcEo9AAAAwQD+Z0r68c2YMNpsmyj3ZKtZNPSvJNcLmyD/
# lWoNJq3djJN4s2JbK8l5ARUdW3xSFEDI9yx/wpfsXoaqWnygP3PoFw2CM4i0EiJiyvrLFU
# r3JLfDUFRy3EJ24RsqbigmEsgQOzTl3xfzeFPfxFoOhokSvTG88PQji1AYHz5kA7p6Zfaz
# btn:[OK]11rJYIe7+e9B0lhku0AFwGyqlWQmS/MhIpnjHIk5tP4heHGSmzKQWJDbTskNWd6aq1G7
# 6HWfDpX4HgoM8AAAALaG9sbWFuYkBhcmM=
# -----END OPENSSH PRIVATE KEY-----
#

10.8. Настройка экземпляра в качестве контроллера Ansible

#cloud-config
#
# Demonstrate setting up an ansible controller host on boot.
# This example installs a playbook repository from a remote private repository
# and then runs two of the plays.

packages_update: true
packages_upgrade: true
packages:
  - git
  - python3-pip

# Set up an ansible user
# ----------------------
# In this case I give the local ansible user passwordless sudo so that ansible
# may write to a local root-only file.
users:
- name: ansible
  gecos: Ansible User
  shell: /bin/bash
  groups: users,admin,wheel,lxd
  sudo: ALL=(ALL) NOPASSWD:ALL

# Initialize lxd using cloud-init.
# --------------------------------
# In this example, a lxd container is
# started using ansible on boot, so having lxd initialized is required.
lxd:
  init:
    storage_backend: dir

# Configure and run ansible on boot
# ---------------------------------
# Install ansible using pip, ensure that community.general collection is
# installed [1].
# Use a deploy key to clone a remote private repository then run two playbooks.
# The first playbook starts a lxd container and creates a new inventory file.
# The second playbook connects to and configures the container using ansible.
# The public version of the playbooks can be inspected here [2]
#
# [1] community.general is likely already installed by pip
# [2] https://github.com/holmanb/ansible-lxd-public
#
ansible:
  install_method: pip
  package_name: ansible
  run_user: ansible
  galaxy:
    actions:
      - ["ansible-galaxy", "collection", "install", "community.general"]

  setup_controller:
    repositories:
      - path: /home/ansible/my-repo/
        source: git@github.com:holmanb/ansible-lxd-private.git
    run_ansible:
      - playbook_dir: /home/ansible/my-repo
        playbook_name: start-lxd.yml
        timeout: 120
        forks: 1
        private_key: /home/ansible/.ssh/id_rsa
      - playbook_dir: /home/ansible/my-repo
        playbook_name: configure-lxd.yml
        become_user: ansible
        timeout: 120
        forks: 1
        private_key: /home/ansible/.ssh/id_rsa
        inventory: new_ansible_hosts

# Write a deploy key to the filesystem for ansible.
# -------------------------------------------------
# This deploy key is tied to a private github repository [1]
# This key exists to demonstrate deploy key usage in ansible
# a duplicate public copy of the repository exists here[2]
#
# [1] https://github.com/holmanb/ansible-lxd-private
# [2] https://github.com/holmanb/ansible-lxd-public
#
write_files:
  - path: /home/ansible/.ssh/known_hosts
    owner: ansible:ansible
    permissions: 0o600
    defer: true
    content: |
      |1|YJEFAk6JjnXpUjUSLFiBQS55W9E=|OLNePOn3eBa1PWhBBmt5kXsbGM4= ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl
      |1|PGGnpCpqi0aakERS4BWnYxMkMwM=|Td0piZoS4ZVC0OzeuRwKcH1MusM= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
      |1|OJ89KrsNcFTOvoCP/fPGKpyUYFo=|cu7mNzF+QB/5kR0spiYmUJL7DAI= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=

  - path: /home/ansible/.ssh/id_rsa
    owner: ansible:ansible
    permissions: 0o600
    defer: true
    encoding: base64
    content: |
      LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFB
      QUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFB
      d0VBQVFBQUFZRUEwUWlRa05WQS9VTEpWZzBzT1Q4TEwyMnRGckg5YVR1SWFNT1FiVFdtWjlNUzJh
      VTZ0cDZoClJDYklWSkhmOHdsaGV3MXNvWmphWVVQSFBsUHNISm5UVlhJTnFTTlpEOGF0Rldjd1gy
      ZTNBOElZNEhpN0NMMDE3MVBoMVUKYmJGNGVIT1JaVkY2VVkzLzhmbXQ3NmhVYnpiRVhkUXhQdVdh
      a0IyemxXNTdFclpOejJhYVdnY2pJUGdHV1RNZWVqbEpOcQpXUW9MNlFzSStpeUlzYXNMc1RTajha
      aVgrT1VjanJEMUY4QXNKS3ZWQStKbnVZNUxFeno1TGQ2SGxGc05XVWtoZkJmOWVOClpxRnJCc1Vw
      M2VUY1FtejFGaHFFWDJIQjNQT3VSTzlKemVGcTJaRE8wUlNQN09acjBMYm8vSFVTK3V5VkJNTDNi
      eEF6dEIKQWM5dFJWZjRqcTJuRjNkcUpwVTFFaXZzR0sxaHJZc0VNQklLK0srVzRwc1F5c3ZTL0ZK
      V2lXZmpqWVMwei9IbkV4MkpHbApOUXUrYkMxL1dXSGVXTGFvNGpSckRSZnNIVnVscTE2MElsbnNx
      eGl1MmNHd081V29Fc1NHdThucXB5ZzQzWkhDYjBGd21CCml6UFFEQVNsbmlXanFjS21mblRycHpB
      eTNlVldhd3dsTnBhUWtpZFRBQUFGZ0dLU2o4ZGlrby9IQUFBQUIzTnphQzF5YzIKRUFBQUdCQU5F
      SWtKRFZRUDFDeVZZTkxEay9DeTl0clJheC9XazdpR2pEa0cwMXBtZlRFdG1sT3JhZW9VUW15RlNS
      My9NSgpZWHNOYktHWTJtRkR4ejVUN0J5WjAxVnlEYWtqV1EvR3JSVm5NRjludHdQQ0dPQjR1d2k5
      TmU5VDRkVkcyeGVIaHprV1ZSCmVsR04vL0g1cmUrb1ZHODJ4RjNVTVQ3bG1wQWRzNVZ1ZXhLMlRj
      OW1tbG9ISXlENEJsa3pIbm81U1RhbGtLQytrTENQb3MKaUxHckM3RTBvL0dZbC9qbEhJNnc5UmZB
      TENTcjFRUGlaN21PU3hNOCtTM2VoNVJiRFZsSklYd1gvWGpXYWhhd2JGS2QzawozRUpzOVJZYWhG
      OWh3ZHp6cmtUdlNjM2hhdG1RenRFVWorem1hOUMyNlB4MUV2cnNsUVRDOTI4UU03UVFIUGJVVlgr
      STZ0CnB4ZDNhaWFWTlJJcjdCaXRZYTJMQkRBU0N2aXZsdUtiRU1yTDB2eFNWb2xuNDQyRXRNL3g1
      eE1kaVJwVFVMdm13dGYxbGgKM2xpMnFPSTBhdzBYN0IxYnBhdGV0Q0paN0tzWXJ0bkJzRHVWcUJM
      RWhydko2cWNvT04yUndtOUJjSmdZc3owQXdFcFo0bApvNm5DcG41MDY2Y3dNdDNsVm1zTUpUYVdr
      SkluVXdBQUFBTUJBQUVBQUFHQUV1ejc3SHU5RUVaeXVqTE9kVG5BVzlhZlJ2ClhET1pBNnBTN3lX
      RXVmanc1Q1NsTUx3aXNSODN5d3cwOXQxUVd5dmhScUV5WW12T0JlY3NYZ2FTVXRuWWZmdFd6NDRh
      cHkKL2dRWXZNVkVMR0thSkFDL3E3dmpNcEd5cnhVUGt5TE1oY2tBTFUyS1lnVisvcmovajZwQk1l
      VmxjaG1rM3Bpa1lyZmZVWApKRFk5OTBXVk8xOTREbTBidUxSekp2Zk1LWUYyQmNmRjRUdmFyak9Y
      V0F4U3VSOHd3dzA1MG9KOEhkS2FoVzdDbTVTMHBvCkZSbk5YRkdNbkxBNjJ2TjAwdkpXOFY3ajd2
      dWk5dWtCYmhqUldhSnVZNXJkRy9VWW16QWU0d3ZkSUVucGs5eEluNkpHQ3AKRlJZVFJuN2xUaDUr
      L1FsUTZGWFJQOElyMXZYWkZuaEt6bDBLOFZxaDJzZjRNNzlNc0lVR0FxR3hnOXhkaGpJYTVkbWdw
      OApOMThJRURvTkVWS1ViS3VLZS9aNXlmOFo5dG1leGZIMVl0dGptWE1Pb2pCdlVISWpSUzVoZEk5
      TnhuUEdSTFkya2pBemNtCmdWOVJ2M3Z0ZEYvK3phbGszZkFWTGVLOGhYSytkaS83WFR2WXBmSjJF
      WkJXaU5yVGVhZ2ZOTkdpWXlkc1F5M3pqWkFBQUEKd0JOUmFrN1VycW5JSE1abjdwa0NUZ2NlYjFN
      ZkJ5YUZ0bE56ZCtPYmFoNTRIWUlRajVXZFpUQkFJVFJlTVpOdDlTNU5BUgpNOHNRQjhVb1pQYVZT
      QzNwcElMSU9mTGhzNktZajZSckdkaVl3eUloTVBKNWtSV0Y4eEdDTFVYNUNqd0gyRU9xN1hoSVd0
      Ck13RUZ0ZC9nRjJEdTdIVU5GUHNaR256SjNlN3BES0RuRTd3MmtoWjhDSXBURmdENzY5dUJZR0F0
      azQ1UVlURG81SnJvVk0KWlBEcTA4R2IvUmhJZ0pMbUlwTXd5cmVWcExMTGU4U3dvTUpKK3JpaG1u
      Slp4TzhnQUFBTUVBMGxoaUtlemVUc2hodDR4dQpyV2MwTnh4RDg0YTI5Z1NHZlRwaERQT3JsS1NF
      WWJrU1hoanFDc0FaSGQ4UzhrTXIzaUY2cG9PazNJV1N2Rko2bWJkM2llCnFkUlRnWEg5VGh3azRL
      Z3BqVWhOc1F1WVJIQmJJNTlNbytCeFNJMUIxcXptSlNHZG1DQkw1NHd3elptRktEUVBRS1B4aUwK
      bjBNbGM3R29vaURNalQxdGJ1Vy9PMUVMNUVxVFJxd2dXUFRLaEJBNnI0UG5HRjE1MGhaUklNb29a
      a0Qyelg2YjFzR29qawpRcHZLa0V5a1R3bktDekY1VFhPOCt3SjNxYmNFbzlBQUFBd1FEK1owcjY4
      YzJZTU5wc215ajNaS3RaTlBTdkpOY0xteUQvCmxXb05KcTNkakpONHMySmJLOGw1QVJVZFczeFNG
      RURJOXl4L3dwZnNYb2FxV255Z1AzUG9GdzJDTTRpMEVpSml5dnJMRlUKcjNKTGZEVUZSeTNFSjI0
      UnNxYmlnbUVzZ1FPelRsM3hmemVGUGZ4Rm9PaG9rU3ZURzg4UFFqaTFBWUh6NWtBN3A2WmZhegpP
      azExckpZSWU3K2U5QjBsaGt1MEFGd0d5cWxXUW1TL01oSXBuakhJazV0UDRoZUhHU216S1FXSkRi
      VHNrTldkNmFxMUc3CjZIV2ZEcFg0SGdvTThBQUFBTGFHOXNiV0Z1WWtCaGNtTT0KLS0tLS1FTkQg
      T1BFTlNTSCBQUklWQVRFIEtFWS0tLS0tCg==

10.9. Добавление основных репозиториев apt

#cloud-config

# Add primary apt repositories
#
# To add 3rd party repositories, see cloud-config-apt.txt or the
# Additional apt configuration and repositories section.
#
#
# Default: auto select based on cloud metadata
#  in ec2, the default is <region>.archive.ubuntu.com
# apt:
#   primary:
#     - arches [default]
#       uri:
#     use the provided mirror
#       search:
#     search the list for the first mirror.
#     this is currently very limited, only verifying that
#     the mirror is dns resolvable or an IP address
#
# if neither mirror is set (the default)
# then use the mirror provided by the DataSource found.
# In EC2, that means using <region>.ec2.archive.ubuntu.com
#
# if no mirror is provided by the DataSource, but 'search_dns' is
# true, then search for dns names '<distro>-mirror' in each of
# - fqdn of this host per cloud metadata
# - localdomain
# - no domain (which would search domains listed in /etc/resolv.conf)
# If there is a dns entry for <distro>-mirror, then it is assumed that there
# is a distro mirror at http://<distro>-mirror.<domain>/<distro>
#
# That gives the cloud provider the opportunity to set mirrors of a distro
# up and expose them only by creating dns entries.
#
# if none of that is found, then the default distro mirror is used
apt:
  primary:
    - arches: [default]
      uri: http://us.archive.ubuntu.com/ubuntu/
# or
apt:
  primary:
    - arches: [default]
      search:
        - http://local-mirror.mydomain
        - http://archive.ubuntu.com
# or
apt:
  primary:
    - arches: [default]
      search_dns: True

10.10. Запуск команд при первой загрузке

10.10.1. Пример 1

#cloud-config

# boot commands
# default: none
# this is very similar to runcmd, but commands run very early
# in the boot process, only slightly after a 'boothook' would run.
# bootcmd should really only be used for things that could not be
# done later in the boot process.  bootcmd is very much like
# boothook, but possibly with more friendly.
# - bootcmd will run on every boot
# - the INSTANCE_ID variable will be set to the current instance id.
# - you can use 'cloud-init-per' command to help only run once
bootcmd:
  - echo 192.168.1.130 us.archive.ubuntu.com >> /etc/hosts
  - [ cloud-init-per, once, mymkfs, mkfs, /dev/vdb ]

10.10.2. Пример 2

#cloud-config

# run commands
# default: none
# runcmd contains a list of either lists or a string
# each item will be executed in order at rc.local like level with
# output to the console
# - runcmd only runs during the first boot
# - if the item is a list, the items will be properly executed as if
#   passed to execve(3) (with the first arg as the command).
# - if the item is a string, it will be simply written to the file and
#   will be interpreted by 'sh'
#
# Note, that the list has to be proper yaml, so you have to quote
# any characters yaml would eat (':' can be problematic)
runcmd:
 - [ ls, -l, / ]
 - [ sh, -xc, "echo $(date) ': hello world!'" ]
 - [ sh, -c, echo "=========hello world=========" ]
 - ls -l /root
 # Note: Don't write files to /tmp from cloud-init use /run/somedir instead.
 # Early boot environments can race systemd-tmpfiles-clean LP: #1707222.
 - mkdir /run/mydir
 - [ wget, "http://slashdot.org", -O, /run/mydir/index.html ]

10.11. Установка произвольных пакетов

#cloud-config

# Install additional packages on first boot
#
# Default: none
#
# if packages are specified, then package_update will be set to true
#
# packages may be supplied as a single package name or as a list
# with the format [<package>, <version>] wherein the specific
# package version will be installed.
packages:
 - pwgen
 - pastebinit
 - [libpython2.7, 2.7.3-0ubuntu3.1]

10.12. Обновление базы apt при первой загрузке

#cloud-config
# Update apt database on first boot (run 'apt-get update').
# Note, if packages are given, or package_upgrade is true, then
# update will be done independent of this setting.
#
# Default: false
package_update: true

10.13. Запуск обновления посредством yum или apt

#cloud-config

# Upgrade the instance on first boot
#
# Default: false
package_upgrade: true

10.14. Управление точками монтирования

#cloud-config

# set up mount points
# 'mounts' contains a list of lists
#  the inner list are entries for an /etc/fstab line
#  ie : [ fs_spec, fs_file, fs_vfstype, fs_mntops, fs-freq, fs_passno ]
#
# default:
# mounts:
#  - [ ephemeral0, /mnt ]
#  - [ swap, none, swap, sw, 0, 0 ]
#
# in order to remove a previously listed mount (ie, one from defaults)
# list only the fs_spec.  For example, to override the default, of
# mounting swap:
# - [ swap ]
# or
# - [ swap, null ]
#
# - if a device does not exist at the time, an entry will still be
#   written to /etc/fstab.
# - '/dev' can be omitted for device names that begin with: xvd, sd, hd, vd
# - if an entry does not have all 6 fields, they will be filled in
#   with values from 'mount_default_fields' below.
#
# Note, that you should set 'nofail' (see man fstab) for volumes that may not
# be attached at instance boot (or reboot).
#
mounts:
 - [ ephemeral0, /mnt, auto, "defaults,noexec" ]
 - [ sdc, /opt/data ]
 - [ xvdh, /opt/data, "auto", "defaults,nofail", "0", "0" ]
 - [ dd, /dev/zero ]

# mount_default_fields
# These values are used to fill in any entries in 'mounts' that are not
# complete.  This must be an array, and must have 6 fields.
mount_default_fields: [ None, None, "auto", "defaults,nofail", "0", "2" ]


# swap can also be set up by the 'mounts' module
# default is to not create any swap files, because 'size' is set to 0
swap:
  filename: /swap.img
  size: "auto" # or size in bytes
  maxsize: 10485760   # size in bytes

10.15. Настройка ключей SSH для экземпляров

#cloud-config

# add each entry to ~/.ssh/authorized_keys for the configured user or the
# first user defined in the user definition directive.
ssh_authorized_keys:
  - ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEA3FSyQwBI6Z+nCSjUUk8EEAnnkhXlukKoUPND/RRClWz2s5TCzIkd3Ou5+Cyz71X0XmazM3l5WgeErvtIwQMyT1KjNoMhoJMrJnWqQPOt5Q8zWd9qG7PBl9+eiH5qV7NZ mykey@host
  - ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA3I7VUf2l5gSn5uavROsc5HRDpZdQueUq5ozemNSj8T7enqKHOEaFoU2VoPgGEWC9RyzSQVeyD6s7APMcE82EtmW4skVEgEGSbDc1pvxzxtchBj78hJP6Cf5TCMFSXw+Fz5rF1dR23QDbN1mkHs7adr8GW4kSWqU7Q7NDwfIrJJtO7Hi42GyXtvEONHbiRPOe8stqUly7MvUoN+5kfjBM8Qqpfl2+FNhTYWpMfYdPUnE7u536WqzFmsaqJctz3gBxH9Ex7dFtrxR4qiqEr9Qtlu3xGn7Bw07/+i1D+ey3ONkZLN+LQ714cgj8fRS4Hj29SCmXp5Kt5/82cD/VN3NtHw== smoser@brickies

# Send pre-generated SSH private keys to the server
# If these are present, they will be written to /etc/ssh and
# new random keys will not be generated
#  in addition to 'rsa' and 'dsa' as shown below, 'ecdsa' is also supported
ssh_keys:
  rsa_private: |
    -----BEGIN RSA PRIVATE KEY-----
    MIIBxwIBAAJhAKD0YSHy73nUgysO13XsJmd4fHiFyQ+00R7VVu2iV9Qcon2LZS/x
    1cydPZ4pQpfjEha6WxZ6o8ci/Ea/w0n+0HGPwaxlEG2Z9inNtj3pgFrYcRztfECb
    1j6HCibZbAzYtwIBIwJgO8h72WjcmvcpZ8OvHSvTwAguO2TkR6mPgHsgSaKy6GJo
    PUJnaZRWuba/HX0KGyhz19nPzLpzG5f0fYahlMJAyc13FV7K6kMBPXTRR6FxgHEg
    L0MPC7cdqAwOVNcPY6A7AjEA1bNaIjOzFN2sfZX0j7OMhQuc4zP7r80zaGc5oy6W
    p58hRAncFKEvnEq2CeL3vtuZAjEAwNBHpbNsBYTRPCHM7rZuG/iBtwp8Rxhc9I5w
    ixvzMgi+HpGLWzUIBS+P/XhekIjPAjA285rVmEP+DR255Ls65QbgYhJmTzIXQ2T9
    luLvcmFBC6l35Uc4gTgg4ALsmXLn71MCMGMpSWspEvuGInayTCL+vEjmNBT+FAdO
    W7D4zCpI43jRS9U06JVOeSc9CDk2lwiA3wIwCTB/6uc8Cq85D9YqpM10FuHjKpnP
    REPPOyrAspdeOAV+6VKRavstea7+2DZmSUgE
    -----END RSA PRIVATE KEY-----

  rsa_public: ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEAoPRhIfLvedSDKw7XdewmZ3h8eIXJD7TRHtVW7aJX1ByifYtlL/HVzJ09nilCl+MSFrpbFnqjxyL8Rr/DSf7QcY/BrGUQbZn2Kc22PemAWthxHO18QJvWPocKJtlsDNi3 smoser@localhost

  dsa_private: |
    -----BEGIN DSA PRIVATE KEY-----
    MIIBuwIBAAKBgQDP2HLu7pTExL89USyM0264RCyWX/CMLmukxX0Jdbm29ax8FBJT
    pLrO8TIXVY5rPAJm1dTHnpuyJhOvU9G7M8tPUABtzSJh4GVSHlwaCfycwcpLv9TX
    DgWIpSj+6EiHCyaRlB1/CBp9RiaB+10QcFbm+lapuET+/Au6vSDp9IRtlQIVAIMR
    8KucvUYbOEI+yv+5LW9u3z/BAoGBAI0q6JP+JvJmwZFaeCMMVxXUbqiSko/P1lsa
    LNNBHZ5/8MOUIm8rB2FC6ziidfueJpqTMqeQmSAlEBCwnwreUnGfRrKoJpyPNENY
    d15MG6N5J+z81sEcHFeprryZ+D3Ge9VjPq3Tf3NhKKwCDQ0240aPezbnjPeFm4mH
    bYxxcZ9GAoGAXmLIFSQgiAPu459rCKxT46tHJtM0QfnNiEnQLbFluefZ/yiI4DI3
    8UzTCOXLhUA7ybmZha+D/csj15Y9/BNFuO7unzVhikCQV9DTeXX46pG4s1o23JKC
    /QaYWNMZ7kTRv+wWow9MhGiVdML4ZN4XnifuO5krqAybngIy66PMEoQCFEIsKKWv
    99iziAH0KBMVbxy03Trz
    -----END DSA PRIVATE KEY-----

  dsa_public: ssh-dss AAAAB3NzaC1kc3MAAACBAM/Ycu7ulMTEvz1RLIzTbrhELJZf8Iwua6TFfQl1ubb1rHwUElOkus7xMhdVjms8AmbV1Meem7ImE69T0bszy09QAG3NImHgZVIeXBoJ/JzByku/1NcOBYilKP7oSIcLJpGUHX8IGn1GJoH7XRBwVub6Vqm4RP78C7q9IOn0hG2VAAAAFQCDEfCrnL1GGzhCPsr/uS1vbt8/wQAAAIEAjSrok/4m8mbBkVp4IwxXFdRuqJKSj8/WWxos00Ednn/ww5QibysHYULrOKJ1+54mmpMyp5CZICUQELCfCt5ScZ9GsqgmnI80Q1h3Xkwbo3kn7PzWwRwcV6muvJn4PcZ71WM+rdN/c2EorAINDTbjRo97NueM94WbiYdtjHFxn0YAAACAXmLIFSQgiAPu459rCKxT46tHJtM0QfnNiEnQLbFluefZ/yiI4DI38UzTCOXLhUA7ybmZha+D/csj15Y9/BNFuO7unzVhikCQV9DTeXX46pG4s1o23JKC/QaYWNMZ7kTRv+wWow9MhGiVdML4ZN4XnifuO5krqAybngIy66PMEoQ= smoser@localhost

# By default, the fingerprints of the authorized keys for the users
# cloud-init adds are printed to the console. Setting
# no_ssh_fingerprints to true suppresses this output.
no_ssh_fingerprints: false

# By default, (most) ssh host keys are printed to the console. Setting
# emit_keys_to_console to false suppresses this output.
ssh:
  emit_keys_to_console: false

10.16. Дополнительные настройки apt и репозиториев

#cloud-config
# apt_pipelining (configure Acquire::http::Pipeline-Depth)
# Default: disables HTTP pipelining. Certain web servers, such
# as S3 do not pipeline properly (LP: #948461).
# Valid options:
#   False/default: Disables pipelining for APT
#   None/Unchanged: Use OS default
#   Number: Set pipelining to some number (not recommended)
apt_pipelining: False

## apt config via system_info:
# under the 'system_info', you can customize cloud-init's interaction
# with apt.
#  system_info:
#    apt_get_command: [command, argument, argument]
#    apt_get_upgrade_subcommand: dist-upgrade
#
# apt_get_command:
#  To specify a different 'apt-get' command, set 'apt_get_command'.
#  This must be a list, and the subcommand (update, upgrade) is appended to it.
#  default is:
#    ['apt-get', '--option=Dpkg::Options::=--force-confold',
#     '--option=Dpkg::options::=--force-unsafe-io', '--assume-yes', '--quiet']
#
# apt_get_upgrade_subcommand: "dist-upgrade"
#  Specify a different subcommand for 'upgrade. The default is 'dist-upgrade'.
#  This is the subcommand that is invoked for package_upgrade.
#
# apt_get_wrapper:
#   command: eatmydata
#   enabled: [True, False, "auto"]
#

# Install additional packages on first boot
#
# Default: none
#
# if packages are specified, then package_update will be set to true

packages: ['pastebinit']

apt:
  # The apt config consists of two major "areas".
  #
  # On one hand there is the global configuration for the apt feature.
  #
  # On one hand (down in this file) there is the source dictionary which allows
  # to define various entries to be considered by apt.

  ##############################################################################
  # Section 1: global apt configuration
  #
  # The following examples number the top keys to ease identification in
  # discussions.

  # 1.1 preserve_sources_list
  #
  # Preserves the existing /etc/apt/sources.list
  # Default: false - do overwrite sources_list. If set to true then any
  # "mirrors" configuration will have no effect.
  # Set to true to avoid affecting sources.list. In that case only
  # "extra" source specifications will be written into
  # /etc/apt/sources.list.d/*
  preserve_sources_list: true

  # 1.2 disable_suites
  #
  # This is an empty list by default, so nothing is disabled.
  #
  # If given, those suites are removed from sources.list after all other
  # modifications have been made.
  # Suites are even disabled if no other modification was made,
  # but not if is preserve_sources_list is active.
  # There is a special alias "$RELEASE" as in the sources that will be replace
  # by the matching release.
  #
  # To ease configuration and improve readability the following common ubuntu
  # suites will be automatically mapped to their full definition.
  # updates   => $RELEASE-updates
  # backports => $RELEASE-backports
  # security  => $RELEASE-security
  # proposed  => $RELEASE-proposed
  # release   => $RELEASE
  #
  # There is no harm in specifying a suite to be disabled that is not found in
  # the source.list file (just a no-op then)
  #
  # Note: Lines don't get deleted, but disabled by being converted to a comment.
  # The following example disables all usual defaults except $RELEASE-security.
  # On top it disables a custom suite called "mysuite"
  disable_suites: [$RELEASE-updates, backports, $RELEASE, mysuite]

  # 1.3 primary/security archives
  #
  # Default: none - instead it is auto select based on cloud metadata
  # so if neither "uri" nor "search", nor "search_dns" is set (the default)
  # then use the mirror provided by the DataSource found.
  # In EC2, that means using <region>.ec2.archive.ubuntu.com
  #
  # define a custom (e.g. localized) mirror that will be used in sources.list
  # and any custom sources entries for deb / deb-src lines.
  #
  # One can set primary and security mirror to different uri's
  # the child elements to the keys primary and secondary are equivalent
  primary:
    # arches is list of architectures the following config applies to
    # the special keyword "default" applies to any architecture not explicitly
    # listed.
    - arches: [amd64, i386, default]
      # uri is just defining the target as-is
      uri: http://us.archive.ubuntu.com/ubuntu
      #
      # via search one can define lists that are tried one by one.
      # The first with a working DNS resolution (or if it is an IP) will be
      # picked. That way one can keep one configuration for multiple
      # subenvironments that select the working one.
      search:
        - http://cool.but-sometimes-unreachable.com/ubuntu
        - http://us.archive.ubuntu.com/ubuntu
      # if no mirror is provided by uri or search but 'search_dns' is
      # true, then search for dns names '<distro>-mirror' in each of
      # - fqdn of this host per cloud metadata
      # - localdomain
      # - no domain (which would search domains listed in /etc/resolv.conf)
      # If there is a dns entry for <distro>-mirror, then it is assumed that
      # there is a distro mirror at http://<distro>-mirror.<domain>/<distro>
      #
      # That gives the cloud provider the opportunity to set mirrors of a distro
      # up and expose them only by creating dns entries.
      #
      # if none of that is found, then the default distro mirror is used
      search_dns: true
      #
      # If multiple of a category are given
      #   1. uri
      #   2. search
      #   3. search_dns
      # the first defining a valid mirror wins (in the order as defined here,
      # not the order as listed in the config).
      #
      # Additionally, if the repository requires a custom signing key, it can be
      # specified via the same fields as for custom sources:
      #   'keyid': providing a key to import via shortid or fingerprint
      #   'key': providing a raw PGP key
      #   'keyserver': specify an alternate keyserver to pull keys from that
      #                were specified by keyid
    - arches: [s390x, arm64]
      # as above, allowing to have one config for different per arch mirrors
  # security is optional, if not defined it is set to the same value as primary
  security:
    - uri: http://security.ubuntu.com/ubuntu
      arches: [default]
  # If search_dns is set for security the searched pattern is:
  #   <distro>-security-mirror

  # if no mirrors are specified at all, or all lookups fail it will try
  # to get them from the cloud datasource and if those neither provide one fall
  # back to:
  #   primary: http://archive.ubuntu.com/ubuntu
  #   security: http://security.ubuntu.com/ubuntu

  # 1.4 sources_list
  #
  # Provide a custom template for rendering sources.list
  # without one provided cloud-init uses builtin templates for
  # ubuntu and debian.
  # Within these sources.list templates you can use the following replacement
  # variables (all have sane Ubuntu defaults, but mirrors can be overwritten
  # as needed (see above)):
  # => $RELEASE, $MIRROR, $PRIMARY, $SECURITY
  sources_list: | # written by cloud-init custom template
    deb $MIRROR $RELEASE main restricted
    deb-src $MIRROR $RELEASE main restricted
    deb $PRIMARY $RELEASE universe restricted
    deb $SECURITY $RELEASE-security multiverse

  # 1.5 conf
  #
  # Any apt config string that will be made available to apt
  # see the APT.CONF(5) man page for details what can be specified
  conf: | # APT config
    APT {
      Get {
        Assume-Yes "true";
        Fix-Broken "true";
      };
    };

  # 1.6 (http_|ftp_|https_)proxy
  #
  # Proxies are the most common apt.conf option, so that for simplified use
  # there is a shortcut for those. Those get automatically translated into the
  # correct Acquire::*::Proxy statements.
  #
  # note: proxy actually being a short synonym to http_proxy
  proxy: http://[[user][:pass]@]host[:port]/
  http_proxy: http://[[user][:pass]@]host[:port]/
  ftp_proxy: ftp://[[user][:pass]@]host[:port]/
  https_proxy: https://[[user][:pass]@]host[:port]/

  # 1.7 add_apt_repo_match
  #
  # 'source' entries in apt-sources that match this python regex
  # expression will be passed to add-apt-repository
  # The following example is also the builtin default if nothing is specified
  add_apt_repo_match: '^[\w-]+:\w'


  ##############################################################################
  # Section 2: source list entries
  #
  # This is a dictionary (unlike most block/net which are lists)
  #
  # The key of each source entry is the filename and will be prepended by
  # /etc/apt/sources.list.d/ if it doesn't start with a '/'.
  # If it doesn't end with .list it will be appended so that apt picks up its
  # configuration.
  #
  # Whenever there is no content to be written into such a file, the key is
  # not used as filename - yet it can still be used as index for merging
  # configuration.
  #
  # The values inside the entries consist of the following optional entries:
  #   'source': a sources.list entry (some variable replacements apply)
  #   'keyid': providing a key to import via shortid or fingerprint
  #   'key': providing a raw PGP key
  #   'keyserver': specify an alternate keyserver to pull keys from that
  #                were specified by keyid

  # This allows merging between multiple input files than a list like:
  # cloud-config1
  # sources:
  #   s1: {'key': 'key1', 'source': 'source1'}
  # cloud-config2
  # sources:
  #   s2: {'key': 'key2'}
  #   s1: {'keyserver': 'foo'}
  # This would be merged to
  # sources:
  #   s1:
  #     keyserver: foo
  #     key: key1
  #     source: source1
  #   s2:
  #     key: key2
  #
  # The following examples number the subfeatures per sources entry to ease
  # identification in discussions.


  sources:
    curtin-dev-ppa.list:
      # 2.1 source
      #
      # Creates a file in /etc/apt/sources.list.d/ for the sources list entry
      # based on the key: "/etc/apt/sources.list.d/curtin-dev-ppa.list"
      source: "deb http://ppa.launchpad.net/curtin-dev/test-archive/ubuntu bionic main"

      # 2.2 keyid
      #
      # Importing a gpg key for a given key id. Used keyserver defaults to
      # keyserver.ubuntu.com
      keyid: F430BBA5 # GPG key ID published on a key server

    ignored1:
      # 2.3 PPA shortcut
      #
      # Setup correct apt sources.list line and Auto-Import the signing key
      # from LP
      #
      # See https://help.launchpad.net/Packaging/PPA for more information
      # this requires 'add-apt-repository'. This will create a file in
      # /etc/apt/sources.list.d automatically, therefore the key here is
      # ignored as filename in those cases.
      source: "ppa:curtin-dev/test-archive"    # Quote the string

    my-repo2.list:
      # 2.4 replacement variables
      #
      # sources can use $MIRROR, $PRIMARY, $SECURITY, $RELEASE and $KEY_FILE
      # replacement variables.
      # They will be replaced with the default or specified mirrors and the
      # running release.
      # The entry below would be possibly turned into:
      #   source: deb http://archive.ubuntu.com/ubuntu bionic multiverse
      source: deb [signed-by=$KEY_FILE] $MIRROR $RELEASE multiverse
      keyid: F430BBA5

    my-repo3.list:
      # this would have the same end effect as 'ppa:curtin-dev/test-archive'
      source: "deb http://ppa.launchpad.net/curtin-dev/test-archive/ubuntu bionic main"
      keyid: F430BBA5 # GPG key ID published on the key server
      filename: curtin-dev-ppa.list

    ignored2:
      # 2.5 key only
      #
      # this would only import the key without adding a ppa or other source spec
      # since this doesn't generate a source.list file the filename key is ignored
      keyid: F430BBA5 # GPG key ID published on a key server

    ignored3:
      # 2.6 key id alternatives
      #
      # Keyid's can also be specified via their long fingerprints
      keyid: B59D 5F15 97A5 04B7 E230  6DCA 0620 BBCF 0368 3F77

    ignored4:
      # 2.7 alternative keyservers
      #
      # One can also specify alternative keyservers to fetch keys from.
      keyid: B59D 5F15 97A5 04B7 E230  6DCA 0620 BBCF 0368 3F77
      keyserver: pgp.mit.edu

    ignored5:
      # 2.8 signed-by
      #
      # One can specify [signed-by=$KEY_FILE] in the source definition, which
      # will make the key be installed in the directory /etc/cloud-init.gpg.d/
      # and the $KEY_FILE replacement variable will be replaced with the path
      # to the specified key. If $KEY_FILE is used, but no key is specified,
      # apt update will (rightfully) fail due to an invalid value.
      source: deb [signed-by=$KEY_FILE] $MIRROR $RELEASE multiverse
      keyid: B59D 5F15 97A5 04B7 E230  6DCA 0620 BBCF 0368 3F77

    my-repo4.list:
      # 2.9 raw key
      #
      # The apt signing key can also be specified by providing a pgp public key
      # block. Providing the PGP key this way is the most robust method for
      # specifying a key, as it removes dependency on a remote key server.
      #
      # As with keyid's this can be specified with or without some actual source
      # content.
      key: | # The value needs to start with -----BEGIN PGP PUBLIC KEY BLOCK-----
        -----BEGIN PGP PUBLIC KEY BLOCK-----
        Version: SKS 1.0.10

        mI0ESpA3UQEEALdZKVIMq0j6qWAXAyxSlF63SvPVIgxHPb9Nk0DZUixn+akqytxG4zKCONz6
        qLjoBBfHnynyVLfT4ihg9an1PqxRnTO+JKQxl8NgKGz6Pon569GtAOdWNKw15XKinJTDLjnj
        9y96ljJqRcpV9t/WsIcdJPcKFR5voHTEoABE2aEXABEBAAG0GUxhdW5jaHBhZCBQUEEgZm9y
        IEFsZXN0aWOItgQTAQIAIAUCSpA3UQIbAwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEA7H
        5Qi+CcVxWZ8D/1MyYvfj3FJPZUm2Yo1zZsQ657vHI9+pPouqflWOayRR9jbiyUFIn0VdQBrP
        t0FwvnOFArUovUWoKAEdqR8hPy3M3APUZjl5K4cMZR/xaMQeQRZ5CHpS4DBKURKAHC0ltS5o
        uBJKQOZm5iltJp15cgyIkBkGe8Mx18VFyVglAZey
        =Y2oI
        -----END PGP PUBLIC KEY BLOCK-----

10.17. Настройка диска

#cloud-config
# Cloud-init supports the creation of simple partition tables and file systems
# on devices.

# Default disk definitions for AWS
# --------------------------------
# (Not implemented yet, but provided for future documentation)

disk_setup:
  ephemeral0:
    table_type: 'mbr'
    layout: True
    overwrite: False

fs_setup:
  - label: None,
    filesystem: ext3
    device: ephemeral0
    partition: auto

# Default disk definitions for Microsoft Azure
# ------------------------------------------

device_aliases: {'ephemeral0': '/dev/sdb'}
disk_setup:
  ephemeral0:
    table_type: mbr
    layout: True
    overwrite: False

fs_setup:
  - label: ephemeral0
    filesystem: ext4
    device: ephemeral0.1
    replace_fs: ntfs


# Data disks definitions for Microsoft Azure
# ------------------------------------------

disk_setup:
  /dev/disk/azure/scsi1/lun0:
    table_type: gpt
    layout: True
    overwrite: True

fs_setup:
  - device: /dev/disk/azure/scsi1/lun0
    partition: 1
    filesystem: ext4


# Default disk definitions for SmartOS
# ------------------------------------

device_aliases: {'ephemeral0': '/dev/vdb'}
disk_setup:
  ephemeral0:
    table_type: mbr
    layout: False
    overwrite: False

fs_setup:
  - label: ephemeral0
    filesystem: ext4
    device: ephemeral0.0

# Caveat for SmartOS: if ephemeral disk is not defined, then the disk will
#    not be automatically added to the mounts.


# The default definition is used to make sure that the ephemeral storage is
# setup properly.

# "disk_setup": disk partitioning
# --------------------------------

# The disk_setup directive instructs Cloud-init to partition a disk. The format is:

disk_setup:
  ephemeral0:
    table_type: 'mbr'
    layout: true
  /dev/xvdh:
    table_type: 'mbr'
    layout:
      - 33
      - [33, 82]
      - 33
    overwrite: True

# The format is a list of dicts of dicts. The first value is the name of the
# device and the subsequent values define how to create and layout the
# partition.
# The general format is:
#   disk_setup:
#     <DEVICE>:
#       table_type: 'mbr'
#       layout: <LAYOUT|BOOL>
#       overwrite: <BOOL>
#
# Where:
#   <DEVICE>: The name of the device. 'ephemeralX' and 'swap' are special
#               values which are specific to the cloud. For these devices
#               Cloud-init will look up what the real devices is and then
#               use it.
#
#               For other devices, the kernel device name is used. At this
#               time only simply kernel devices are supported, meaning
#               that device mapper and other targets may not work.
#
#               Note: At this time, there is no handling or setup of
#               device mapper targets.
#
#   table_type=<TYPE>: Currently the following are supported:
#                   'mbr': default and setups a MS-DOS partition table
#                   'gpt': setups a GPT partition table
#
#               Note: At this time only 'mbr' and 'gpt' partition tables
#                   are allowed. It is anticipated in the future that
#                   we'll also have "RAID" to create a mdadm RAID.
#
#   layout={...}: The device layout. This is a list of values, with the
#               percentage of disk that partition will take.
#               Valid options are:
#                   [<SIZE>, [<SIZE>, <PART_TYPE]]
#
#               Where <SIZE> is the _percentage_ of the disk to use, while
#               <PART_TYPE> is the numerical value of the partition type.
#
#               The following setups two partitions, with the first
#               partition having a swap label, taking 1/3 of the disk space
#               and the remainder being used as the second partition.
#                 /dev/xvdh':
#                   table_type: 'mbr'
#                   layout:
#                     - [33,82]
#                     - 66
#                   overwrite: True
#
#               When layout is "true" it means single partition the entire
#               device.
#
#               When layout is "false" it means don't partition or ignore
#               existing partitioning.
#
#               If layout is set to "true" and overwrite is set to "false",
#               it will skip partitioning the device without a failure.
#
#   overwrite=<BOOL>: This describes whether to ride with saftey's on and
#               everything holstered.
#
#               'false' is the default, which means that:
#                   1. The device will be checked for a partition table
#                   2. The device will be checked for a file system
#                   3. If either a partition of file system is found, then
#                       the operation will be _skipped_.
#
#               'true' is cowboy mode. There are no checks and things are
#                   done blindly. USE with caution, you can do things you
#                   really, really don't want to do.
#
#
# fs_setup: Setup the file system
# -------------------------------
#
# fs_setup describes the how the file systems are supposed to look.

fs_setup:
  - label: ephemeral0
    filesystem: 'ext3'
    device: 'ephemeral0'
    partition: 'auto'
  - label: mylabl2
    filesystem: 'ext4'
    device: '/dev/xvda1'
  - cmd: mkfs -t %(filesystem)s -L %(label)s %(device)s
    label: mylabl3
    filesystem: 'btrfs'
    device: '/dev/xvdh'

# The general format is:
#   fs_setup:
#     - label: <LABEL>
#       filesystem: <FS_TYPE>
#       device: <DEVICE>
#       partition: <PART_VALUE>
#       overwrite: <OVERWRITE>
#       replace_fs: <FS_TYPE>
#
# Where:
#   <LABEL>: The file system label to be used. If set to None, no label is
#     used.
#
#   <FS_TYPE>: The file system type. It is assumed that the there
#     will be a "mkfs.<FS_TYPE>" that behaves likes "mkfs". On a standard
#     Ubuntu Cloud Image, this means that you have the option of ext{2,3,4},
#     and vfat by default.
#
#   <DEVICE>: The device name. Special names of 'ephemeralX' or 'swap'
#     are allowed and the actual device is acquired from the cloud datasource.
#     When using 'ephemeralX' (i.e. ephemeral0), make sure to leave the
#     label as 'ephemeralX' otherwise there may be issues with the mounting
#     of the ephemeral storage layer.
#
#     If you define the device as 'ephemeralX.Y' then Y will be interpetted
#     as a partition value. However, ephermalX.0 is the _same_ as ephemeralX.
#
#   <PART_VALUE>:
#     Partition definitions are overwritten if you use the '<DEVICE>.Y' notation.
#
#     The valid options are:
#     "auto|any": tell cloud-init not to care whether there is a partition
#       or not. Auto will use the first partition that does not contain a
#       file system already. In the absence of a partition table, it will
#       put it directly on the disk.
#
#       "auto": If a file system that matches the specification in terms of
#       label, type and device, then cloud-init will skip the creation of
#       the file system.
#
#       "any": If a file system that matches the file system type and device,
#       then cloud-init will skip the creation of the file system.
#
#       Devices are selected based on first-detected, starting with partitions
#       and then the raw disk. Consider the following:
#           NAME     FSTYPE LABEL
#           xvdb
#           |-xvdb1  ext4
#           |-xvdb2
#           |-xvdb3  btrfs  test
#           \-xvdb4  ext4   test
#
#         If you ask for 'auto', label of 'test, and file system of 'ext4'
#         then cloud-init will select the 2nd partition, even though there
#         is a partition match at the 4th partition.
#
#         If you ask for 'any' and a label of 'test', then cloud-init will
#         select the 1st partition.
#
#         If you ask for 'auto' and don't define label, then cloud-init will
#         select the 1st partition.
#
#         In general, if you have a specific partition configuration in mind,
#         you should define either the device or the partition number. 'auto'
#         and 'any' are specifically intended for formatting ephemeral storage or
#         for simple schemes.
#
#       "none": Put the file system directly on the device.
#
#       <NUM>: where NUM is the actual partition number.
#
#   <OVERWRITE>: Defines whether or not to overwrite any existing
#     filesystem.
#
#     "true": Indiscriminately destroy any pre-existing file system. Use at
#         your own peril.
#
#     "false": If an existing file system exists, skip the creation.
#
#   <REPLACE_FS>: This is a special directive, used for Microsoft Azure that
#     instructs cloud-init to replace a file system of <FS_TYPE>. NOTE:
#     unless you define a label, this requires the use of the 'any' partition
#     directive.
#
# Behavior Caveat: The default behavior is to _check_ if the file system exists.
#   If a file system matches the specification, then the operation is a no-op.

10.18. Настройка источников данных

#cloud-config

# Documentation on data sources configuration options
datasource:
  # Ec2
  Ec2:
    # timeout: the timeout value for a request at metadata service
    timeout : 50
    # The length in seconds to wait before giving up on the metadata
    # service.  The actual total wait could be up to
    #   len(resolvable_metadata_urls)*timeout
    max_wait : 120

    #metadata_url: a list of URLs to check for metadata services
    metadata_urls:
     - http://169.254.169.254:80
     - http://instance-data:8773

  MAAS:
    timeout : 50
    max_wait : 120

    # there are no default values for metadata_url or oauth credentials
    # If no credentials are present, non-authed attempts will be made.
    metadata_url: http://mass-host.localdomain/source
    consumer_key: Xh234sdkljf
    token_key: kjfhgb3n
    token_secret: 24uysdfx1w4

  NoCloud:
    # default seedfrom is None
    # if found, then it should contain a url with:
    #    <url>/user-data and <url>/meta-data
    # seedfrom: http://my.example.com/i-abcde/
    seedfrom: None

    # fs_label: the label on filesystems to be searched for NoCloud source
    fs_label: cidata

    # these are optional, but allow you to basically provide a datasource
    # right here
    user-data: |
      # This is the user-data verbatim
    meta-data:
      instance-id: i-87018aed
      local-hostname: myhost.internal

  SmartOS:
    # For KVM guests:
    # Smart OS datasource works over a serial console interacting with
    # a server on the other end. By default, the second serial console is the
    # device. SmartOS also uses a serial timeout of 60 seconds.
    serial_device: /dev/ttyS1
    serial_timeout: 60

    # For LX-Brand Zones guests:
    # Smart OS datasource works over a socket interacting with
    # the host on the other end. By default, the socket file is in
    # the native .zoncontrol directory.
    metadata_sockfile: /native/.zonecontrol/metadata.sock

    # a list of keys that will not be base64 decoded even if base64_all
    no_base64_decode: ['root_authorized_keys', 'motd_sys_info',
                       'iptables_disable']
    # a plaintext, comma delimited list of keys whose values are b64 encoded
    base64_keys: []
    # a boolean indicating that all keys not in 'no_base64_decode' are encoded
    base64_all: False

10.19. Создание разделов и файловых систем

#cloud-config
# Cloud-init supports the creation of simple partition tables and file systems
# on devices.

# Default disk definitions for AWS
# --------------------------------
# (Not implemented yet, but provided for future documentation)

disk_setup:
  ephemeral0:
    table_type: 'mbr'
    layout: True
    overwrite: False

fs_setup:
  - label: None,
    filesystem: ext3
    device: ephemeral0
    partition: auto

# Default disk definitions for Microsoft Azure
# ------------------------------------------

device_aliases: {'ephemeral0': '/dev/sdb'}
disk_setup:
  ephemeral0:
    table_type: mbr
    layout: True
    overwrite: False

fs_setup:
  - label: ephemeral0
    filesystem: ext4
    device: ephemeral0.1
    replace_fs: ntfs


# Data disks definitions for Microsoft Azure
# ------------------------------------------

disk_setup:
  /dev/disk/azure/scsi1/lun0:
    table_type: gpt
    layout: True
    overwrite: True

fs_setup:
  - device: /dev/disk/azure/scsi1/lun0
    partition: 1
    filesystem: ext4


# Default disk definitions for SmartOS
# ------------------------------------

device_aliases: {'ephemeral0': '/dev/vdb'}
disk_setup:
  ephemeral0:
    table_type: mbr
    layout: False
    overwrite: False

fs_setup:
  - label: ephemeral0
    filesystem: ext4
    device: ephemeral0.0

# Caveat for SmartOS: if ephemeral disk is not defined, then the disk will
#    not be automatically added to the mounts.


# The default definition is used to make sure that the ephemeral storage is
# setup properly.

# "disk_setup": disk partitioning
# --------------------------------

# The disk_setup directive instructs Cloud-init to partition a disk. The format is:

disk_setup:
  ephemeral0:
    table_type: 'mbr'
    layout: true
  /dev/xvdh:
    table_type: 'mbr'
    layout:
      - 33
      - [33, 82]
      - 33
    overwrite: True

# The format is a list of dicts of dicts. The first value is the name of the
# device and the subsequent values define how to create and layout the
# partition.
# The general format is:
#   disk_setup:
#     <DEVICE>:
#       table_type: 'mbr'
#       layout: <LAYOUT|BOOL>
#       overwrite: <BOOL>
#
# Where:
#   <DEVICE>: The name of the device. 'ephemeralX' and 'swap' are special
#               values which are specific to the cloud. For these devices
#               Cloud-init will look up what the real devices is and then
#               use it.
#
#               For other devices, the kernel device name is used. At this
#               time only simply kernel devices are supported, meaning
#               that device mapper and other targets may not work.
#
#               Note: At this time, there is no handling or setup of
#               device mapper targets.
#
#   table_type=<TYPE>: Currently the following are supported:
#                   'mbr': default and setups a MS-DOS partition table
#                   'gpt': setups a GPT partition table
#
#               Note: At this time only 'mbr' and 'gpt' partition tables
#                   are allowed. It is anticipated in the future that
#                   we'll also have "RAID" to create a mdadm RAID.
#
#   layout={...}: The device layout. This is a list of values, with the
#               percentage of disk that partition will take.
#               Valid options are:
#                   [<SIZE>, [<SIZE>, <PART_TYPE]]
#
#               Where <SIZE> is the _percentage_ of the disk to use, while
#               <PART_TYPE> is the numerical value of the partition type.
#
#               The following setups two partitions, with the first
#               partition having a swap label, taking 1/3 of the disk space
#               and the remainder being used as the second partition.
#                 /dev/xvdh':
#                   table_type: 'mbr'
#                   layout:
#                     - [33,82]
#                     - 66
#                   overwrite: True
#
#               When layout is "true" it means single partition the entire
#               device.
#
#               When layout is "false" it means don't partition or ignore
#               existing partitioning.
#
#               If layout is set to "true" and overwrite is set to "false",
#               it will skip partitioning the device without a failure.
#
#   overwrite=<BOOL>: This describes whether to ride with saftey's on and
#               everything holstered.
#
#               'false' is the default, which means that:
#                   1. The device will be checked for a partition table
#                   2. The device will be checked for a file system
#                   3. If either a partition of file system is found, then
#                       the operation will be _skipped_.
#
#               'true' is cowboy mode. There are no checks and things are
#                   done blindly. USE with caution, you can do things you
#                   really, really don't want to do.
#
#
# fs_setup: Setup the file system
# -------------------------------
#
# fs_setup describes the how the file systems are supposed to look.

fs_setup:
  - label: ephemeral0
    filesystem: 'ext3'
    device: 'ephemeral0'
    partition: 'auto'
  - label: mylabl2
    filesystem: 'ext4'
    device: '/dev/xvda1'
  - cmd: mkfs -t %(filesystem)s -L %(label)s %(device)s
    label: mylabl3
    filesystem: 'btrfs'
    device: '/dev/xvdh'

# The general format is:
#   fs_setup:
#     - label: <LABEL>
#       filesystem: <FS_TYPE>
#       device: <DEVICE>
#       partition: <PART_VALUE>
#       overwrite: <OVERWRITE>
#       replace_fs: <FS_TYPE>
#
# Where:
#   <LABEL>: The file system label to be used. If set to None, no label is
#     used.
#
#   <FS_TYPE>: The file system type. It is assumed that the there
#     will be a "mkfs.<FS_TYPE>" that behaves likes "mkfs". On a standard
#     Ubuntu Cloud Image, this means that you have the option of ext{2,3,4},
#     and vfat by default.
#
#   <DEVICE>: The device name. Special names of 'ephemeralX' or 'swap'
#     are allowed and the actual device is acquired from the cloud datasource.
#     When using 'ephemeralX' (i.e. ephemeral0), make sure to leave the
#     label as 'ephemeralX' otherwise there may be issues with the mounting
#     of the ephemeral storage layer.
#
#     If you define the device as 'ephemeralX.Y' then Y will be interpetted
#     as a partition value. However, ephermalX.0 is the _same_ as ephemeralX.
#
#   <PART_VALUE>:
#     Partition definitions are overwritten if you use the '<DEVICE>.Y' notation.
#
#     The valid options are:
#     "auto|any": tell cloud-init not to care whether there is a partition
#       or not. Auto will use the first partition that does not contain a
#       file system already. In the absence of a partition table, it will
#       put it directly on the disk.
#
#       "auto": If a file system that matches the specification in terms of
#       label, type and device, then cloud-init will skip the creation of
#       the file system.
#
#       "any": If a file system that matches the file system type and device,
#       then cloud-init will skip the creation of the file system.
#
#       Devices are selected based on first-detected, starting with partitions
#       and then the raw disk. Consider the following:
#           NAME     FSTYPE LABEL
#           xvdb
#           |-xvdb1  ext4
#           |-xvdb2
#           |-xvdb3  btrfs  test
#           \-xvdb4  ext4   test
#
#         If you ask for 'auto', label of 'test, and file system of 'ext4'
#         then cloud-init will select the 2nd partition, even though there
#         is a partition match at the 4th partition.
#
#         If you ask for 'any' and a label of 'test', then cloud-init will
#         select the 1st partition.
#
#         If you ask for 'auto' and don't define label, then cloud-init will
#         select the 1st partition.
#
#         In general, if you have a specific partition configuration in mind,
#         you should define either the device or the partition number. 'auto'
#         and 'any' are specifically intended for formatting ephemeral storage or
#         for simple schemes.
#
#       "none": Put the file system directly on the device.
#
#       <NUM>: where NUM is the actual partition number.
#
#   <OVERWRITE>: Defines whether or not to overwrite any existing
#     filesystem.
#
#     "true": Indiscriminately destroy any pre-existing file system. Use at
#         your own peril.
#
#     "false": If an existing file system exists, skip the creation.
#
#   <REPLACE_FS>: This is a special directive, used for Microsoft Azure that
#     instructs cloud-init to replace a file system of <FS_TYPE>. NOTE:
#     unless you define a label, this requires the use of the 'any' partition
#     directive.
#
# Behavior Caveat: The default behavior is to _check_ if the file system exists.
#   If a file system matches the specification, then the operation is a no-op.

В этой заметке мы рассмотрим некоторые базовые приёмы работы с oVirt 4.0 в конфигурации Hosted Engine, то есть основные действия, которые может потребоваться выполнить администратору после развёртывания oVirt. Чтобы начать работу с oVirt, нужно хотя бы на базовом уровне понимать значение компонент инфраструктуры этого продукта. Довольно простым и доступным языком описал основные компоненты oVirt Александр Руденко в своём блоге: oVirt часть 4. Настройка инфраструктуры. Рекомендую к предварительному прочтению.

Инициализация Data Center

После того, как мы начнём ознакомление с веб-консолью портала администрирования oVirt на свежей инсталляции, мы можем обнаружить, что в консоли не отображается информация о присутствии виртуальной машины с oVirt Hosted Engine, а также о дисковом разделе из FC SAN на СХД, на который была установлена эта виртуальная машина. Как я понял, причина заключается в том, что наш Data Center (верхний уровень иерархии oVirt) не проинициализирован. Для того, чтобы выполнить его инициализацию, можно воспользоваться функцией подсказки Guide Me на панели кнопок вкладки Data Centers или в контекстном меню нашего дата-центра по умолчанию Default, который был автоматически создан в процессе развёртывания oVirt.

image_thumb15

Инициализация Дата-Центра невозможна без предоставления в распоряжение oVirt дискового хранилища, на котором будут располагаться создаваемые виртуальные машины. Поэтому, в первую очередь, в открывшемся окне выбираем пункт Configure Storage

image_thumb16[1]

Откроется форма добавления хранилища к oVirt. Так как мы намереваемся подключить дисковое хранилище для размещения виртуальных машин, выберем в поле Domain Function значение Data. Тип хранилища Storage Type выбираем тот, который у нас планируется использовать (в нашем случае это Fibre Channel). В поле Use Host выбираем хост, с которого будет произведена проверка доступа к хранилищу и зададим понятное нам имя хранилища в поле Name. Поле Description по моим наблюдениям в oVirt 4.0.1 при добавлении FC Data Domain не сохраняется, возможно этот недочёт исправят в будущих версиях. После выбора хоста в табличной части формы появится список доступных на этом хосте LUN-ов. Малый LUN размером 90GB в нашем случае уже используется под виртуальную машину Hosted Engine, поэтому здесь мы выбираем второй свободный LUN размером 2000GB.

image_thumb17[1]

Через несколько секунд после того, как я добавил в oVirt новый чистый FC LUN для хранения виртуальных машин, в веб-консоли появилась информация и о LUN-e под виртуальную машину oVirt Engine, а статус Дата-Центра изменился на Up

image_thumb18

Кстати, присваиваемое по умолчанию имя Data Domain «hosted_storage» можно при желании переименовать (в System > Data Centers > Default > Storage – выбрать имя нужного Data Domain и нажать Manage Domain)

image_thumb19

После инициализации Дата-Центра в веб-консоли должна появиться информация и о работающей виртуальной машине Hosted Engine.

Подключение ISO Domain

После первичной инициализации Дата-Центра и Кластера указанное в процессе развёртывания oVirt Engine хранилище NFS, предназначенное для хранения ISO-образов (ISO Domain), в веб-консоли может быть не видно. Если так, то в первую очередь на ВМ Engine стоит проверить содержимое файла /etc/exports.d/ovirt-engine-iso-domain.exports. При необходимости можно подправить этот файл, например так:

# cat /etc/exports.d/ovirt-engine-iso-domain.exports

# /var/nfs-ovirt-iso-share/files  10.1.0.0/24(rw,sync,no_root_squash,no_subtree_check)
/var/nfs-ovirt-iso-share/files KOM-AD01-VM3*.holding.com(rw,sync,no_subtree_check,all_squash,anonuid=36,anongid=36)

После правки файла экспорта, заставим NFS сервер перечитать новые параметры:

# exportfs -rv

После этого проверим, какие шары может отдавать NFS-сервер:

# exportfs

/var/nfs-ovirt-iso-share/files
                KOM-AD01-VM3*.holding.com

Будем считать, что наш NFS сервер настроен так как надо, и теперь можно попробовать присоединить ISO Domain в oVirt. Для этого в веб-консоли переходим к System > Data Centers > Default > на закладке Storage жмём кнопку Attach ISO

image_thumb29

В открывшейся форме выбираем ранее описанный ISO Domain

image_thumb30

После этого в веб-консоли нам станет доступно это хранилище для размещения ISO-образов.

image_thumb31[1]

Опять же, при необходимости можно переименовать только что присоединённый ISO Domain. Сделать это можно в System > Data Centers > Default > Storage  — выбрать нужный ISO Domain и нажать Manage Domain. Для большей наглядности я переименую заданное в процессе развёртывания oVirt имя ISO_DOMAIN, например, в NFS-HEngine-ISO:

image_thumb32

Загрузка ISO образов в ISO Domain

Возможности прямой загрузки ISO образов в ISO Domain через веб-интерфейс oVirt нет. Загрузить ISO образы можно непосредственно на виртуальном сервере Hosted Engine. Для примера я добавлю загрузочный инсталляционный образ Ubuntu Server 16.04 LTS. Как я понял, для этого действия предполагается иметь на локальной файловой системе сервера заранее скачанный ISO-образ и использовать утилиту ovirt-iso-uploader для его копирования в ISO Domain.

# wget http://releases.ubuntu.com/16.04/ubuntu-16.04.1-server-amd64.iso -P /tmp/
# ovirt-iso-uploader --iso-domain=NFS-HEngine-ISO upload /tmp/ubuntu-16.04.1-server-amd64.iso --force

Please provide the REST API password for the admin@internal oVirt Engine user (CTRL+D to abort):
Uploading, please wait...
INFO: Start uploading /tmp/ubuntu-16.04.1-server-amd64.iso
Uploading: [########################################] 100%
INFO: /tmp/ubuntu-16.04.1-server-amd64.iso uploaded successfully


# rm /tmp/ubuntu-16.04.1-server-amd64.iso

Хотя, в нашем случае, можно воспользоваться более простым вариантом добавления образов — загружая их из Интернета прямо в каталог, где ISO Domain хранит образы. Это каталог вида:
/var/nfs-ovirt-iso-share/files/<идентификатор>/images/11111111-1111-1111-1111-111111111111/

# wget http://mirror.yandex.ru/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1511.iso -P /var/nfs-ovirt-iso-share/files/b6773c29-5c80-4825-b345-9bf84ae48bdf/images/11111111-1111-1111-1111-111111111111/
# chmod 640 /var/nfs-ovirt-iso-share/files/b6773c29-5c80-4825-b345-9bf84ae48bdf/images/11111111-1111-1111-1111-111111111111/CentOS-7-x86_64-Minimal-1511.iso
# chown 36:36 /var/nfs-ovirt-iso-share/files/b6773c29-5c80-4825-b345-9bf84ae48bdf/images/11111111-1111-1111-1111-111111111111/CentOS-7-x86_64-Minimal-1511.iso

Обратите внимание на то, что после загрузки желательно выставить на файл разрешения по аналогии с тем, как их выставляет утилита ovirt-iso-uploader.

Теперь проверим состояние ISO Domain в веб-консоли oVirt (System > Data Centers > Default > Storage > выберем соответствующий ISO Domain и на закладке Images проверим доступность загруженных ранее ISO-образов)

image

Как видим, оба образа отображаются и могут быть использованы в дальнейшем для подключения к виртуальным машинам.

Настройка сетей

Создавать логические сети в oVirt имеет смысл в том случае, если, например, в вашей сети используется изоляция разнородного трафика с помощью VLAN. Например, если физические сетевые интерфейсы наших хостов виртуализации подключены к транковым портам коммутаторов, имеющих доступ к множеству VLAN-ов, то с помощью создания виртуальных сетей с определённым VLAN с последующей привязкой этих сетей к сетевым адаптерами виртуальных машин, мы сможем организовать необходимое разделение трафика. В следующем примере мы создадим логическую сеть с номером VLAN 1000. Перейдём в веб-консоли в System > Data Centers > Default > Networks. Здесь мы увидим список доступных сетей нашего Дата-Центра. В данный момент здесь присутствует только сеть ovirtmgmt, которая была автоматически создана в процессе развёртывания oVirt (к этой сети привязан vNIC виртуальной машины Hosted Engine). Чтобы создать новую сеть используем кнопку New

image

В открывшейся форме создания логической сети на вкладке General зададим понятное для нас имя с описанием, укажем номер VLAN-а и включим признак того, что эта сеть может использоваться для виртуальных машин – VM network

image

Так как создаваемые в oVirt логические сети — это объекты уровня Дата-Центра, а в Дата-Центре может быть не один Кластер, на вкладке Cluster мы можем при необходимости настроить привязку этих сетей к конкретным Кластерам. В данном случае мы не меняем предложенных по умолчанию настроек.

image

Профиль vNIC по умолчанию создаётся для сети с одноимённым названием и при желании можно изменить его имя.

image

Подробнее о том, для чего могут использоваться профили vNIC можно почитать здесь. Если кратко, то с помощью множества профилей vNIC в рамках одной логической сети можно реализовать разные возможности виртуальных сетевых адаптеров, например, выбрать различные политики QoS (сами политики QoS настраиваются на уровне Дата-Центра), настроить различные опции сетевой фильтрации, включить Port Mirroring и т.д. Полные настройки профилей доступны в System > Data Centers > Default > Networks на закладке vNIC Profiles при выборе той или иной логической сети.

image

После создания сети, для того чтобы виртуальные машины могли использовать подключение к этой сети, необходимо выполнить привязку этих сетей к физическим сетевым интерфейсам хостов. Перейдём в веб-консоли в System > Data Centers > Default, выберем вкладку Hosts, выберем какой-нибудь хост, к которому хотим выполнить привязку сети, и в нижней части экрана перейдём на закладку Network Interfaces. Здесь мы увидим информацию о сетевых интерфейсах хоста. Нажмём кнопку Setup Host Networks.

image

Откроется форма привязки логических сетей к хосту. В этой форме справа будут перечислены все имеющиеся в oVirt, но не привязанные к хосту сети, а слева текущая сетевая конфигурация хоста. С помощью манипулятора, типа «мышь», перетаскиваем интересующую нас сеть на интерфейс хоста…

image

В нашем случае используется привязка ранее созданной сети с VLAN 1000 к интерфейсу bond0:

image

После этого на хосте будет создан интерфейс с соответствующим номером VLAN и в веб-консоли эта информация будет отображена соответственно:

image

Аналогичным образом нужно выполнить привязку созданной нами логической сети ко всем хостам, где могут оказаться, например в процессе миграции, виртуальные машины, привязанные к данной сети.

Создание новой виртуальной машины

Создадим новую виртуальную машину и установим на неё OC Ubuntu Server 16.04 LTS с ранее загруженного в ISO Domain установочного образа. Переходим в System > Data Centers > Default > закладка Virtual Machines > кнопка New VM.

image

В открывшейся веб-форме создания виртуальной машины сразу нажимаем кнопку Show Advanced Options, чтобы включить расширенный режим настроек. Назначение полей нетрудно понять из их названий. Задаём тип гостевой ОС ВМ, имя ВМ, так как оно будет отображаться в oVirt, описание. Для виртуального интерфейса nic1 выбираем ранее созданный vNIC Profile, который в свою очередь привязан в ранее созданной логической сети. Чтобы создать новый диск для виртуальной машины используем кнопку Create

image

Поверх формы создания виртуальной машины откроется форма создания нового виртуального диска, где мы укажем его размер, понятное имя с описанием, выберем хранилище для размещения файла диска (Storage Domain) и тип распределения данных (Allocation Policy). Не забудем включить опцию Bootable, так планируем устанавливать на этот диск ОС.

image

Таким образом, для примера, я создал первый диск (под гостевую ОС) и дополнительный (под данные приложений).

image

Переходим на вкладку System и настраиваем параметры оперативной памяти, процессора, часовой пояс:

image

На вкладке Console выбираем параметры подключения к консоли виртуальной машины. В данном случае нам доступны два основных графических протокола VNC и SPICE (к особенностям их использования мы вернёмся чуть позже), так как в свойствах ОС выбран тип Linux.

image

На вкладке Host при необходимости можно настроить привязку виртуальной машины к какому-то конкретному хосту в кластере, а также изменить параметры миграции ВМ между хостами.

image

На вкладке High Availability можно настроить приоритет перезапуска виртуальной машины в контексте выполнения операций по автоматическому восстановлению доступности виртуальных машин в кластере.

image

На вкладке Resource Allocation настраиваются дополнительные опции, которыми можно контролировать производительность той или иной виртуальной машины, путём определения порядка выделения физических ресурсов этой машине.

image

На вкладке Boot Options определяем порядок использования устройств для загрузки. Здесь мы можем присоединить к виртуальному CD-ROM ранее загруженный в ISO Domain установочный ISO-образ операционной системы Linux, которую мы планируем установить на диск ВМ.

image

Сохраняем настроенный свойства виртуальной машины и пробуем выполнить её запуск из консоли используя пункты меню или кнопки Run или Run Once.

image

Функция Run Once позволяет выполнять запуск виртуальной машины с изменением ряда её параметров, которые не сохраняются в конфигурации этой ВМ при следующем перезапуске, например, именно здесь можно указать единожды монтируемый ISO образ, который нужен для установки ОС и уже не потребуется при следующей перезагрузке ВМ.

image

Подключение к консоли виртуальных машин

После того, как виртуальная машина запущена, мы сможем подключиться к её консоли разными способами. Поддерживаемые варианты подключения к консоли виртуальной машины описаны в онлайн-документе Console Clients Resources. На данный момент поддерживаются 3 протокола SPICE, VNC и RDP. Протокол RDP можно использовать только для виртуальных машин с гостевой ОС Windows. Протокол VNC требует наличия VNC-клиента. Протокол SPICE может работать как через Native SPICE-клиент, так и как HTML5-апплет.

В качестве Native SPICE-клиента можно использовать, например, программу Virt-Viewer. Все доступные для загрузки версии можно найти здесь. Если установка Virt-Viewer планируется на Windows, то на данный момент здесь рекомендуют использовать версию 3 вместо 4-ой, так как в последней имеются какие-то проблемы. Скачиваем и устанавливаем Virt-Viewer, после чего в консоли oVirt, выбрав нужную нам виртуальную машину, нажимаем кнопку с зелёным монитором для подключения к консоли ВМ.

image

Будет скачан файл console.vv и запущен в ассоциированном приложении Virt-Viewer, после чего мы получим доступ к консоли ВМ:

image

При попадании курсора в консоль, управление курсором переходит в виртуальную машину. Для возврата курсора обратно используем сочетание клавиш Shift+F12.

Помимо Native SPICE-клиента можно использовать возможности HTML5 SPICE-клиент, то есть консоль виртуальной машины при этом будет открываться непосредственно в интернет-браузере. Тесты показали, что в Internet Explorer v11 HTML5 SPICE-клиент не работает. В Firefox и Chrome работает, но не всегда стабильно и при условии, что SSL сертификат, используемый в веб-консоли oVirt является доверенным (этого можно добиться либо добавив само-подписанный сертификат oVirt в хранилище доверенных сертификатов пользователя в системе, либо заменить сертификат на веб-сайте oVirt, так как мы сделали это ранее). Однако не смотря на то, что даже если требование доверия браузера сертификату соблюдено мы можем получить ошибку типа:

WebSocket error: Can’t connect to websocket on URL: wss://kom-ad01-ovirt1.holding.com:6100

image

В прошлой заметке (в последнем абзаце) был описан способ решения этой проблемы, подсказанный в мейл-группе oVirt. Напомню, что смысл его в том, чтобы откорректировать конфигурационный файл /etc/ovirt-engine/ovirt-websocket-proxy.conf.d/10-setup.conf, изменив в нём значение переменных SSL_CERTIFICATE и SSL_KEY.

Для более комфортной работы при подключении по протоколу SPICE, в гостевую ОС виртуальной машины можно дополнительно установить такие  компоненты , как агент SPICE vdagent и видео драйвер SPICE QXL. Загрузить их можно по ссылке SPICE Download (секция «Guest«). В некоторых дистрибутивах GNU/Linux видеодрайвер SPICE QXL уже входит в базовый сосав ОС.

Установка компонент интеграции в виртуальные машины

Основную информацию о гостевых агентах oVirt можно найти в документе Understanding Guest Agents and Other Tools. В этом же документе можно найти таблицу совместимости компонент интеграции с разными типами гостевых систем Linux и Windows.

Компоненты интеграции гостевых ОС в среду виртуализации oVirt состоят из дополнительно устанавливаемых в гостевую ОС агентов oVirt Guest Agent, SPICE Agent и драйверов VirtIO Drivers.

oVirt Guest Agent

Информация о том, какие преимущества даёт установка oVirt Guest Agent доступна в документе Guest Agent. Примеры установки гостевого агента на разные дистрибутивы Linux есть в серии How to install the guest agent in .… Например, в нашей виртуальной машине с гостевой ОС Ubuntu 16.04 LTS агент установился из официальных репозиториев, однако после его установки потребовалась корректировка прав на каталог для логов службы ovirt-guest-agent, иначе служба отказывалась стартовать:

$ sudo apt-get install ovirt-guest-agent
$ sudo chown ovirtagent:ovirtagent -R /var/log/ovirt-guest-agent
$ sudo systemctl enable ovirt-guest-agent
$ sudo reboot
$ sudo service ovirt-guest-agent status

image

После того, как служба агента запущена в виртуальной машине, в веб-консоли oVirt нам станут доступны дополнительные сведения о текущем состоянии гостевой ОС. В частности, на закладке General появится информация о текущем состоянии утилизации оперативной памяти внутри ВМ.

image

Так же появится дополнительная информация на закладках Applications, Guest Info и других

image

На другую нашу виртуальную машину c Hosted Engine на базе CentOS 7.2 агент был установлен из ранее подключённого репозитория EPEL (yum install epel-release) следующей последовательностью команд:

# yum -y install ovirt-guest-agent
# systemctl enable ovirt-guest-agent
# systemctl start ovirt-guest-agent
# service ovirt-guest-agent status

По поводу установки агента в гостевые системы на базе ОС Windows мы останавливаться не будем, так как в нашем случае виртуализация oVirt разворачивается исключительно под Linux/Unix системы, а для для Windows систем есть более дружелюбная среда на базе гипервизора Hyper-V. Однако, для желающих эксплуатировать гостевые системы на базе Windows, в oVirt есть статья с примером установки гостевого агента в записи блога Open Source Community — How to Install oVirt’s Windows Guest Tools.

SPICE Agent

Простая инструкция по установке агента SPICE vdagent, расширяющего возможности работы с консолью гостевых ОС Linux есть в документе How to install the spice guest agent. На разных дистрибутивах Linux в общем случае процедура сводится к установке пакета spice-vdagent. Например на нашей виртуальной машине с Ubuntu 16.04 LTS это делается так:

$ sudo apt-get install spice-vdagent

После установки служба автоматически запускается и настраивается на автозагрузку при старте системы:

image

После установки агента SPICE vdagent я заметил улучшение удобства работы с консолью ВМ в Virt-Viewer, в частности перестало дёргать курсор мыши и само перемещение курсора мыши между моей клиентской системой и окном консоли Virt-Viewer теперь стало работать прозрачно, без потери управления при попадании в окно консоли (Shift+F12 теперь стал не нужен для возврата управления курсором). А то, как работает функция общего буфера обмена, я так и не постиг.

На гостевых системах RHEL/CentOS/Fedora установка агента SPICE выполняется также просто:

$ sudo yum install spice-vdagent
VirtIO Drivers

Согласно вышеупомянутого документа драйверы VirtIO Drivers уже входят в состав всех гостевых ОС Linux, а для Windows систем потребуется их отдельная установка (можно воспользоваться руководствами How to create a Windows … Virtual Machine).

Проверка живой миграции

Так как у нас в кластере уже есть 2 хоста, мы можем попробовать вызвать процедуру живой миграции виртуальной машины между хостами. Для примера выполним процедуру живой миграции виртуальной машины Hosted Engine. Для проверки постоянной доступности виртуальной машины в процессе живой миграции перед запуском процедуры миграции запустим ping до виртуального сервера Engine, затем в веб-консоли oVirt выберем эту виртуальную машину и нажмём кнопку Migrate

image_thumb22

Откроется окно, где мы можем выбрать хост, на который нужно мигрировать виртуальную машину. В нашем примере используется автоматическое определение хоста назначения

image_thumb23

После нажатия ОК в консоли увидим изменение статуса виртуальной машины…

image_thumb25

А спустя несколько секунд виртуальная машина уже будет работать на другом хосте, при этом  доступной виртуальной машины останется на прежнем уровне. Проверяем статистику ping и видим, что потерь соединения с нашей виртуальной машиной в процессе миграции не было. И это хорошо.

image_thumb26

В ранних версиях oVirt миграция виртуальной машины Hosted Engine подразумевала предварительное включение Global HA Maintenance, но современная версия oVirt 4.0, как следует, в частности, из документа How to perform live migration of Hosted Engine VM уже этого не требует.

На этом пока всё. В следующей части мы рассмотрим механизмы Fencing в oVirt, как средство достижения High Availability.

Дополнительные источники информации:

  • Александр Руденко — iVirt-it.ru – oVirt
  • Almas AkeHayc — Установка и настройка oVirt 3.6 на CentOS 7 x64

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Tweaking com windows repair aio setup
  • Какая разрядность лучше 32 или 64 для windows 10
  • Требовать неповторяемости паролей windows 10
  • Как проверить наличие видеокарты на компьютере windows 7
  • Как в grub прописать windows 10