Что такое lvm при установке ubuntu
Перейти к содержимому

Что такое lvm при установке ubuntu

  • автор:

Logical Volume Manager (LVM)

Logical Volume Manager (LVM) — это очень мощная система управления томами с данными для Linux. Она позволяет создавать поверх физических разделов (или даже неразбитых винчестеров) логические тома, которые в самой системе будут видны как обычные блочные устройства с данными (т.е. как обычные разделы). Основные преимущества LVM в том, что во-первых одну группу логических томов можно создавать поверх любого количества физических разделов, а во-вторых размер логических томов можно легко менять прямо во время работы. Кроме того, LVM поддерживает механизм снапшотов, копирование разделов «на лету» и зеркалирование, подобное RAID -1.

Создание и удаление

Как уже отмечалось, LVM строится на основе разделов жёсткого диска и/или целых жёстких дисков. На каждом из дисков/разделов должен быть создан физический том (physical volume). К примеру, мы используем для LVM диск sda и раздел sdb2:

На этих физических томах создаём группу томов, которая будет называться, скажем, vg1:

Посмотрим информацию о нашей группе томов:

Групп можно создать несколько, каждая со своим набором томов. Но обычно это не требуется.

Теперь в группе томов можно создать логические тома lv1 и lv2 размером 20 Гбайт и 30 Гбайт соответствено:

Теперь у нас есть блочные устройства /dev/vg1/lv1 и /dev/vg1/lv2.

Осталось создать на них файловую систему. Тут различий с обычными разделами нет:

Удаление LVM (или отдельных его частей, например, логических томов или групп томов) происходит в обратном порядке — сначала нужно отмонтировать разделы, затем удалить логические тома ( lvremove ), после этого можно удалить группы томов ( vgremove ) и ненужные физические тома ( pvremove ).

Добавление физических томов

Чтобы добавить новый винчестер sdc в группу томов, создадим физический том:

И добавим его в нашу группу:

Теперь можно создать ещё один логический диск ( lvcreate ) или увеличить размер существующего ( lvresize ).

Удаление физических томов

Чтобы убрать из работающей группы томов винчестер sda сначала перенесём все данные с него на другие диски:

Затем удалим его из группы томов:

И, наконец, удалим физический том:

Вообще-то, последняя команда просто убирает отметку о том, что диск является членом lvm, и особой пользы не приносит. После удаления из LVM для дальнейшего использования диск придётся переразбивать/переформатировать.

Изменение размеров

LVM позволяет легко изменять размер логических томов. Для этого нужно сначала изменить сам логический том:

а затем файловую систему на нём:

Как просто попробовать

Если LVM устанавливается не для дальнейшего использования, а «напосмотреть», то диски и разделы можно заменить файлами. Не понадобятся ни дополнительные диски, ни виртуальные машины. Мы создадим виртуальные накопители и будем с ними работать. Например, можно создать 4 диска по 1 Гбайт, но можно создать другое количество большего или меньшего размера как вам хочется. Создаем сами файлы, имитирующие устройства:

Создаем loopback устройства из файлов:

Дальше поступаем так же, как если бы ми создавали LVM на реальных дисках. Обратите внимание на названия loop-устройств — они могут отличаться от приведённых здесь.

Снапшоты

Одна из важнейших особенностей LVM — это поддержка механизма снапшотов. Снапшоты позволяют сделать мгновенный снимок логического тома и использовать его в дальнейшем для работы с данными.

Примеры использования

LVM активно используется, когда необходим механизм снапшотов. Например, этот механизм крайне важен при бекапе постоянно меняющихся файлов. LVM позволяет заморозить некоторое состояние ФС и скопировать с неё все нужные данные, при этом на оригинальной ФС останавливать запись не нужно.

Также снапшоты можно применить для организации поддержки файловым сервером с Samba механизма архивных копий, об этом в соответствующей статье:

LVM с LiveCD

Если у вас возникла необходимость работать с LVM с LiveCD Ubuntu, то вам придётся выполнить несколько дополнительных действий, поскольку по умолчанию утилит для работы с LVM нет.

Сначала вам нужно установить эти утилиты:

