Linux lvm восстановление данных

RAID 5 с LVM под Linux и как с него восстанавливать информацию

В данном руководстве мы рассмотрим способ создания в ОС Linux программного LVM RAID. А также представим простое решение, позволяющее вернуть утраченную информации с LV RAID 5 после случайного удаления или непредвиденной неисправности накопителей.

«LVM» (означает Менеджер логических томов) это функция ОС Linux, благодаря которой можно объединить несколько разделов одного или нескольких накопителей в единый непрерывный логический раздел (том). А «LVM RAID» – это отдельный метод сбора «LV» раздела, который объединяет несколько физических носителей, но они получают дополнительную защиту данных как «RAID» массив.

Драйвера DM будут использоваться для управления физическими устройствами LVM, а драйвера MD — для размещения информации на носителях. LVM управляет скрытыми логическими томами (DM), которые находятся между видимыми разделами (LV) и носителями.

В нашем случае, мы будем создавать «RAID 5». Чем он отличается от других типов массивов, вы узнаете посмотрев этот видеоурок.

Размечаем физические диски, создаем LV RAID группу.

В терминале Linux вводим команду: lvcreate, и создаем LV RAID.

Если в системе не установлен компонент LVM, то прописываем команду: sudo apt install lvm2.

Все команды нужно выполнять от имени «root», поэтому вводим: sudo -i, чтобы не вводить пароль «root» постоянно.

Теперь разметка дисков через стандартную дисковую утилиту Linux, выбираем тип ФС и форматируем.

Или выполняем через терминал: fdisk /dev/sdb.

  • n – создает новый раздел,
  • p – устанавливает для раздела значение «основной»,
  • 1 – присваивает номер.

Дважды жмем «Ввод», соглашаясь со значением первого и последнего секторов.

Далее, нужно задать настройки LVM. Каждый в своей строке применяем атрибуты:

  • t – запускает процесс по изменению типа нового раздела,
  • 8e – устанавливает значение LVM.

Убедимся, что новый раздел имеет нужный тип. Наберите в командной строке атрибут «p». Система обработает запрос и представит в табличной форме итоговые сведения. Искомое устройство будет маркировано значением «sdb1» с типом системы «Linux LVM». Потом записываем установленные изменения, используя атрибут «w». Теперь повторите для каждого диска, который будет входить в LVM.

Далее вводим: pvcreate /dev/sdb1.

Повторяем команду для каждого диска, заменив «sdb1» на другое имя, в нашем случае «sdc1», «sdd1», «sde1», «sdf1».

Теперь собираем в единую группу: vgcreate и перечисляем все входящие носители:

«vgcreate vg1 /dev/sdb1 dev/sdc1 dev/sdd1 dev/sde1 dev/sdf1». Где «vg1» — имя группы.

Создаем программный LVM RAID 5

Вводим команду: «lvcreate -n lvr5 –type raid5 -L 10G -i 4 vg1»

Где атрибуты означают:

  • -n – присваивает тому имя.
  • –type raid5 – задает тип массива.
  • -L – устанавливает граничный размер для логического тома (у нас его величина равна 10 ГБ).
  • -i – указывает количество устройств, которые будут задействованы в хранении пользовательских данных. Сюда не входит дополнительное устройство для хранения блоков четности. Число должно быть 2 или больше, так как минимальное количество дисков для данного типа – три.
  • vg1 – объясняет системе, откуда ей следует взять нужное количество дискового пространства (указывается конкретный том или целая группа).

После выполнения новый массив RAID 5 на виртуальной группе LVM будет создан. Теперь нужно отформатировать массив смонтировать. Форматируем RAID 5 в «ext4»: «mkfs -t ext4 /dev/vg1/lvr5»

Где, файловая система «ext4», название группы «vg1», имя тома «lvr5».

Монтируем RAID 5 массив в систему, вводим команду: «mkdir /mnt/lvr5», и вторую: «mount -t ext4 /dev/vg1/lvr5 /mnt/lvr5».

Теперь массив смонтирован и готов к работе.

Проверяем статус LVM RAID

Выполняем команду: «lvs -a -o name,copy_percent,devices vg1»

На терминале будет выведена вся доступная информация об подключенных физических носителях и группах томов.

Как восстанавливать данные с LVM RAID массива
В нашем случае, мы создавали LVM RAID 5, такой тип массива хранит дополнительную избыточную информацию, что хорошо сказывается на сохранности данных. То есть при поломке одного или даже двух физических дисков, большинство файлов все равно можно будет восстановить в нетронутом виде.

