Это старая версия документа.


Расширенная установка

Программный RAID

Избыточный массив независимых дисков (Redundant Array of Independent Disks, RAID) это метод использования нескольких дисков для различных сочетаний увеличения надежности хранения данных и/или увеличения производительности операций чтения/записи в зависимости от используемого уровня RAID. RAID реализуется либо на программном уровне (когда операционная система знает про оба носителя и активно их обслуживает), либо на аппаратном (когда специальный контроллер заставляет ОС думать, что существует только один носитель и обслуживает носители незаметно для системы).

ПО для работы с RAID, включенное в текущие версии Linux (и Ubuntu), основано на драйвере «mdadm» и работает очень хорошо, даже лучше чем многие, так называемые, «аппаратные» RAID контроллеры. Этот секция поможет вам установить Ubuntu Server Edition, используя два раздела RAID первого уровня, находящиеся на двух физических жестких дисках, один для / (корневого раздела), а другой для подкачки (swap).

Разметка

Следуйте инструкциям по установке пока вы не достигните этапа разметки дисков, затем:

  1. Выберите метод разметки Вручную.

  2. Выберите первый жесткий диск и согласитесь «Создать новую пустую таблицу разделов на этом устройстве?».

    Повторите этот шаг для каждого диска, который вы собираетесь включить в RAID массив.

  3. Выберите «СВОБОДНОЕ МЕСТО» на первом носителе и выберите «Создать новый раздел».

  4. Далее, выберите размер раздела. Этот раздел будет разделом подкачки, а общее правило для определения размера раздела подкачки – двойной объем RAM. Введите размер, далее выберите «Первичный», затем «Начало».

    :!: Двойной размер раздела подкачки по отношению к оперативной памяти (RAM) не всегда желателен, особенно на системах с большим объемом RAM. Расчет размера раздела подкачки в значительной степени зависит от того, как будет использоваться система.

  5. Выберите строку «Использовать как:» вверху. По умолчанию там установлено «Журналируемая файловая система Ext4», измените ее на «физический том для RAID» затем выберите «Настройка раздела закончена».

  6. Для раздела / снова выберите «СВОБОДНОЕ МЕСТО» на первом носителе и нажмите «Создать новый раздел».

  7. Используйте оставшееся свободное на носителе место и выберите «Далее», а затем «Первичный».

  8. Так же как и для раздела подкачки выберите строку «Использовать как:» вверху и измените ее на «физический том для RAID». Также поставьте отметку на строке «Загрузочный флаг:». После этого выберите «Настройка раздела закончена».

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

Настройка RAID

С разметкой разделов массив готов к настройке:

  1. Вернитесь на основную страницу «Разметка дисков», выберите «Настройка программного RAID» сверху.

  2. Выберите «да» для записи изменений на диск.

  3. Выберите «Создать MD устройство».

  4. Для этого примера выберите «RAID1», но если вы используете другую конфигурацию выберите соответствующий тип (RAID0 RAID1 RAID5).

    :!: Для использования RAID5 нужно по крайней мере три диска. Использование RAID0 или RAID1 потребует лишь двух дисков.

  5. Введите количество активных устройств равное «2», или же количество жестких дисков которые у вас выделены под массив. После этого нажмите «Далее».

  6. Далее, введите число резервных устройств «0» по умолчанию, после чего нажмите «Далее».

  7. Выберите используемые разделы. Как правило это будут sda1, sdb1, sdc1, и т.д. Цифры обычно совпадают, а разные буквы соответствуют разным жестким дискам.

    Для раздела подкачки выберите sda1 и sdb1. Нажмите «Далее» для перехода к следующему шагу.

  8. Повторите шаги с третьего по седьмой для раздела /, выбрав sda2 и sdb2.

  9. По окончании выберите «Завершить».

Форматирование

Теперь должен появиться список жестких дисков и RAID устройств. Следующим шагом является форматирование и установка точек монтирования для RAID устройств. Относитесь к RAID устройствам как к локальным жестким дискам, отформатируйте и выберите точки монтирования соответственно.

  1. Выберите «#1» под разделом «RAID1 устройство #0».

  2. Выберите «Использовать как:». Далее выберите «раздел подкачки», затем «Настройка раздела выполнена».

  3. Следующим выберите «#1» под разделом «RAID1 устройство #1».

  4. Выберите «Использовать как:». Далее выберите «Журналируемая файловая система Ext4».

  5. Затем выберите «Точка подключения:» и выберите « / – корневая файловая система». Измените все необходимые опции и выберите «Настройка раздела выполнена».

  6. Ну и наконец, выберите «Завершить разметку и записать изменения на диск».