Далее посмотрите командами

доступность ваших групп томов. Ну а дальше запустите все группы командой

Эта команда должна сообщить о том, что все ваши логические тома активированы. Теперь можно работать с ними обычным образом.

Установка Ubuntu Desktop на LVM

Классические разделы, на которые чаще всего разбивается жёсткий диск для установки системы и хранения данных, имею ряд существенных недостатков. Их размер очень сложно изменять, они находятся в строгой последовательности и просто взять кусочек от первого раздела и добавить к последнему не получится, если между ними есть ещё разделы. Поэтому очень часто при начальном разбиении винчестера пользователи ломают себе голову — сколько места выделить под тот или иной раздел. И почти всегда в процессе использования системы приходят к выводу, что они сделали не правильный выбор.

  • Логические тома LVM больше не привязаны к физическому местоположению. В рамках LVM вообще не существует такого понятия, как порядок логических томов.
  • Размер логических томов можно увеличивать прямо на лету, а у отмонтированных томов можно кроме того легко уменьшать размер, не выходя из системы.
  • При необходимости можно размазать логические тома по нескольким физическим жёстким дискам, таким образом увеличив доступное место. При этом система всё так же будет видеть только один логический том, хотя размер его будет превышать доступные размеры жёстких дисков. Можно провести и обратную операцию, удалив жёсткий диск из LVM, таким образом освободив его для другого использования.
  • LVM поддерживает механизм снапшотов — мгновенных копий файловой системы тома. Это может очень пригодиться для создания бекапов.
  • Есть ещё масса плюсов, о которых можно почитать в специализированных статьях про LVM.

Учтите, что управление LVM осуществляется через терминал, поэтому, дабы ничего не поломать, вам необходимо сначала научиться более-менее комфортно с ним работать. Кроме того, ознакомьтесь с принципами работы и основными концепциями LVM, дабы понимать, что это такое. Статья рассчитана не на новичков, а на тех, кто уже разобрался в основах Ubuntu.

Предварительная подготовка

Вам необходимо запустить систему с LiveCD и подключить компьютер к интернету. Далее откройте терминал и установите прямо в LiveCD сессию необходимые утилиты командой:

Всё, теперь можно начинать работу с LVM. Но сначала необходимо выделить место, на котором мы будем создавать LVM. Для этого вам потребуется редактор разделов Gparted, который находится в меню Система→Администрирование (System→Administration). Создайте с помощью него раздел, поверх которого вы будете разворачивать LVM. Если вы готовы выделить под LVM весь жёсткий диск, то создайте раздел на весь жёсткий диск. Не выбирайте никакую файловую систему для раздела — просто пустой раздел (unformatted). Не забудьте, для применения всех внесённых вами через Gparted изменений нужно нажать на зелёную галочку на верхней панели или выбрать в меню Edit пункт Apply.

После того, как изменения в разметку будут успешно внесены, необходимо будет поменять тип нужного вам раздела на Linux LVM. Для этого нажмите правой клавишей на разделе, и выберите пункт Управление флагами (Manage flags). В открывшемся окне поставьте галочку в поле с именем lvm, дождитесь окончания применения всех изменений и закройте Gparted. На этом подготовительный этап закончен.

Создание логических томов LVM

Теперь пора приступить к непосредственному созданию LVM. Для примера будем считать, что LVM мы создаём поверх раздела /dev/sda1. В этом случае сначала необходимо инициализировать физический раздел командой:

Далее создать группу томов (о том, что это такое, читайте в статьях про LVM), командой

И, наконец, создать необходимые вам логические тома. Тут стоит заметить, что так как увеличивать размер LVM томов можно легко прямо в работающей системе, то лучше всего выделять для логических томов минимальный необходимый размер. Не бойтесь, что большой объём останется нераспределённым в рамках группы томов, он не пропадёт. Как только вам понадобится дополнительное место, вы сможете его легко добавить к любому логическому тому. А вот уменьшить размер логического тома значительно сложней.

Обычно для установки системы требуется раздел под корень, раздел под /home, раздел под swap и иногда — раздел под данные. Создать логические тома подо все эти четыре задачи можно командами:

Параметр -n, если вы ещё не поняли, задаёт имя логического тома, -L — его размер.

Теперь необходимо создать файловые системы на созданных логических томах. Сделать это можно примерно следующими командами:

Обратите внимание, что имена логических томов LVM в системе выглядят как /dev/<имя_группы_томов>/ .

Кроме того, файловая система ext4 по умолчанию резервирует часть места для системных данных. Поскольку на /home, и уж тем более на разделе с пользовательскими файлами, никаких системных данных никогда не будет, то лучше отменить это резервирование, дабы освободить пропадающее зря место. Для это пригодятся команды

Ни в коем случае не отменяйте резервирование для корневого раздела, иначе система может вообще перестать работать!

Ну и наконец вы возможно захотите присвоить разделу с данными нормальную метку, дабы он красиво отображался в установленной системе. Сделать это можно примерно такой командой:

Теперь можно приступать непосредственно к установке на созданные нами логические тома.

Установка системы

Собственно сама установка стандартна, однако когда вам предложат выбрать способ разбиения диска, выберите ручной режим. В открывшемся окне вы увидите все созданные вами тома LVM. Укажите для каждого соответствующую точку монтирования, однако не ставьте галочку форматирования. Для раздела под данные можете указать точку монтирования /media/data.

Дождитесь завершения установки, но компьютер не перезагружайте!

Если вы перезагрузите компьютер, то ваша новая система не запустится. В этом случае необходимо будет снова зайти в LiveCD, установить утилиты работы с LVM, а далее выполнить команду

После чего выполнить инструкции, приведённые ниже.

Активирование LVM в установленной системе

Систему вы поставили, однако осталась одна небольшая проблема — в установленной Ubuntu нет утилит работы с LVM, а значит она просто не запустится. Это достаточно легко исправить.

Для начала, не выходя с LiveCD, смонтируйте логический том, который вы выделили под корень, в папку /mnt. Сделать это можно командой

Теперь необходимо будет войти в установленную систему с помощью chroot, однако предварительно надо временно подключить в неё некоторые важные системные ресурсы. Для этого выполните команды

Теперь перейдите в установленную систему командой

И установите необходимые утилиты командой

Всё, установка завершена. Закройте терминал, нажмите Ctrl-Alt-Del и перезаргузите компьютер. Не забудьте достать LiveCD из привода. Компьютер должен загрузиться в только что установленную систему.

Дальнейшая работа

Допустим, в какой-то момент вам перестало хватать 5 гигабайт, которые вы выделили под раздел /home. Не беда. Посмотрите, сколько неиспользованного места осталось в группе томов командой

Теперь увеличьте размер логического тома /dev/local/home до нужного командой

Учтите, что в параметре -L указывается полный желаемый размер, а не его приращение. После увеличения размера логического тома останется лишь растянуть файловую систему на весь новый объём. Сделать это можно командой

Всё, размер логического тома увеличен.

Кроме увеличения размера логических томов на лету, LVM умееет ещё много чего полезного. Например, создавать мгновенные снапшоты. Однако обо всех тонкостях работы с этой технологией читайте в специализированных статьях.

How To Use LVM To Manage Storage Devices on Ubuntu 18.04

How To Use LVM To Manage Storage Devices on Ubuntu 18.04

Logical Volume Management, or LVM, is a storage device management technology that gives users the power to pool and abstract the physical layout of component storage devices for flexible administration. Using the device mapper Linux kernel framework, the current iteration, LVM2, can be used to gather existing storage devices into groups and allocate logical units from the combined space as needed.

In this tutorial, you’ll learn how to manage LVM by displaying information about volumes and potential targets, create and destroy volumes of various types, and modify existing volumes through resizing or transformation.

Prerequisites

To follow along, you will need to have a non-root user with sudo privileges configured on an Ubuntu 18.04 server. You can follow our Ubuntu 18.04 Initial Server Setup guide to get started.

Also, if you’re not familiar with LVM components and concepts, you can review our Introduction to LVM guide for more information.

When you are ready, log into your server with your sudo user.