Производители NAS, к своим устройствам, предоставляют собственное ПО для восстановления данных с их массива. Но так как мы использовали программный RAID, то нам понадобится По от сторонних разработчиков. Главные критерии выбора оного: поддержка нужных файловых систем, низкоуровневый чтение диска, а также наличие автоматического и ручного RAID конструктора. Программа должна пересобрать массив заново и позволить смонтировать его в систему, а далее остается только провести анализ и сохранить все «живые данные».

LVM является одной из множества технологий Linux, которая позволяет достичь большой гибкости в управлении дисковым пространством. Эта функция, объединённая с RAID, хорошо защищает данные от возможной потери, обеспечивает простой способ хранения, управления и совместного использования пользовательских файлов в хранилище.

Читайте также:  Csv для windows phone

Полную версию статьи со всеми дополнительными видео уроками смотрите в источнике.

Источник

Восстановление потерянного тома LVM в XenServer

Жила-была у меня машина с XenServer 6.5 на борту и несколькими массивами из SATA-дисков. В последнее время перестало хватать быстродействия SATA и было решено заменить один массив на SAS-диски. Для этих целей был найден RAID-контроллер Adaptec 3805 (знаю, что старье, зато халява).

После успешного создания RAID-массива из SAS-дисков(каюсь, использовал адаптековский raid) и добавления оного как lvm-storage, начал перенос одного из образов виртуальных машин на него. В процессе созерцания прогресса переноса закралось подозрение о неладном, так как изменился тон звучания сервера. А когда сервер ушел в самостоятельную перезагрузку, я начал понемногу седеть… И окончательно меня добило то, что после перезагрузки я не нашел переносимый образ ни в одном из хранилищ, а само новое хранилище отображается со статусом «не доступно».

После непродолжительной прогулки для успокоения нервов и чашки кофе я закатал рукава (ага, на футболке то) и начал думать как восстановить образ…

Для начала, естественно, полез в логи и увидел, что при создании хранилища из массива SAS произошла ошибка:

Ошибка означает, что хранилище не доступно. Я решил проверить физические тома lvm через pvdisplay и не увидел созданного тома на SAS-массиве. pvs тоже не обнаружил тома.
Это означало, что хранилище, на самом деле, не создалось. Точнее создался объект хранилища в XenServer, но при этом он не был связан с физическим хранилищем. Почему XenServer так себя повел, и, тем более, позволил перенести образ в это хранилище, я так и не выяснил.

Получается, что образ на SAS-массиве можно даже не искать, так как физически на него ничего не переносилось. Значит нужно пробовать восстанавливать образ с хранилища, на котором он был изначально.

Поиск в интернете на тему восстановления логических томов LVM задал начальный вектор раскопок.

LVM хранит свою текущую конфигурацию в /etc/lvm/backup/ и, в обычных условиях, архив старых конфигураций в виде бинарных файлов, в /etc/lvm/archive/. UUID хранилища XenServer соответствует имени LVM VolumeGroup. Но, оказывается, в XenServer этот самый архив отключен:

# Configuration of metadata backups and archiving. In LVM2 when we
# talk about a ‘backup’ we mean making a copy of the metadata for the
# *current* system. The ‘archive’ contains old metadata configurations.
# Backups are stored in a human readeable text format.
backup <

# Should we maintain a backup of the current metadata configuration?
# Use 1 for Yes; 0 for No.
# Think very hard before turning this off!
backup = 1

# Where shall we keep it?
# Remember to back up this directory regularly!
backup_dir = «/etc/lvm/backup»

# Should we maintain an archive of old metadata configurations.
# Use 1 for Yes; 0 for No.
# On by default. Think very hard before turning this off.
archive = 0

# Where should archived files go?
# Remember to back up this directory regularly!
archive_dir = «/etc/lvm/archive»

# What is the minimum number of archive files you wish to keep?
retain_min = 10

# What is the minimum time you wish to keep an archive file for?
retain_days = 30
>

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

Если видно что-то похожее на конфиги, то можно снять дамп этих секторов для более удобного чтения (в моем случае архив занимал 100Мб):

Так же дамп можно снять через команду lvmdump.

В дампе ищу конфиг, дата которого предшествует моменту пропажи образа:

Из этого конфига нужна только запись, соответствующая пропавшему образу (та запись, которая отсутствует в текущем конфиге в /etc/lvm/backup/ , в моем случае VHD-6bdf21c1-cc52-45d1-ab9e-56bd7aa9bc89). Переписываю ее в текущую конфигурацию и даю LVM команду восстановить VG из бэкапа:

Проверяю, что Logical Volume подхватился:

Если сейчас сделать поиск по хранилищу (через XenCenter или xe sr-scan), то XenServer успешно затрет эту запись и все придется делать заново. Как я понял, XenServer не видит у себя VDI (образа диска) с UUID, соответствующем UUID нашему восстановленному Logical Volume.

XenServer, при использовании lvm, хранит образы дисков напрямую в Logcal Volume. Точнее Logical Volume это и есть VHD-образ. Поэтому я предположил, что можно заставить XenServer увидеть образ, скопировав его поверх другого, такого же размера.

Для копирования раздела активирую разделы в этом VG:

Теперь есть доступ к разделу LVM, значит можно скопировать этот раздел с помощью dd:

После того, как скопированный образ добавился в виртуальной машине, а так же после того, как машина стартанула с этого образа, моему счастью не было предела!

Однако не все так радужно. Нужно было еще выключить сервер, чтобы вытащить глючный контроллер. А когда я его включил образ снова пропал! Получается, что XenServer при запуске сверяет UUID образа в LVM c UUID в своей базе и, если они не совпадают, образ удаляется.

Пока ковырял LVM заметил, что при переносе образа из одного хранилища в другое так же меняется и его UUID и, исходя из этого, предположил, что можно окончательно воскресить образ, просто скопировав переписанный через dd образ в другое хранилище. Это должно обновить UUID в образе, сопоставив его в UUID в базе. Повторяем все процедуры заново, после чего переносим образ на временно созданное для этого хранилище, добавляем к виртуальной машине и пробуем ее запустить. Запуск проходит нормально.

Читайте также:  Что будет если отключить центр безопасности windows 10

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

Источник

Data Recovery from LVM Volumes in Linux

Would you like to know how to use the LVM technology in Linux? How to create an LVM volume, how to configure and mount it in your operating system, how to add and remove disks, and how to recover the information you have accidentally deleted? In today’s article, you will find all of that – and even more.

What is LVM?

LVM (Logical Volume Manager) is a standard disk management feature available in every version of Linux. The volume manager provides a new level of interaction between your operating system and disks or volumes which this system is using. In a conventional disk management pattern, Linux looks for available drives first, and then checks what volumes are available on these devices.

With the help of LVM, disks or volumes can be united into a single space. If the disk space is treated like that, the operating system will see no difference between them and the volume manager will show the operating system only the necessary volume groups or physical disks.

In fact, LVM has several considerable advantages to offer:

It can create a logical volume based on any number of physical disks which will be represented in the operating system as a single disk space.

The number of disks included and the size of such volume can be modified without interrupting your work.

Also, the LVM technology lets you do many things on the fly, like copying certain volumes, or configuring the mirroring feature the way it works in RAID 1 systems.

How to add LVM to the operating system?

If you are going to use LVM options for the first time, you have to install it. Here is the command you need for installation: sudo apt install lvm2

After that, type the administrator’s password, and click Yes to confirm your intention.

Some Linux versions have this feature installed by default.

This can be checked easily, by typing the command lvm in the terminal window.

Now you can move on to dealing with disks.

How to format a physical disk

Here we are, with three empty hard disks 320 GB each, which are unformatted and without any partitions.

The easiest way to format a disk is by using a disk management utility. Click on a disk – open advanced settings – then format it.

Specify the name and file system – Next– and click Format again to confirm your action

Now you’ll need the password to your administrator account.

Now that this disk is formatted, repeat the operation for every other disk which is not.

Also, a disk can be formatted with the terminal, using the command fdisk.

Sign in with a superuser account – sudo –i – type the password.

Now run the following command: fdisk /dev/sdb – where sdb is the unformatted disk.

Before you continue, make sure you have selected the right disk, because this operation erases all data from there.

Type n – new volume, p – primary, 1 – first partition, then press Enter twice.

Now let’s get the volume ready to be used with LVM. Type t to change the volume type, and then 8e to assign LVM type.

Check the volume properties by pressing p – you can see everything is OK, a new formatted volume with the name sdb1 appeared; press w to record the changes. Similarly, format all the disks which are not formatted yet.

Now create an LVM volume on the partition you have just created, by entering the command: pvcreate /dev/sdb1.

Repeat the command for every disk: pvcreate /dev/sdс1, pvcreate /dev/sdd1.