Если вы разместили корневой раздел на RAID массиве, установщик спросит хотите ли вы загружать систему в состоянии пониженной работоспособности. Более подробную информацию читайте в разделе Поврежденный RAID.

Далее процесс установки продолжится как обычно.

Поврежденный RAID

В определенный момент работы компьютера вы можете столкнуться с отказом диска. Когда это случится, при использовании программного RAID, операционная система переведет массив в режим пониженной работоспособности (degraded state).

Если массив поврежден, в связи с возможностью потери данных, по-умолчанию Ubuntu Server Edition запустит начальный загрузчик через 30 секунд. Как только загрузчик стартует, появится предупреждение на 50 секунд с выбором либо продолжить и загрузить систему, либо сделать попытку восстановления вручную. Запуск загрузчика с предупреждением может быть как желательным, так и нет, особенно если это удаленный компьютер. Загрузка с поврежденным массивом может быть настроена по-разному:

  • Утилита dpkg-reconfigure может быть использована для настройки желательного варианта по-умолчанию и в процессе у вас будет возможность задать дополнительные настройки, связанные с массивом. Таких, как слежение, почтовые предупреждения и пр. Для перенастройки mdadm введите следующее:
sudo dpkg-reconfigure mdadm
  • Команда sudo dpkg-reconfigure mdadm изменит конфигурационный файл /etc/initramfs-tools/conf.d/mdadm. У этого файла есть возможность предварительной настройки желаемого поведения системы и он может быть отредактирован вручную:
BOOT_DEGRADED=true
Конфигурационный файл может быть проигнорирован при использовании параметров ядра
  • Использование параметра ядра также позволит загрузиться системе с поврежденным массивом:
    1. Когда сервер стартует, нажмите Shift для выхода в меню GRUB.
    2. Нажмите «e» для редактирования опций загрузки ядра.
    3. Клавишей курсор вниз подсветите строку ядра.
    4. Добавьте «bootdegraded=true» (без кавычек) в конец строки.
    5. Нажмите Ctrl-x для загрузки системы.

Once the system has booted you can either repair the array see RAID Maintenance for details, or copy important data to another machine due to major hardware failure.

RAID Maintenance

The mdadm utility can be used to view the status of an array, add disks to an array, remove disks, etc:

To view the status of an array, from a terminal prompt enter:

sudo mdadm -D /dev/md0 The -D tells mdadm to display detailed information about the /dev/md0 device. Replace /dev/md0 with the appropriate RAID device.

To view the status of a disk in an array:

sudo mdadm -E /dev/sda1 The output if very similar to the mdadm -D command, adjust /dev/sda1 for each disk.

If a disk fails and needs to be removed from an array enter:

sudo mdadm –remove /dev/md0 /dev/sda1 Change /dev/md0 and /dev/sda1 to the appropriate RAID device and disk.

Similarly, to add a new disk:

sudo mdadm –add /dev/md0 /dev/sda1 Sometimes a disk can change to a faulty state even though there is nothing physically wrong with the drive. It is usually worthwhile to remove the drive from the array then re-add it. This will cause the drive to re-sync with the array. If the drive will not sync with the array, it is a good indication of hardware failure.

The /proc/mdstat file also contains useful information about the system's RAID devices:

cat /proc/mdstat Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] md0 : active raid1 sda1[0] sdb1[1]

    10016384 blocks [2/2] [UU]
    

unused devices: <none> The following command is great for watching the status of a syncing drive:

watch -n1 cat /proc/mdstat Press Ctrl+c to stop the watch command.

If you do need to replace a faulty drive, after the drive has been replaced and synced, grub will need to be installed. To install grub on the new drive, enter the following:

sudo grub-install /dev/md0 Replace /dev/md0 with the appropriate array device name.

Resources

The topic of RAID arrays is a complex one due to the plethora of ways RAID can be configured. Please see the following links for more information:

Ubuntu Wiki Articles on RAID.

Software RAID HOWTO

Managing RAID on Linux

Logical Volume Manager (LVM) Logical Volume Manger, or LVM, allows administrators to create logical volumes out of one or multiple physical hard disks. LVM volumes can be created on both software RAID partitions and standard partitions residing on a single disk. Volumes can also be extended, giving greater flexibility to systems as requirements change.

Overview

A side effect of LVM's power and flexibility is a greater degree of complication. Before diving into the LVM installation process, it is best to get familiar with some terms.