Step 1 – Displaying Information About Physical Volumes, Volume Groups, and Logical Volumes

Accessing information about the various LVM components on your system is essential for managing your physical and logical volumes. LVM provides a number of tools for displaying information about every layer in the LVM stack.

Displaying Information About All LVM Compatible Block Storage Devices

To display all of the available block storage devices that LVM can potentially manage, use the lvmdiskscan command:

Notice the devices that can potentially be used as physical volumes for LVM.

This will likely be your first step when adding new storage devices to use with LVM.

Displaying Information about Physical Volumes

A header is written to storage devices to mark them as free to use as LVM components. Devices with these headers are called physical volumes.

You can display all of the physical devices on your system by using lvmdiskscan with the -l option, which will only return physical volumes:

The pvscan command is similar in that it searches all available devices for LVM physical volumes. The output format includes a small amount of additional information:

If you need additional details about your volume, the pvs and pvdisplay commands can do that for you.

The pvs command is highly configurable and can display information in many different formats. Because its output can be tightly controlled, it is frequently used when scripting or automation is needed. Its basic output provides a useful at-a-glance summary similar to the earlier commands:

For more verbose, human-readable output, the pvdisplay command is a good option:

To discover the logical extents that have been mapped to each volume, pass in the -m option to pvdisplay :

This can be very useful when trying to determine which data is held on which physical disk for management purposes.

Displaying Information about Volume Groups

LVM also has plenty of tools to display information about volume groups.

The vgscan command can be used to scan the system for available volume groups. It also rebuilds the cache file when necessary. It is a good command to use when you are importing a volume group into a new system:

This command does not output very much information, but it should be able to find every available volume group on the system. To display more information, the vgs and vgdisplay commands are available.

Like its physical volume counterpart, the vgs command is versatile and can display a large amount of information in a variety of formats. Because its output can be manipulated, it is frequently used when scripting or automation is needed. For example, some helpful output modifications are to show the physical devices and the logical volume path:

Likewise, for more verbose, human-readable output, use the vgdisplay command. Adding the -v flag provides information about the physical volumes the volume group is built upon, and the logical volumes that were created using the volume group:

The vgdisplay command is useful because it can tie together information about many different elements of the LVM stack.

Displaying Information about Logical Volumes

To display information about logical volumes, LVM has a related set of tools.

As with the other LVM components, the lvscan option scans the system and outputs minimal information about the logical volumes it finds:

For more complete information, the lvs command is flexible and powerful to use in scripts:

To find the number of stripes and the logical volume type, use the —segments option:

The most human-readable output is produced by the lvdisplay command.

When the -m flag is added, the tool will also display information about how the logical volume is broken down and distributed:

In this example, the /dev/LVMVolGroup/projects logical volume is contained entirely within the /dev/sda physical volume. This information is useful if you need to remove that underlying device and wish to move the data off to specific locations.

Step 2 – Creating or Extending LVM Components

This section discusses how to create and expand physical volumes, volume groups, and logical volumes.

Creating Physical Volumes From Raw Storage Devices

To use storage devices with LVM, they must first be marked as a physical volume. This specifies that LVM can use the device within a volume group.

First, use the lvmdiskscan command to find all block devices that LVM can access and use:

Here, notice the devices that are suitable to be turned into physical volumes for LVM.

Warning: Make sure that you double-check that the devices you intend to use with LVM do not have any important data already written to them. Using these devices within LVM will overwrite the current contents. If you have important data on your server, make backups before proceeding.

To mark the storage devices as LVM physical volumes, use pvcreate . You can pass in multiple devices at once:

This command writes an LVM header on all of the target devices to mark them as LVM physical volumes.

Creating a New Volume Group from Physical Volumes

To create a new volume group from LVM physical volumes, use the vgcreate command. You have to provide a volume group name, followed by at least one LVM physical volume:

This example creates your volume group with a single initial physical volume. You can pass in more than one physical volume at creation if you’d like:

Usually, you only need a single volume group per server. All LVM-managed storage can be added to that pool and then logical volumes can be allocated from that.

