proxmox lvm thin что это
Proxmox lvm thin что это
storage pool type: lvm
LVM is a thin software layer on top of hard disks and partitions. It can be used to split available disk space into smaller logical volumes. LVM is widely used on Linux and makes managing hard drives easier.
Another use case is to put LVM on top of a big iSCSI LUN. That way you can easily manage space on that iSCSI LUN, which would not be possible otherwise, because the iSCSI specification does not define a management interface for space allocation
Configuration
The LVM backend supports the common storage properties content, nodes, disable, and the following LVM specific properties:
Configuration Example (/etc/pve/storage.cfg)
General LVM advantages
LVM is a typical block storage, but this backend does not support snapshot and clones. Unfortunately, normal LVM snapshots are quite inefficient, because they interfere all writes on the whole volume group during snapshot time.
One big advantage is that you can use it on top of a shared storage, for example an iSCSI LUN. The backend itself implement proper cluster wide locking.
Note: The newer LVM-thin backend allows snapshot and clones, but does not support shared storage. |
Standard installation
On a default installation Proxmox VE will use lvm. The layout looks like followed.
VG | LV | Mountpoint | Note |
---|---|---|---|
pve | swap | will used as swap partition | |
pve | root | / | Example |
pve | data | /var/lib/vz/ | Proxmox VE = 4.2 |
In Proxmox VE 4.2 we changed the LV data to a thin pool, to provide snapshots and native performance of the disk. The /var/lib/vz is now included in the LV root.
LVM-Thin
storage pool type: lvmthin
LVM normally allocates blocks when you create a volume. LVM thin pools instead allocates blocks when they are written. This behavior is called thin-provisioning, because volumes can be much larger than physically available space.
You can use the normal LVM command line tools to manage and create LVM thin pools (see man lvmthin for details). Assuming you already have a LVM volume group called pve, the following commands create a new LVM thin pool (size 100G) called data:
Under certain circumstances, LVM does not correctly calculate the metadatapool/chunk size. Please check if the metadatapool is big enough. The formula which has to be satisfied is:
PoolSize/ChunkSize * 64b = MetadataPoolSize
you can get this information via
Configuration
The LVM thin backend supports the common storage properties content, nodes, disable, and the following LVM specific properties:
Configuration Example (/etc/pve/storage.cfg)
General LVM-Thin advantages
LVM thin is a block storage, but fully supports snapshots and clones efficiently. New volumes are automatically initialized with zero.
It must be mentioned that LVM thin pools cannot be shared across multiple nodes, so you can only use them as local storage.
Create a extra LV for /var/lib/vz
This can be easily done by create a new thin LV. It is thin provisioned.
A real world example it looks like
Now a filesystem must be create on the LV.
And at last step this have to be mounted.
Note: Be sure that /var/lib/vz is empty. On a default installation it isn’t. |
Resize metadata pool
Note: If the pool will extend, then it is be necessary to extent also the metadata pool. |
It can be achieved with the following command.
LVM vs LVM-Thin
Type | Content types | Image formats | Shared | Snapshots | Clones |
---|---|---|---|---|---|
LVM | images,rootdir | raw | possible | no | no |
LVM-Thin | images,rootdir | raw | no | yes | yes |
Administration
Create a Volume Group
Let’s assume we have a empty disk /dev/sdb, where we want to make a Volume Group named vmdata.
First create a partition.
Troubleshooting and known issues
Thin Overprovisioning
Therefore it is recommended
— to avoid overprovisioning; or at least, if not possible
— to check regularly via
the actual physical usage.
See also «Automatically extend thin pool LV» in
Proxmox 4. День второй. Thin-LVM
Добрый день, друзья. После ранее опубликованной статьи много воды утекло, было поднято несколько серверов, несколько уже на новой 5-ой версии. Были и кластеры и CEPH и даже репликация с двумя нодами (появилась функция в 5-ке). Для себя принял решение (как и советовали в прошлых комментариях), что проще и удобнее ставить debian, правильно размечать диски и поверх рабочего soft-raid поднимать proxmox.
О разметке, о VLM и о тонких дисках далее и пойдет речь.
На одном сервере столкнулся с очень большой и неприятной вещью. Сервер отдельный, на debian 8. При разметке, в которой отдельное большое место выделяется под thin-lvm диск для хранения дисков виртуальных машин, есть одна тонкость, которую я не учитывал ранее.
Пример реальной конфигурации: создан soft raid-10 из 4 дисков по 3 Тб.
Из общих 5,7 Тб выделен отдельный диск в 5,37 типа LVM-Thin для дисков виртуалок. Размещены виртуальные машины, общий выделенный объем дисков которых составил 4,03 ТБ. Машины работали себе и понемногу заполняли диски. Заполнение за полгода составило в среднем на 20-30% в каждой из виртуалок.
В очередной день (естественно понедельник, который совпал еще и с первым днем долгожданного отпуска) наш сервер zabbix начал лихорадочно отправлять через телеграмм уведомления от витруалок. Сначала про отказы отдельных сервисов типа http или ssh, а потом и вовсе про потерю пингов. Полез подключаться через ssh на почтовую виртуалку, тормозит, с первых пары секунд ничего не понятно, тут прилетают еще с десяток сообщений от zabbix о проблемах других виртуалок. Боковым взглядом понимаю, что плохо у всех виртуалок, кроме самого гиперзивора. Залезаю на него и открываю консоль первой же проблемной машины.
Первым, что подумал, рассыпался soft-raid. Но почему не было уведомления на эту тема от самого гипера – раз, почему гиппер работает внешне корректно – два.
Лезу на lvm –a И вижу общие данные по pve\data
Data% — 23,51%
Meta% — 99,95%
Проверяю остальные виртуалки – лежат с такими же ошибками записи, сервисы лихорадочно дергаются в конвульсиях. Пользователи – в истерике.
Из всех вменяемых статей в гугле на эту тему – везде пишут одно и тоже средство – расширить место с помощью добавления дополнительного физического жесткого диска.
Учитывая, что попасть в наш местный форд нокс, где находится этот сервер сложновато, теряем кучу времени, отправляем атишника с флешкой на 8Гб. Через 1,5 часа он на месте, вставляет флешку, я добавляю ее в группу lvm, расширяю meta диск еще на 3 Гб командой:
И получаю в итоге Meta% — 1,58%
Перезапускаю по очереди машины, проверяя их диски и исправляя проблемы руками, т.к. некоторые (например, почтовый сервер) не захотели без проблем и исправлений по sfck запускаться по-человечески. И наконец-то решаю проблему.
Что это было, Карл? — спрашиваю я себя.
Создавая раздел Thin-LVM и добавляя его в proxmox я и не думал, что надо вручную учитывать емкость метаданных, вычислять их на калькуляторе и задавать вручную при создании диска. Почему такие важные, критичные показатели никак не мониторятся к примеру через тот же GUI Proxmox?
Ребята, если не сложно, в комментариях, очень прошу высказаться по этому поводу, что сделано не так, почему очень мало написано про создание Thin и именно про meta данные. И какие есть варианты решения проблемы помимо моего. Далеко не всегда рядом может оказаться авторизованный человек с флешкой, которого пустили в ДЦ, дали доступ в стойку, а я, находясь в отпуске за 1 тыс км, сумел-таки простоем в 2 часа решить проблему.
Proxmox VE Storage
The Proxmox VE storage model is very flexible. Virtual machine images can either be stored on one or several local storages, or on shared storage like NFS or iSCSI (NAS, SAN). There are no limits, and you may configure as many storage pools as you like. You can use all storage technologies available for Debian Linux.
One major benefit of storing VMs on shared storage is the ability to live-migrate running machines without any downtime, as all nodes in the cluster have direct access to VM disk images. There is no need to copy VM image data, so live migration is very fast in that case.
The storage library (package libpve-storage-perl ) uses a flexible plugin system to provide a common interface to all storage types. This can be easily adopted to include further storage types in the future.
Storage Types
There are basically two different classes of storage types:
File level based storage technologies allow access to a fully featured (POSIX) file system. They are in general more flexible than any Block level storage (see below), and allow you to store content of any type. ZFS is probably the most advanced system, and it has full support for snapshots and clones.
Block level storage
Description | PVE type | Level | Shared | Snapshots | Stable | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
If a storage runs full, all guests using volumes on that storage receive IO errors. This can cause file system inconsistencies and may corrupt your data. So it is advisable to avoid over-provisioning of your storage resources, or carefully observe free space to avoid such conditions. |
Storage Configuration
Sharing storage configuration makes perfect sense for shared storage, because the same “shared” storage is accessible from all nodes. But it is also useful for local storage types. In this case such local storage is available on all nodes, but it is physically different and can have totally different content.
Storage Pools
The : line starts the pool definition, which is then followed by a list of properties. Most properties require a value. Some have reasonable defaults, in which case you can omit the value.
Common Storage Properties
A few storage properties are common among different storage types.
List of cluster node names where this storage is usable/accessible. One can use this property to restrict storage access to a limited set of nodes.
A storage can support several content types, for example virtual disk images, cdrom iso images, container templates or container root directories. Not all storage types support all content types. One can set this property to select what this storage is used for.
Allow to store container data.
Backup files ( vzdump ).
Snippet files, for example guest hook scripts
Mark storage as shared.
You can use this flag to disable the storage completely.
Deprecated, please use prune-backups instead. Maximum number of backup files per VM. Use 0 for unlimited.
Retention options for backups. For details, see Backup Retention.
Default image format ( raw|qcow2|vmdk )
It is not advisable to use the same storage pool on different Proxmox VE clusters. Some storage operation need exclusive access to the storage, so proper locking is required. While this is implemented within a cluster, it does not work between different clusters. |
Volumes
To get the file system path for a use:
Volume Ownership
There exists an ownership relation for image type volumes. Each such volume is owned by a VM or Container. For example volume local:230/example-image.raw is owned by VM 230. Most storage backends encodes this ownership information into the volume name.
When you remove a VM or Container, the system also removes all associated volumes which are owned by that VM or Container.
Using the Command Line Interface
It is recommended to familiarize yourself with the concept behind storage pools and volume identifiers, but in real life, you are not forced to do any of those low level operations on the command line. Normally, allocation and removal of volumes is done by the VM and Container management tools.
Nevertheless, there is a command line tool called pvesm (“Proxmox VE Storage Manager”), which is able to perform common storage management tasks.
Examples
Disable storage pools
Enable storage pools
Change/set storage options
Remove storage pools. This does not delete any data, and does not disconnect or unmount anything. It just removes the storage configuration.
Allocate a 4G volume in local storage. The name is auto-generated if you pass an empty string as
List storage status
List storage contents
List volumes allocated by VMID
List container templates
Show file system path for a volume
Directory Backend
Storage pool type: dir
Proxmox VE can use local directories or locally mounted shares for storage. A directory is a file level storage, so you can store any content type like virtual disk images, containers, templates, ISO images or backup files.
This backend assumes that the underlying directory is POSIX compatible, but nothing else. This implies that you cannot create snapshots at the storage level. But there exists a workaround for VM images using the qcow2 file format, because that format supports snapshots internally.
We use a predefined directory layout to store different content types into different sub-directories. This layout is used by all file level storage backends.
Configuration
This backend supports all common storage properties, and adds an additional property called path to specify the directory. This needs to be an absolute file system path.
File naming conventions
This backend uses a well defined naming scheme for VM images:
This specifies the owner VM.
This can be an arbitrary name ( ascii ) without white space. The backend uses disk-[N] as default, where [N] is replaced by an integer to make the name unique.
Specifies the image format ( raw|qcow2|vmdk ).
When you create a VM template, all VM images are renamed to indicate that they are now read-only, and can be used as a base image for clones:
Storage Features
As mentioned above, most file systems do not support snapshots out of the box. To workaround that problem, this backend is able to use qcow2 internal snapshot capabilities.
Same applies to clones. The backend uses the qcow2 base image feature to create clones.
Content types | Image formats | Shared | Snapshots | Clones | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
After an NFS request times out, NFS request are retried indefinitely by default. This can lead to unexpected hangs on the client side. For read-only content, it is worth to consider the NFS soft option, which limits the number of retries to three. |
Storage Features
NFS does not support snapshots, but the backend uses qcow2 features to implement snapshots and cloning.
Content types | Image formats | Shared | Snapshots | Clones | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Content types | Image formats | Shared | Snapshots | Clones | |||
---|---|---|---|---|---|---|---|
Content types | Image formats | Shared | Snapshots | Clones |
---|---|---|---|---|
Without their key, backups will be inaccessible. Thus, you should keep keys ordered and in a place that is separate from the contents being backed up. It can happen, for example, that you back up an entire system, using a key on that system. If the system then becomes inaccessible for any reason and needs to be restored, this will not be possible as the encryption key will be lost along with the broken system. |
It is recommended that you keep your key safe, but easily accessible, in order for quick disaster recovery. For this reason, the best place to store it is in your password manager, where it is immediately recoverable. As a backup to this, you should also save the key to a USB drive and store that in a secure place. This way, it is detached from any system, but is still easy to recover from, in case of emergency. Finally, in preparation for the worst case scenario, you should also consider keeping a paper copy of your key locked away in a safe place. The paperkey subcommand can be used to create a QR encoded version of your key. The following command sends the output of the paperkey command to a text file, for easy printing.
Additionally, it is possible to use a single RSA master key pair for key recovery purposes: configure all clients doing encrypted backups to use a single public master key, and all subsequent encrypted backups will contain a RSA-encrypted copy of the used AES encryption key. The corresponding private master key allows recovering the AES key and decrypting the backup even if the client system is no longer available.
The same safe-keeping rules apply to the master key pair as to the regular encryption keys. Without a copy of the private key recovery is not possible! The paperkey command supports generating paper copies of private master keys for storage in a safe, physical location. |
Because the encryption is managed on the client side, you can use the same datastore on the server for unencrypted backups and encrypted backups, even if they are encrypted with different keys. However, deduplication between backups with different keys is not possible, so it is often better to create separate datastores.
Do not use encryption if there is no benefit from it, for example, when you are running the server locally in a trusted network. It is always easier to recover from unencrypted backups. |
Example: Add Storage over CLI
Then you could add this share as a storage to the whole Proxmox VE cluster with:
Что нам стоит LVM построить (принцип работы, производительность, Thin Provision)
Не смотря на наличие нескольких статей на Хабре, про LVM2 и производительность Thin Provisioning, решил провести своё исследование, так как имеющиеся показались мне поверхностными.
Кому интересно, добро пожаловать под кат.
Немного о LVM2
Собственно, LVM это система управления дисковым пространством. Позволяет логически объединить несколько дисковых пространств (физические тома) в одно, и уже из этого пространства (Дисковой Группы или группы томов), можно выделять разделы (Логические Тома), доступные для работы. ОС получает к ним доступ через DevMapper.
Логические тома могут свободно размещаться в дисковой группе, занимая непрерывные или разрывные диапазоны адресов, или находится частично на разных дисках группы. Логические тома можно с легкостью изменять в размерах (а вот ФС не все так могут) или перемещать между дисками группы, а также создавать мгновенные снимки состояния логического тома (снапшот). Именно снапшоты и представляют главный интерес в статье.
Как вообще работает LVM
Идея тут проста, все вертится вокруг таблиц соответствия логических и физических адресов.
Общая схема такая: Физические тома отражаются на Дисковую группу. Дисковая группа отражается на Логические тома.
Снапшоты чуть иначе: собственная таблица ассоциирует блоки оригинального тома и блоки снапшота (копия блоков оригинала, до их модификации). Работает по принципу копирования при записи (CoW, делается копия блока оригинального тома, потом происходит запись этого блока в оригинальном томе). Создать снапшот от снапшота невозможно.
Тонкие тома работают чуть иначе. В группе томов создается специальный том (пул тонких томов, на самом деле состоит из двух, для данных и мета данных), из этого пула происходит выделение виртуального пространства для тонких томов. Пространство виртуально, потому как до момента реальной записи, блоки не выделяются из пула. И вообще, можно задать виртуальный размер тома, больше чем пул. Когда том распухнет до предела, система заморозит запись в него, до увеличения размеров пула. Снапшоты тут похожи на своих «толстых» братьев, но оперируют уже не блоками, а ссылками на блоки. То есть, после создания снапшота, запись в оригинал происходит так-же как и до создания снапшота (перезаписываемые блоки выделяются из пула). Есть возможность создавать снапшот от снапшота, а также можно указывать внешний том оригинала (размещенный вне тонкого пула в той же группе томов, защищенный от записи).
Производительность
Производительность толстых томов без снапшотов равна обычным дисковым разделам (разница очень мала), а как обстоят дела со снапшотами?
Тесты показали ад и ужас. Из-за CoW, операции записи в оригинальным том замедляются катастрофически! И чем больше снапшотов, тем хуже.
Несколько исправить положение дел может задание большего размера фрагмента (по умолчанию, это 4 килобайта, что дает большой объем маленьких iops). Ситуация несравнимо лучше, если писать не в оригинальный том, а в снапшот.
Тонкие тома показывают более сбалансированную картину. Скорость работы слабо зависит от числа снапшотов, и скорость значительно ниже, чем для простого толстого тома без снапшотов и близка к скорости записи в толстый снапшот. Основной вклад в тормоза дает процесс выделения места (фрагмент размером в 4 килобайта).
Методика тестирования
Надежность
Оценивать надежность я буду просто, по уровню сложности механизма доступа к информации. Чем он сложнее, тем его надежность ниже (к реальной надежности это имеет довольно далекое отношение).
Самым надежным, выглядит конечно обычный раздел. Пространство линейно, никаких промежуточных абстракций. Ломаться особо не чему. Из клёвых плюшек нет ничего.
Второе место займет Толстый Том. Появившиеся абстракции конечно не делают его надежнее, но добавляют массу гибкости. Восстанавливать данные из рассыпавшегося LVM не так уж и легко, но скорее всего, большинство томов будут размещены линейно, с небольшой фрагментацией (и эти фрагменты возможно будут крупными, вряд ли вы будете расширят разделы маленькими блоками).
Самыми ненадежными выглядят Тонкие Тома. Сложный механизм выделения места, изначально фрагментированное пространство (но не сами данные, они то как раз размещены компактно и даже линейно). Повреждение таблицы трансляции адресов, сделает данные крайне сложно читаемыми. К слову, надежность btrfs, zfs или ntfs на более худшем уровне. У тонких томов только распределение пространства в опасности, а у ФС еще и своих абстракций полно.
- Что значит прививаться с осторожностью спутник v
- Тульский кремль что посмотреть с детьми