Create a volume group

Combine the three disks you have just prepared into an LVM volume. Here’s the command to use:

vgcreate vg1 /dev/sdb1 dev/sdc1 dev/sdd1

where vg1 is the name of the new group. Actually, you can use any name you prefer, but it’s recommended to put the vg letter combination before the name so that you know it is a volume group.

Create a logical volume to use LVM

When the disks are combined into the group, you need to create a new logical volume, so that you can use this group. For this purpose, type the command:

lvcreate -L 10G -n lv1 vg1

Where the -L stands for the size of the logical volume – it is 10 GB in this case, and the -n assigns a name to the volume, and the vg1 indicates from which volume the space should be taken.

If there is any data on the disk, the operating system will warn you about it: type yes to confirm your decision to erase the information.

Читайте также:  Как windows 10 оптимизирует ssd

How to format and mount a logical volume?

The last step you still have to take is to format the volume in the disk management utility and mount it. Click on it to open advanced settings and then format it; specify the name and file system – Next– and click Format again.

Type the root (superuser) account password, and click here to start mounting. Now you can use the new volume.

If you need to format it with the terminal, type the following command:

mkfs -t ext4 /dev/vg1/lv1

Specify the file system as Ext4, the group name, and the volume name.

For mounting, type the following: mkdir /mnt/lv1, and then – mount -t ext4 /dev/vg1/lv1 /mnt/lv1.

The volume is mounted.

How to change the volume size?

One of the advantages offered by logical volumes is the opportunity to add a new hard disk on the fly and expand the volume group. And on the contrary, if there is a hard disk in the volume group which is not in use, you can remove it.

There are three main tools to make physical volumes, volume groups and logical volumes larger or smaller.

  • Resize – this command shrinks or extends physical and logical volumes, but can’t handle volume groups;
  • Extend – use it to increase logical volumes or volume groups;
  • Reduce – it can make logical volumes or volume groups smaller.

How to add a new hard disk to a volume group

The first step when you want to add a hard disk to a group is to format it. Scroll up to find a detailed explanation of this step.

After that, run the following command: vgextend vg1 /dev/sde1

where vg1 is the group name, and sde1 is the new (formatted) disk.

How to display detailed information about LVM

To display detailed information on the composition of an LVM group, run the command pvdisplay.

It displays the path to a physical disk, the name of the virtual group where it belongs, the information on the free and used disk space, disk ID and many other things.

How to remove a logical volume

To remove a logical volume, make sure that i’s disconnected (unmounted), then run the lvremove command, and the volume will be removed.

This command will help you to remove a volume group, but before that, you need to unmount the logical volume, so use another command first: umount /mnt/lv1

To proceed with removal, type this command: lvremove /dev/vg1/lv1, and type Yes to confirm this operation.

When the removal operation is successful, you’ll see this message.

Now the group can be removed, with this command: sudo vgremove vg1

Now it is time to remove all the disks that used to constitute the group; this command will do it: sudo pvremove /dev/sdb1 /dev/sdc1 /dev/sdd1

All the formatting of the physical disk is removed, and now the disk is back to its original condition.

How to recover deleted data from an LVM volume

If you accidentally removed important information from an LVM logical volume, you can still restore it with the help of Hetman Partition Recovery.

This utility supports LVM partitions and guarantees data recovery from there. It can handle most popular file systems used in Windows, Linux, Unix, and MacOS. It can ignore errors of the logical structure, scan the hard disk and restore the files you are looking for.

At the moment, there is no version of Hetman Partition Recovery for Linux. However, you can still run it with the help of a virtual machine based on Windows, install it as the secondary operating system on your PC, or connect the hard disk to another computer.

Start the program: after initialization, it recognized the logical volume without effort and now it displays all the data available on this volume.

Start with running Fast scan – right-click on the disk, Open, Fast scan – and when the scan is over, the program will display the results in the right side of the window. Removed elements are marked with a red cross.

If the Fast scan doesn’t find the data you need, then use Full analysis.

Select the files to be restored, click Recovery, choose where to save them, then click Recovery again.

When the process is over, you will find all the files in the folder you have selected.

Conclusion

In this article, we did our best to explain how to use Logical Volume Management – an integrated feature of Linux. We have reviewed all important stages: creating and configuring an LVM partition, adding and mounting new hard disks, shrinking and removing volumes. The LVM feature has been developed with servers in mind, but now you can enjoy all of its benefits on a desktop PC at home.

See the full article with all additional video tutorials.

Источник

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