One reason you may wish to have more than one volume group is if you feel you need to use different extent sizes for different volumes. You don’t typically have to set the extent size (the default size of 4M is adequate for most uses), but if you need to, you can do so upon volume group creation by passing the -s option:

This will create a new volume group with an 8M extent size.

Adding a Physical Volume to an Existing Volume Group

To expand a volume group by adding additional physical volumes, use the vgextend command. This command takes a volume group followed by the physical volumes to add. You can pass in multiple devices at once if you’d like:

The physical volume will be added to the volume group, expanding the available capacity of the storage pool.

Creating a Logical Volume by Specifying Size

To create a logical volume from a volume group storage pool, use the lvcreate command. Specify the size of the logical volume with the -L option, then specify a name with the -n option, and pass in the volume group to allocate the space from.

For instance, to create a 10G logical volume named test from the LVMVolGroup volume group, write:

If the volume group has enough free space to accommodate the volume capacity, the new logical volume will be created.

Creating a Logical Volume From All Remaining Free Space

If you wish to create a volume using the remaining free space within a volume group, use the vgcreate command with the -n option to name and pass in the volume group like the previous step. Instead of passing in a size, use the -l 100%FREE option, which uses the remaining extents within the volume group to form the logical volume:

This should use up the remaining space in the logical volume.

Creating Logical Volumes with Advanced Options