Physical Volume (PV): physical hard disk, disk partition or software RAID partition formatted as LVM PV.

Volume Group (VG): is made from one or more physical volumes. A VG can can be extended by adding more PVs. A VG is like a virtual disk drive, from which one or more logical volumes are carved.

Logical Volume (LV): is similar to a partition in a non-LVM system. A LV is formatted with the desired file system (EXT3, XFS, JFS, etc), it is then available for mounting and data storage.

Installation

As an example this section covers installing Ubuntu Server Edition with /srv mounted on a LVM volume. During the initial install only one Physical Volume (PV) will be part of the Volume Group (VG). Another PV will be added after install to demonstrate how a VG can be extended.

There are several installation options for LVM, «Guided - use the entire disk and setup LVM» which will also allow you to assign a portion of the available space to LVM, «Guided - use entire and setup encrypted LVM», or Manually setup the partitions and configure LVM. At this time the only way to configure a system with both LVM and standard partitions, during installation, is to use the Manual approach.

Follow the installation steps until you get to the Partition disks step, then:

At the «Partition Disks screen choose «Manual».

Select the hard disk and on the next screen choose «yes» to «Create a new empty partition table on this device».

Next, create standard /boot, swap, and / partitions with whichever filesystem you prefer.

For the LVM /srv, create a new Logical partition. Then change «Use as» to «physical volume for LVM» then «Done setting up the partition».

Now select «Configure the Logical Volume Manager» at the top, and choose «Yes» to write the changes to disk.

For the «LVM configuration action» on the next screen, choose «Create volume group». Enter a name for the VG such as vg01, or something more descriptive. After entering a name, select the partition configured for LVM, and choose «Continue».

Back at the «LVM configuration action» screen, select «Create logical volume». Select the newly created volume group, and enter a name for the new LV, for example srv since that is the intended mount point. Then choose a size, which may be the full partition because it can always be extended later. Choose «Finish» and you should be back at the main «Partition Disks» screen.

Now add a filesystem to the new LVM. Select the partition under «LVM VG vg01, LV srv», or whatever name you have chosen, the choose Use as. Setup a file system as normal selecting /srv as the mount point. Once done, select «Done setting up the partition».

Finally, select «Finish partitioning and write changes to disk». Then confirm the changes and continue with the rest of the installation.

There are some useful utilities to view information about LVM:

pvdisplay: shows information about Physical Volumes.

vgdisplay: shows information about Volume Groups.

lvdisplay: shows information about Logical Volumes.

Extending Volume Groups

Continuing with srv as an LVM volume example, this section covers adding a second hard disk, creating a Physical Volume (PV), adding it to the volume group (VG), extending the logical volume srv and finally extending the filesystem. This example assumes a second hard disk has been added to the system. In this example, this hard disk will be named /dev/sdb and we will use the entire disk as a physical volume (you could choose to create partitions and use them as different physical volumes)

Make sure you don't already have an existing /dev/sdb before issuing the commands below. You could lose some data if you issue those commands on a non-empty disk.

First, create the physical volume, in a terminal execute:

sudo pvcreate /dev/sdb

Now extend the Volume Group (VG):

sudo vgextend vg01 /dev/sdb Use vgdisplay to find out the free physical extents - Free PE / size (the size you can allocate). We will assume a free size of 511 PE (equivalent to 2GB with a PE size of 4MB) and we will use the whole free space available. Use your own PE and/or free space.

The Logical Volume (LV) can now be extended by different methods, we will only see how to use the PE to extend the LV:

sudo lvextend /dev/vg01/srv -l +511 The -l option allows the LV to be extended using PE. The -L option allows the LV to be extended using Meg, Gig, Tera, etc bytes.

Even though you are supposed to be able to expand an ext3 or ext4 filesystem without unmounting it first, it may be a good practice to unmount it anyway and check the filesystem, so that you don't mess up the day you want to reduce a logical volume (in that case unmounting first is compulsory).

The following commands are for an EXT3 or EXT4 filesystem. If you are using another filesystem there may be other utilities available.

sudo umount /srv sudo e2fsck -f /dev/vg01/srv The -f option of e2fsck forces checking even if the system seems clean.

Finally, resize the filesystem:

sudo resize2fs /dev/vg01/srv Now mount the partition and check its size.

mount /dev/vg01/srv /srv && df -h /srv Resources

See the Ubuntu Wiki LVM Articles.

See the LVM HOWTO for more information.

Another good article is Managing Disk Space with LVM on O'Reilly's linuxdevcenter.com site.

For more information on fdisk see the fdisk man page.