What is linux kvm

🔯 Что такое KVM (виртуальная машина на основе ядра) в Linux?

Виртуализация является горячей темой в области вычислительной техники.

Существует другой тип решений и методов виртуализации, используемых в другой среде и операционных системах.

KVM или виртуальная машина на основе ядра – это технология виртуализации, используемая в ядре и дистрибутивах Linux.

Linux KVM может использоваться только в ядре и дистрибутиве Linux из-за его архитектуры проектирования.

Аппаратная поддержка KVM

Технология KVM может использоваться только с аппаратной поддержкой, предоставляемой процессором.

Процессоры Intel и AMD предоставляют эту аппаратную поддержку.

Как работает KVM?

KVM – это модуль ядра Linux, и для работы с KVM модуль должен быть установлен и загружен в ядро Linux.

Модуль обычно называется kvm, но для процессоров Intel он называется kvm_intel, а для процессоров AMD – kvm_amd.

Ядро Linux будет изолировать созданную виртуальную машину памяти и процессора в процесс, как отдельную систему.

Особенности KVM

Виртуализация KVM предоставляет следующие функции в процессе виртуализации.

  • Безопасность: KVM использует комбинацию SELinux и sVirt для защиты и изоляции виртуальных машин.
  • Хранение: KVM может использовать локальные или связанные с NAS технологии хранения с различными файловыми системами. На диске ВМ хранится один или несколько файлов со снимками, резервными копиями.
  • Аппаратное обеспечение: KVM может использовать самые разные аппаратные средства, поддерживаемые Linux, такие как USB, принтер, PCI-устройства и т. Д.
  • Память: KVM наследует функции управления памятью в Linux, включая неравномерный доступ к памяти и слияние страниц на одном ядре.
  • Живая миграция: KVM поддерживает живую миграцию с одного хоста виртуализации на другой хост без прерывания обслуживания.

Модули ядра KVM

Как указывалось ранее, Linux KVM можно использовать с модулями ядра с именем kvm.

Мы установим модуль ядра Linux KVM с помощью следующей команды, если он не установлен.

Проверьте установку KVM

Мы можем проверить установку KVM с помощью команды kvm-ok, которая предоставит информацию и поддержку оборудования, как показано ниже.

Из скриншота видно, что /dev/kvm существует и KVM acceleration можно использовать без проблем.

KVM Qemu

KVM – это часть ядра виртуализации Linux.

В пользовательском пространстве используется инструмент с именем Qemu.

Qemu обеспечивает эмуляцию устройств VM и связь с ядром.

Qemu запускается как эмулятор виртуальной машины и объединяется с KVM для обеспечения полной виртуализации.

Мы можем установить KVM Qemu с помощью следующей команды.

Инструмент KVM Libvirt

Libvirt – это библиотека, используемая для виртуализации KVM в более корпоративной манере.

Libvirt предоставляет сервисы для подключения, управления сервисами виртуализации и создания, удаления, запуска и остановки виртуальных машин.

Мы можем установить libvirt с именем пакета libvirt-daemon, который является сервисом.

Инструменты KVM GUI

Виртуальными машинами KVM можно управлять с помощью различных инструментов графического интерфейса.

Но virt-manager – это популярные инструменты, которые можно использовать локально в системе. Мы можем установить Virt Manager как показано ниже.

Источник

Общие принципы работы QEMU-KVM

Мое текущее понимание:

1) KVM

KVM (Kernel-based Virtual Machine) – гипервизор (VMM – Virtual Machine Manager), работающий в виде модуля на ОС Linux. Гипервизор нужен для того, чтобы запускать некий софт в несуществующей (виртуальной) среде и при этом, скрывать от этого софта реальное физическое железо, на котором этот софт работает. Гипервизор работает в роли «прокладки» между физическим железом (хостом) и виртуальной ОС (гостем).

Поскольку KVM является стандартным модулем ядра Linux, он получает от ядра все положенные ништяки (работа с памятью, планировщик и пр.). А соответственно, в конечном итоге, все эти преимущества достаются и гостям (т.к. гости работают на гипервизоре, которые работает на/в ядре ОС Linux).

KVM очень быстрый, но его самого по себе недостаточно для запуска виртуальной ОС, т.к. для этого нужна эмуляция I/O. Для I/O (процессор, диски, сеть, видео, PCI, USB, серийные порты и т.д.) KVM использует QEMU.

2) QEMU

QEMU (Quick Emulator) – эмулятор различных устройств, который позволяет запускать операционные системы, предназначенные под одну архитектуру, на другой (например, ARM –> x86). Кроме процессора, QEMU эмулирует различные периферийные устройства: сетевые карты, HDD, видео карты, PCI, USB и пр.

Читайте также:  Амиго браузер для mac os

Работает это так:

Инструкции/бинарный код (например, ARM) конвертируются в промежуточный платформонезависимый код при помощи конвертера TCG (Tiny Code Generator) и затем этот платформонезависимый бинарный код конвертируется уже в целевые инструкции/код (например, x86).

ARM –> промежуточный_код –> x86

По сути, вы можете запускать виртуальные машины на QEMU на любом хосте, даже со старыми моделями процессоров, не поддерживающими Intel VT-x (Intel Virtualization Technology) / AMD SVM (AMD Secure Virtual Machine). Однако в таком случае, это будет работать весьма медленно, в связи с тем, что исполняемый бинарный код нужно перекомпилировать на лету два раза, при помощи TCG (TCG – это Just-in-Time compiler).

Т.е. сам по себе QEMU мега крутой, но работает очень медленно.

3) Protection rings

Бинарный программный код на процессорах работает не просто так, а располагается на разных уровнях (кольцах / Protection rings) с разными уровнями доступа к данным, от самого привилегированного (Ring 0), до самого ограниченного, зарегулированного и «с закрученными гайками» (Ring 3).

Операционная система (ядро ОС) работает на Ring 0 (kernel mode) и может делать с любыми данными и устройствами все, что угодно. Пользовательские приложения работают на уровне Ring 3 (user mode) и не в праве делать все, что захотят, а вместо этого каждый раз должны запрашивать доступ на проведение той или иной операции (таким образом, пользовательские приложения имеют доступ только к собственным данным и не могут «влезть» в «чужую песочницу»). Ring 1 и 2 предназначены для использования драйверами.

До изобретения Intel VT-x / AMD SVM, гипервизоры работали на Ring 0, а гости работали на Ring 1. Поскольку у Ring 1 недостаточно прав для нормального функционирования ОС, то при каждом привилегированном вызове от гостевой системы, гипервизору приходилось на лету модифицировать этот вызов и выполнять его на Ring 0 (примерно так, как это делает QEMU). Т.е. гостевой бинарный код НЕ выполнялся напрямую на процессоре, а каждый раз на лету проходил несколько промежуточных модификаций.

Накладные расходы были существенными и это было большой проблемой и тогда производители процессоров, независимо друг от друга, выпустили расширенный набор инструкций (Intel VT-x / AMD SVM), позволяющих выполнять код гостевых ОС НАПРЯМУЮ на процессоре хоста (минуя всякие затратные промежуточные этапы, как это было раньше).

С появлением Intel VT-x / AMD SVM, был создан специальный новый уровень Ring -1 (минус один). И теперь на нем работает гипервизор, а гости работают на Ring 0 и получают привилегированный доступ к CPU.

  • хост работает на Ring 0
  • гости работают на Ring 0
  • гипервизор работает на Ring -1

4) QEMU-KVM

KVM предоставляет доступ гостям к Ring 0 и использует QEMU для эмуляции I/O (процессор, диски, сеть, видео, PCI, USB, серийные порты и т.д., которые «видят» и с которыми работают гости).

Отсюда QEMU-KVM (или KVM-QEMU) 🙂

P.S. Текст этой статьи изначально был опубликован в Telegram канале @RU_Voip в качестве ответа на вопрос одного из участников канала.

Напишите в комментариях, в каких местах я не правильно понимаю тему или если есть, что дополнить.

Источник

What is KVM virtualization in Linux?

Posted by Surendra Anne | Feb 1, 2013 | KVM | 8 |

In this post we will see what is KVM virtualization and it’s terminology. I included terminology as virtualization concept is still picking up by Linux users and new system administrators in this post. This will help in understanding different terms used. Below are some posts on the virtualization concepts and advantages we covered so far.

What is KVM virtualization?

KVM(Kernel Virtual machine) is an inbuilt virtualization software available in Linux(Have to select it when installing OS Or can be installed when ever it’s required). Up to recent years virtualization software are installed as stand alone software in Linux. But to make things more reliable, fast and virtualization is becoming a part of Kernel activities, this software is bundled along Linux OS which can be installed as a part of Kernel. There are many advantages of this KVM when compared to other virtualization software’s available in Linux.

  • Can interact directly with the Kernel
  • Default virtualization in leading Linux Distributions
  • One of the Linux software developed aggressively.
  • Almost becoming competitor to VMware by implementing technologies such as v2v, p2v, and many open source tools to manage VM’s
  • Number of open source cloud automation software’s use KVM as default hyperviser.

How KVM virtualization works?

Once we install KVM on a Linux box a hardware file /dev/kvm is created which will act as interpreter between actual hardware and hypervisor manager(Virt-manager). When ever a request for hardware changes/additions comes from hypervisor manager, your KVM software starts allocating those resources virtually by interacting with real hardware. Suppose we want to change RAM on a virtual machine, this is communicated by your hypervisor manager to KVM for allocating the resource. Then KVM interacts with hardware and reserves that RAM from real RAM for that particular VM. This happens for the other resources as well. To make it simple I did not explain the concept of ballooning and another things.

Читайте также:  Полное удаление всех драйверов windows 10

Kvm virtualization architecture in Linux

(KVM)Virtualization terminology

VT(Virtualization Technology) enabled: If a hardware supports virtualization directly without any third-party software to simulate then that hardware is called as VT enabled processor. This is denoted by VTx in Intel processors and AMD-v For AMD processors. So if you want to install KVM on your machine your processor should support one of them.

Guest OS: Guest OS is the OS you are going to install on a Virtual machine which guest to the Host/base OS. You can install number of guest Operating systems on a host machine.

HOST OS: This is the OS where you are going to install your hypervisor software like KVM and virtual manager etc. This base OS so that you hypervisor start running as KVM is not an OS it should run on a OS to get things done.

Hyperviser: Hyperviser is a software which will help us in implementing virtualization. KVM, Vmware ESX and Xen are some examples of Hypervisors.

Virtual machine: Virtual machine is a virtual hardware allocated by Hypervisor for installing Guest OS on it so that it can run as separate machine.

libvirt: A toolkit to interact with the virtualization capabilities of recent versions of Linux (and other OSes). This is a building block to KVM.

virsh(Virtualization Shell): Virsh is a shell for managing hypervisors and VM’s directly from Host OS terminal. We cover this virsh extensively in our coming posts.

Cloning: Cloning is a concept to replicate a VM state/data etc so that we no need to install a new OS. After cloning we can use the cloned machine as we use normal VM.

p2v: This type of converting a machine from one state to other. In this we can convert a physical machine to virtual machine to consolidate a hardware machine.

v2v: This is the concept of migrating virtual machine to other virtual machine at the time of maintenance etc.

Hyper-threading(HT): This is Intel’s proprietary simultaneous multithreading (SMT) implementation used to improve parallelization of computations (doing multiple tasks at once) performed on PC microprocessors.

Overcommit: This is concept of committing resource more than available at HOST OS resources such as RAM, CPU and harddisk. We should be very much cautious when dealing with over commit.

Do you have other terminology which is not discussed here please do let us know by using comments section so that we will include them here.

Источник

What is KVM?

Overview

Kernel-based Virtual Machine (KVM) is an open source virtualization technology built into Linux®. Specifically, KVM lets you turn Linux into a hypervisor that allows a host machine to run multiple, isolated virtual environments called guests or virtual machines (VMs).

KVM is part of Linux. If you’ve got Linux 2.6.20 or newer, you’ve got KVM. KVM was first announced in 2006 and merged into the mainline Linux kernel version a year later. Because KVM is part of existing Linux code, it immediately benefits from every new Linux feature, fix, and advancement without additional engineering.

How does KVM work?

KVM converts Linux into a type-1 (bare-metal) hypervisor. All hypervisors need some operating system-level components—such as a memory manager, process scheduler, input/output (I/O) stack, device drivers, security manager, a network stack, and more—to run VMs. KVM has all these components because it’s part of the Linux kernel. Every VM is implemented as a regular Linux process, scheduled by the standard Linux scheduler, with dedicated virtual hardware like a network card, graphics adapter, CPU(s), memory, and disks.

Implementing KVM

Long story short, you have to run a version of Linux that was released after 2007 and it needs to be installed on X86 hardware that supports virtualization capabilities. If both of those boxes are checked, then all you have to do is load 2 existing modules (a host kernel module and a processor-specific module), an emulator, and any drivers that will help you run additional systems.

Читайте также:  Astra linux postgresql contrib

But implementing KVM on a supported Linux distribution—like Red Hat Enterprise Linux—expands KVM’s capabilities, letting you swap resources among guests, share common libraries, optimize system performance, and a lot more.

Migrating to a KVM-based virtual infrastructure

Building a virtual infrastructure on a platform you’re contractually tied to may limit your access to the source code. That means your IT developments are probably going to be more workarounds than innovations, and the next contract could keep you from investing in clouds, containers, and automation. Migrating to a KVM-based virtualization platform means being able to inspect, modify, and enhance the source code behind your hypervisor. And there’s no enterprise-license agreement because there’s no source code to protect. It’s yours.

KVM features

KVM is part of Linux. Linux is part of KVM. Everything Linux has, KVM has too. But there are specific features that make KVM an enterprise’s preferred hypervisor.

Security

KVM uses a combination of security-enhanced Linux (SELinux) and secure virtualization (sVirt) for enhanced VM security and isolation. SELinux establishes security boundaries around VMs. sVirt extends SELinux’s capabilities, allowing Mandatory Access Control (MAC) security to be applied to guest VMs and preventing manual labeling errors.

Storage

KVM is able to use any storage supported by Linux, including some local disks and network-attached storage (NAS). Multipath I/O may be used to improve storage and provide redundancy. KVM also supports shared file systems so VM images may be shared by multiple hosts. Disk images support thin provisioning, allocating storage on demand rather than all up front.

Hardware support

KVM can use a wide variety of certified Linux-supported hardware platforms. Because hardware vendors regularly contribute to kernel development, the latest hardware features are often rapidly adopted in the Linux kernel.

Memory management

KVM inherits the memory management features of Linux, including non-uniform memory access and kernel same-page merging. The memory of a VM can be swapped, backed by large volumes for better performance, and shared or backed by a disk file.

Live migration

KVM supports live migration, which is the ability to move a running VM between physical hosts with no service interruption. The VM remains powered on, network connections remain active, and applications continue to run while the VM is relocated. KVM also saves a VM’s current state so it can be stored and resumed later.

Performance and scalability

KVM inherits the performance of Linux, scaling to match demand load if the number of guest machines and requests increases. KVM allows the most demanding application workloads to be virtualized and is the basis for many enterprise virtualization setups, such as datacenters and private clouds (via OpenStack®).

Scheduling and resource control

In the KVM model, a VM is a Linux process, scheduled and managed by the kernel. The Linux scheduler allows fine-grained control of the resources allocated to a Linux process and guarantees a quality of service for a particular process. In KVM, this includes the completely fair scheduler, control groups, network name spaces, and real-time extensions.

Lower latency and higher prioritization

The Linux kernel features real-time extensions that allow VM-based apps to run at lower latency with better prioritization (compared to bare metal). The kernel also divides processes that require long computing times into smaller components, which are then scheduled and processed accordingly.

Managing KVM

It’s possible to manually manage a handful of VM fired up on a single workstation without a management tool. Large enterprises use virtualization management software that interfaces with virtual environments and the underlying physical hardware to simplify resource administration, enhance data analyses, and streamline operations. Red Hat created Red Hat Virtualization for exactly this purpose.

KVM and Red Hat

We believe in KVM so much that it’s the sole hypervisor for all of our virtualization products, and we’re continually improving the kernel code with contributions to the KVM community. But since KVM is part of Linux, it’s already included in Red Hat Enterprise Linux—so why would you want Red Hat Virtualization?

Well, Red Hat has 2 versions of KVM. The KVM that ships with Red Hat Enterprise Linux has all of the hypervisor functionality with basic management capabilities, allowing customers to run unlimited isolated virtual machines on a single host. Red Hat Virtualization contains an advanced version of KVM that enables enterprise management of unlimited guest machines. It’s ideal for use in datacenter virtualization, technical workstations, private clouds, and in development or production.

Источник

Оцените статью