Logical volumes can be created with some advanced options. Some options that you may wish to consider are:

  • —type : This specifies the type of logical volume, which determines how the logical volume is allocated. Some available types will not be available if there are not enough underlying physical volumes to correctly create the chosen topography. Some of the most common types are:
    • linear : The default type. The underlying physical devices used, if more than one, will be appended to each other, one after the other.
    • striped : Similar to RAID 0, the striped topology divides data into chunks and spread in a round-robin fashion across the underlying physical volumes. This can lead to performance improvements, but might lead to greater data vulnerability. This requires the -i option and a minimum of two physical volumes.
    • raid1 : Creates a mirrored RAID 1 volume. By default, the mirror will have two copies, but more can be specified by the -m . This requires a minimum of two physical volumes.
    • raid5 : Creates a RAID 5 volume. This requires a minimum of three physical volumes.
    • raid6 : Creates a RAID 6 volume. This requires a minimum of four physical volumes.

    To demonstrate, begin by creating a striped volume. You must specify at least two stripes for this method. This topology and stripe count requires a minimum of two physical volumes with available capacity:

    To create a mirrored volume, use the raid1 type. If you want more than two sets of data, use the -m option. This example uses -m 2 to create a total of three sets of data. LVM counts this as one original data set with two mirrors. You need at least three physical volumes for this to succeed:

    To create a snapshot of a volume, you must provide the original logical volume to snapshot instead of the volume group. Snapshots do not take up much space initially, but grow in size as changes are made to the logical volume it is tracking. The size used during this procedure is the maximum size that the snapshot can be. Snapshots that grow past this size are broken and cannot be used, however, snapshots approaching their capacity can be extended:

    Note: To revert a logical volume to the point-in-time of a snapshot, use the lvconvert —merge command:

    This will bring the origin of the snapshot back to the state when the snapshot was taken.

    There are a number of options that can dramatically alter the way that your logical volumes function.

    Growing the Size of a Logical Volume

    One of the main advantages of LVM is the flexibility it provides in provisioning logical volumes. You can adjust the number or size of volumes on the fly without stopping the system.

    To grow the size of an existing logical volume, use the lvresize command. Use the -L flag to specify a new size. You can also use relative sizes by adding a + size. In that case, LVM will increase the size of the logical volume by the amount specified. To automatically resize the filesystem being used on the logical volume, pass in the —resizefs flag.

    To correctly provide the name of the logical volume to expand, you need to give the volume group, followed by a slash, followed by the logical volume:

    In this example, the logical volume and the filesystem of the test logical volume on the LVMVolGroup volume group will both be increased by 5G.

    If you wish to handle the filesystem expansion manually, take out the —resizefs option and use the filesystem’s native expansion utility afterwards. For example, for an Ext4 filesystem, write:

    This returns the same result.

    Step 3 – Removing or Downsizing LVM Components

    Since capacity reduction can result in data loss, the procedures to shrink the available capacity, either by reducing the size of or removing components are typically a bit more involved.

    Reducing the Size of a Logical Volume

    To shrink a logical volume, you should first back up your data. Because this reduces the available capacity, mistakes can lead to data loss.

    When you are ready, check on how much space is currently being used:

    In this example, a little over 521M of the space is currently in use. Use this to help you estimate the size that you can reduce the volume to.

    Unlike expansions, filesystem shrinking should be performed when unmounted. First, make sure you’re in the root directory:

    Next, unmount the filesystem:

    After unmounting, check the filesystem to ensure that everything is in working order. Pass in the filesystem type with the -t option. Use -f to check when the filesystem appears:

    After checking the filesystem, you can reduce the filesystem size using the filesystem’s native tools. For Ext4 filesystems, this would be the resize2fs command. Pass in the final size for the filesystem:

    Warning: The safest option here is to choose a final size that is a fair amount larger than your current usage. Give yourself some buffer room to avoid data loss and ensure that you have backups in place.

    Once the operation is complete, resize the logical volume by passing the same size to the lvresize command with the -L flag:

    You are warned about the possibility of data loss. If you are ready, enter y to proceed.

    After the logical volume has been reduced, check the filesystem again:

    If everything is functioning correctly, you can remount the filesystem using your usual mount command:

    Your logical volume should now be reduced to the appropriate size.

    Removing a Logical Volume

    If you no longer need a logical volume, you can remove it with the lvremove command.

    First, unmount the logical volume if it is currently mounted:

    Afterwards, remove the logical volume by entering this command:

    You are asked to confirm the procedure. If you are certain you want to delete the logical volume, press y .

    Removing a Volume Group

    To remove an entire volume group, including all of the logical volumes within it, use the vgremove command.

    Before you remove a volume group, you should remove the logical volumes using the procedure previously discussed. At the very least, you must make sure that you unmount any logical volumes that the volume group contains:

    Afterwards, you can delete the entire volume group by passing the volume group name to the vgremove command:

    You are then prompted to confirm that you wish to remove the volume group. If you have any logical volumes still present, you are given individual confirmation prompts for those before removing.

    Removing a Physical Volume

    To remove a physical volume from LVM management, the procedure you need depends on whether the device is currently being used by LVM.

    If the physical volume is in use, you have to move the physical extents located on the device to a different location. This requires the volume group to have enough other physical volumes to handle the physical extents. If you are using more complex logical volume types, you might need additional physical volumes even when you have plenty of free space to accommodate the topology.

    When you have enough physical volumes in the volume group to handle the physical extents, move them off of the physical volume you wish to remove by running:

    This process can take time depending on the size of the volumes and the amount of data to transfer.

    Once the extents have been relocated to peer volumes, you can remove the physical volume from the volume group:

    This removes the vacated physical volume from the volume group. After this is complete, you can remove the physical volume marker from the storage device:

    You can now use the removed storage device for other purposes or remove it from the system entirely.

    Conclusion

    You now have an understanding of how to manage storage devices on Ubuntu 18.04 with LVM. You also know how to get information about the state of existing LVM components, how to use LVM to compose your storage system, and how to modify volumes to meet your needs. Feel free to test these concepts in a safe environment to get a better grasp of how they fit together.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    What is LVM

    LVM stands for Logical Volume Management. It is a system of managing logical volumes, or filesystems, that is much more advanced and flexible than the traditional method of partitioning a disk into one or more segments and formatting that partition with a filesystem.

    Why use LVM?

    For a long time I wondered why anyone would want to use LVM when you can use gparted to resize and move partitions just fine. The answer is that lvm can do these things better, and some nifty new things that you just can’t do otherwise. I will explain several tasks that lvm can do and why it does so better than other tools, then how to do them. First you should understand the basics of lvm.

    The Basics

    • Volume Groups
    • Physical Volumes
    • Logical Volumes

    A Volume Group is a named collection of physical and logical volumes. Typical systems only need one Volume Group to contain all of the physical and logical volumes on the system, and I like to name mine after the name of the machine. Physical Volumes correspond to disks; they are block devices that provide the space to store logical volumes. Logical volumes correspond to partitions: they hold a filesystem. Unlike partitions though, logical volumes get names rather than numbers, they can span across multiple disks, and do not have to be physically contiguous.

    The Specifics

    One of the biggest advantages LVM has is that most operations can be done on the fly, while the system is running. Most operations that you can do with gparted require that the partitions you are trying to manipulate are not in use at the time, so you have to boot from the livecd to perform them. You also often run into the limits of the msdos partition table format with gparted, including only 4 primary partitions, and all logical partitions must be contained within one contiguous extended partition.

    Resizing Partitions

    With gparted you can expand and shrink partitions, but only if they are not in use. LVM can expand a partition while it is mounted, if the filesystem used on it also supports that ( like the usual ext3/4 ). When expanding a partition, gparted can only expand it into adjacent free space, but LVM can use free space anywhere in the Volume Group, even on another disk. When using gparted, this restriction often means that you must move other partitions around to make space to expand one, which is a very time consuming process that can result in massive data loss if it fails or is interrupted ( power loss ).

    Moving Partitions

    Moving partitions with gparted is usually only necessary in the first place because of the requirement that partitions be physically contiguous, so you probably won’t ever need to do this with LVM. If you do, unlike gparted, LVM can move a partition while it is in use, and will not corrupt your data if it is interrupted. In the event that your system crashes or loses power during the move, you can simply restart it after rebooting and it will finish normally. When I got my SSD drive, I simply plugged it in, booted it up, and asked lvm to move my running root filesystem to the new drive in the background while I continued working. Another reason you might want to move is to replace an old disk with a new, larger one. You can migrate the system to the new disk while using it, and then remove the old one later.

    Many Partitions

    If you like to test various Linux distributions, or just different version of Ubuntu, or both, you can quickly end up with quite a few partitions. With conventional msdos partitions, this becomes problematic due to its limitations. With LVM you can create as many Logical Volumes as you wish, and it is usually quite easy since you usually have plenty of free space left. Usually people allocate the entire drive to one partition when they first install, but since extending a partition is so easy with LVM, there is no reason to do this. It is better to allocate only what you think you will need, and leave the rest of the space free for future use. If you end up running out of the initial allocation, adding more space to that volume is just one command that completes immediately while the system is running normally.

    Snapshots

    This is something you simply can not do without LVM. It allows you to freeze an existing Logical Volume in time, at any moment, even while the system is running. You can continue to use the original volume normally, but the snapshot volume appears to be an image of the original, frozen in time at the moment you created it. You can use this to get a consistent filesystem image to back up, without shutting down the system. You can also use it to save the state of the system, so that you can later return to that state if you mess things up. You can even mount the snapshot volume and make changes to it, without affecting the original.

    The Details

    So how do I start using LVM?

    The alternate installer has the ability to set up and install to LVM, and is the supported way of doing so. You can install the lvm2 package on an existing system, or the desktop livecd and manually set it up, and then install to it. This is what I will cover. (Ubuntu 12.10 has since introduced LVM support from the installation live CD.)

    First, you need a Physical Volume. Typically you start with a hard disk, and create an LVM type partition on it. You can create one with gparted or fdisk, and usually only want one partition to use the whole disk, since LVM will handle subdividing it into Logical Volumes. In gparted, you need to check the lvm flag when creating the partition, and with fdisk, tag the type with code 8e.

    Once you have your LVM partition, you need to initialize it as a Physical Volume. Assuming this partition is /dev/sda1:

    sudo pvcreate /dev/sda1

    This writes the LVM header to the partition, which identifies it as a Physical Volume, and sets up a small area to hold the metadata describing everything about the Volume Group, and the the rest of the partition as unused Physical Extents. After that, you need to create a Volume Group named foo:

    sudo vgcreate foo /dev/sda1

    Now you have a Volume Group named foo. I suggest you change foo to a name meaningful to you. foo contains only one Physical Volume. Now you want to create a Logical Volume from some of the free space in foo:

    sudo lvcreate -n bar -L 5g foo

    This creates a Logical Volume named bar in Volume Group foo using 5 GB of space. If you are installing, you probably want to create a Logical Volume like this to use as a root filesystem, and one for swap, and maybe one for /home. I currently have a Logical Volume for a Lucid install, and one for a Maverick install, so that is what I named those volumes. You can find the block device for this Logical Volume in ‘/dev/foo/bar’ or ‘dev/mapper/foo-bar’.

    You might also want to try the lvs and pvs commands, which list the Logical Volumes and Physical Volumes respectively, and their more detailed variants; lvdisplay and pvdisplay.

    If you are doing this from the desktop livecd, once you have created your Logical Volumes from the terminal, you can run the installer, and use manual partitioning to select how to use each Logical Volume, and then install.

    Resizing Partitions

    You can extend a Logical Volume with:

    sudo lvextend -L +5g foo/bar

    This will add 5 GB to the bar Logical Volume in the foo Volume Group. You can specify an absolute size if you want instead of a relative size by omitting the leading +. The space is allocated from any free space anywhere in the bar Volume Group. If you have multiple Physical Volumes you can add the names of one or more of them to the end of the command to limit which ones should be used to satisfy the request.

    After extending the Logical Volume you need to expand the filesystem to use the new space. For ext 3/4, you simply run:

    sudo resize2fs /dev/foo/bar

    Moving Partitions

    If you only have one Physical Volume then you probably will not ever need to move, but if you add a new disk, you might want to. To move the Logical Volume bar off of Physical Volume /dev/sda1, you run:

    sudo pvmove -n bar /dev/sda1

    If you omit the -n bar argument, then all Logical Volumes on the /dev/sda1 Physical Volume will be moved. If you only have one other Physical Volume, then that is where it will be moved to, or you can add the name of one or more specific Physical Volumes that should be used to satisfy the request, instead of any Physical Volume in the Volume Group with free space. This process can be resumed safely if interrupted by a crash or power failure, and can be done while the Logical Volume(s) in question are in use. You can also add -b to perform the move in the background and return immediately, or -i s to have it print how much progress it has made every s seconds. If you background the move, you can check its progress with the lvs command.

    Snapshots

    When you create a snapshot, you create a new Logical Volume to act as a clone of the original Logical Volume. The snapshot volume initially does not use any space, but as changes are made to the original volume, the changed blocks are copied to the snapshot volume before they are changed, in order to preserve them. This means that the more changes you make to the origin, the more space the snapshot needs. If the snapshot volume uses all of the space allocated to it, then the snapshot is broken and can not be used any more, leaving you only with the modified origin. The lvs command will tell you how much space has been used in a snapshot Logical Volume. If it starts to get full, you might want to extend it with the lvextend command. To create a snapshot of the bar Logical Volume and name it snap, run:

    sudo lvcreate -s -n snap -L 5g foo/bar

    This will create a snapshot named snap of the original Logical Volume bar and allocate 5 GB of space for it. Since the snapshot volume only stores the ares of the disk that have changed since it was created, it can be much smaller than the original volume. I recently used a 5 GB snapshot of a 12 GB Logical Volume holding my Maverick root filesystem and ran an dist-upgrade to Natty on the origin, which only used about 50-60% of the snapshot space.

    While you have the snapshot, you can mount it if you wish and will see the original filesystem as it appeared when you made the snapshot. In the above example you would mount the /dev/foo/snap device. You can modify the snapshot without affecting the original, and the original without affecting the snapshot. If you take a snapshot of your root Logical Volume, and then upgrade some packages, or to the next whole distribution release, and then decide it isn’t working out, you can merge the snapshot back into the origin volume, effectively reverting to the state at the time you made the snapshot. To do this, you simply run:

    sudo lvconvert --merge foo/snap

    If the origin volume of foo/snap is in use, it will inform you that the merge will take place the next time the volumes are activated. If this is the root volume, then you will need to reboot for this to happen. At the next boot, the volume will be activated and the merge will begin in the background, so your system will boot up as if you had never made the changes since the snapshot was created, and the actual data movement will take place in the background while you work.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *