What is linux device mapper

Device-mapper и DM-multipath

В статье про настройку iSCSI LUN на NetApp была затронута тема многоканальности (multipathing). Напомню, что это побочное явления использования нескольких физических каналов между целевым сетевым хранилищем данных (СХД) и сервером-инициатором, свойственное всем блочным протоколам. При наличии нескольких путей до инициатора, презентованный ему LUN (Logical Unit Number) будет виден столько раз, сколько существует путей. Поэтому прибегают к помощи вспомогательных средств для группирования всех этих «фантомных» LUN в единственный. В Windows это делается средствами MPIO, в Linux – демоном multipathd, который является компонентом device-mapper, именно о последних двух и пойдет речь в данной статье.

Device-Mapper

Device-mapper является частью ядра Linux, и основным его назначением является трансляция (mapping) одного блочного устройства в другое. На основе device-mapper строятся такие системы как LVM2, софтовый RAID и др. Device-mapper представляет некое «виртуальное» блочное устройство, и все данные, которые проходят через него, он посылает на другое, уже «реальное» блочное устройство.

Это виртуальное блочное устройство представляет собой таблицу, в которой описывается проброс каждого логического блока этого устройства на реальные физические блочные устройства.

При ссылке на «реальное» блочное устройство DM может использовать как его имя, отображаемое в файловой системе (/dev/sda), так и старший (major) и младший (minor) номера устройства в формате major:minor.

Общий вид строки в таблице преобразования:

  • start – начальный блок виртуального устройства
  • length – длина сегмента
  • type – тип преобразования. Бывают: linear, striped (позволяет пробрасывать виртуальное устройство на несколько физических), mirror, snapshot (используется для создания снимка тома диска), error, zero, multipath, crypt
  • device – название физического устройства
  • offset – отступ в физическом устройстве

Пример строки линейного преобразования с 0-го блока виртуального устройства, сегмента длиною 1638400 в физическое устройство со старшим номером 8, младшим номером 2 и отступом на нем в 41146992.

В зависимости от типа преобразования в строке могут появляться дополнительные параметры.

При создании снимка тома диска средствами LVM используются четыре устройства Device Mapper:

  1. Устройство с linear-типом, хранящее первоначальную таблицу преобразования тома.
  2. Устройство с linear-типом для использования в качестве Copy-on-Write устройства – перед каждой записью на том, первоначальные данные будут сохраняться на CoW устройстве.
  3. Устройство со snapshot-типом хранящую таблицу преобразования из комбинаций первого и второго устройств и видного, как снимок, тома.
  4. «Первоначальный» том (использующий номер устройства первоначального тома источника) чья таблица преобразования заменяется на «snapshot-mapping» из первого устройства.

Пример создания LVM тома BASE и snapshot-подтома SNAP на этом томе

Что в свою очередь создает четыре устройства, которые можно посмотреть

Device-Mapper Multipath

Device mapper multipath (DM-Multipath) позволяет сгруппировать несколько путей между сервером и хранилищем (multipathing — многоканальность) в одно устройство.

При настройке активный/пассивный многоканальность позволяет избежать прерывания в работе при выходе из строя одного из путей (кабеля, свитча, контроллера). В этом режиме используется только половина путей.

При настройке активный/активный задействуются все доступные пути по карусельному алгоритму

Идентификаторы многоканальных устройств

Каждой многоканальное устройство (СХД) имеет т.н. World Wide Identifier (WWID), уникальный глобальный идентификатор. На его основании и делается предположение, о единстве LUN, доступного по множеству путей.

Например, сервер с двумя HBA (адаптер для подключения к FC сети) подключенный через FC свитч к СХД с двумя портами, при презентации ему одного LUN на этой СХД увидит четыре устройства: /dev/sda, /dev/sdb, dev/sdc, and /dev/sdd. DM-Multipath создаст одно «виртуальное» устройство с уникальным WWID.

Создаваемые DM-Multipath «виртуальные» устройства находятся в двух местах:

  • /dev/mapper – каталог, используемый непосредственно для создания логических томов;
  • /dev/dm-n устройства, используемые системой для внутренних нужд.

После создания виртуальных устройств средствами DM-Multipath можно приступить к созданию физических томов LVM (Physical volume LVM). Стоить отметить, что использование LVM необязательно и можно форматировать виртуальные устройства fdisk’ом, но это крайне не рекомендуется, т.к. внесет еще большую сумятицу.

RedHat отмечает, что для создания физических томов LVM на диске не должно быть разделов.
При создании логических томов LVM (Logical volume LVM) на СХД, подключенных несколькими путями по схеме активный/пассивный необходимо отредактировать файл настроек LVM (/etc/lvm.conf) для исключения дисков на которые ссылаются «виртуальные» устройства, созданные DM-Pathing. Чтобы это сделать, достаточно внести фильтр все SCSI устройств в файл lvm.conf:

  • dm_multipath – модуль ядра
  • mpathconf – утилита для настройки многоканальности
  • multipath – утилита для отображения и настройки многоканальных устройств
  • multipathd – демон, следящий за доступностью путей
  • kpartx – утилита создает «виртуальные» устройства для DOS-разделов
Читайте также:  Ошибка при запуске приложения 0xc00000e5 windows 10 как исправить

Процесс подготовки DM-Multipath на RedHat/CentOS

  1. Установка device-mapper-multipath пакета.
  2. Изменение настроек по умолчанию в файле /etc/multipath.conf на необходимые. По умолчанию DM-Multipath включает в себя настройки для большинства СХД таким образом, что при его работе виртуальные устройства будут называться опознаваемо.
  3. Запуск демона multipathd

Установка и настройка Device Mapper Multipath для NetApp

  1. Проверяем наличие установленных пакетов DM и DM-Multipath

И устанавливаем device-mapper-multipath из репозитория вашей ОС, если его нет.
Редактируем /etc/multipath.conf и приводим его к желаемому виду

Конфигурационный файл DM-Multipath состоит из сл. секций:

  • blacklist – список игнорируемых устройств (по wwid и/или по имени устройства (devnode))
  • blacklist_exceptions – список исключений из списка игнора
  • defaults – общие настройки
  • multipaths – список устройств с особыми настройками (имеет приоритет над defaults и devices)
  • devices – настройки отдельных СХД с подсекциями для каждой из них (имеет приоритет над defaults)

Примеры multipath.conf для NetApp и RedHat различных версий

  • RedHat 6 with ALUA
    defaults <
    user_friendly_names no
    max_fds max
    flush_on_last_del yes
    queue_without_daemon no
    >
    blacklist <
    devnode «^hd[a-z]»
    devnode «^(ram|raw|loop|fd|md|dm-|sr|scd|st)3*»
    devnode «^cciss.*»
    >
    devices <
    device <
    vendor «NETAPP»
    product «LUN»
    path_grouping_policy group_by_prio
    features «1 queue_if_no_path»
    prio «alua»
    path_checker directio
    failback immediate
    path_selector «round-robin 0»
    hardware_handler «1 alua»
    rr_weight uniform
    rr_min_io 128
    getuid_callout «/lib/udev/scsi_id -g -u -d /dev/%n»
    >
    >
  • RedHat 5 Update 7 with ALUA
    defaults <
    user_friendly_names no
    queue_without_daemon no
    flush_on_last_del yes
    max_fds max
    pg_prio_calc avg
    >
    blacklist <
    devnode «^hd[a-z]»
    devnode «^(ram|raw|loop|fd|md|dm-|sr|scd|st)8*»
    devnode «^cciss.*»
    >
    devices <
    device <
    vendor «NETAPP»
    product «LUN»
    path_grouping_policy group_by_prio
    features «1 queue_if_no_path»
    prio_callout «/sbin/mpath_prio_alua /dev/%n»
    path_checker directio
    path_selector «round-robin 0»
    failback immediate
    hardware_handler «1 alua»
    rr_weight uniform
    rr_min_io 128
    getuid_callout «/sbin/scsi_id -g -u -s /block/%n»
    >
    >
  • RedHat 5 Update 7 without ALUA
    defaults <
    user_friendly_names no
    queue_without_daemon no
    flush_on_last_del yes
    max_fds max
    pg_prio_calc avg
    >
    blacklist <
    devnode «^hd[a-z]»
    devnode «^(ram|raw|loop|fd|md|dm-|sr|scd|st)1*»
    devnode «^cciss.*»
    >
    devices <
    device <
    vendor «NETAPP»
    product «LUN»
    path_grouping_policy group_by_prio
    features «1 queue_if_no_path»
    prio_callout «/sbin/mpath_prio_ontap /dev/%n»
    path_checker directio
    path_selector «round-robin 0»
    failback immediate
    hardware_handler «0»
    rr_weight uniform
    rr_min_io 128
    getuid_callout «/sbin/scsi_id -g -u -s /block/%n»
    >
    >

Источник

Beginners guide to Device Mapper (DM) multipathing

Multipathing Overview

A path is a connection between a server and the underlying storage. The path can be severed due to many reasons like faulty HBA, faulty cable etc. To avoid such single point of failures, multipathing exists. Multipathing ensures that the system uses multiple physical paths to provide redundancy and increased throughput. There are many vendor specific multipathing implementations like EMC’s powerpath and Symantecs VxDMP.

What is Device Mapper multipath

Device Mapper Multipathing (or DM-multipathing) is a Linux native multipath tool, which allows you to configure multiple I/O paths between server nodes and storage arrays into a single device. These I/O paths are physical SAN connections that can include separate cables, switches, and controllers. Multipathing aggregates the I/O paths, creating a new device that consists of the aggregated paths. Regardless of the vendor hardware in use, device mapper creates a block device under /dev/mapper/ for each LUN attached to the system.

Device Mapper components
The important components of Device Mapper multipathing are :

Component Description
dm-multipath kernel module responsible for making routing decisions under normal/failure conditions
multipath Command used for viewing/listing multipath devices and for initial configuration
multipathd daemon that moitors path, marks failed paths, reactivates restored paths, adds/removes device files as needed.
kpartx command used to create device mapper entries for partitions on multipathed LUN. It is invoked automatically when multipath command is used.

How to verify if DMMP is installed and configured

1. Check whether device-mapper is installed.

2. Check that the following device mapper modules are loaded.

3. If above conditions are met, check whether the file /etc/multipath.conf is configured. Make sure the lines in bold are commented out in order to enable device mapper.

4. Check whether multipathd is running.

5. If yes, check any devices listed using the command below.

If all the above steps succeed, the system is configured for DMMP.

Multipathing Configuration

Before starting to configure the multipathing, make sure the device-mapper-multipath package is installed. If not installed, install it using yum :

The device mapper multipathing uses the configuration file /etc/multipath.conf for the configuration. If you make any changes to this file the multipath command must be run in order to reconfigure the multipathed devices. The easiest way to create this file is to use the mpathconf utility. If there is an existing configuration file mpathconf will edit it, if no such file exists it will copy /usr/share/doc/device-mapper-multipath-*/multipath.conf.

The configuration file consists of 5 major sections as below :

Section Description
defaults system-level default configuration
blacklist Blacklisted devies. Devices that should not be configured under DMMP
blacklist_exceptions Exceptions to the blacklisted devices
devices settings for individual storage controller devices
multipaths fine-tune configuration of individual LUNs
Читайте также:  Any to epub mac os

Verifying Configuration

The multipath command can be used to verify the multipathinf configuration. To list the information about multipathed devices :

The output shows a multipathed LUN, mpath0. The number following it is the LUN’s WWID. The status active/ready indicates that the path is ready for I/O. If the path is showing faulty/failed then it needs to be repaired before using it for I/O. After the configuration is completed, we can start the multipathd persistently :

User Friendly Device Names

In order to troubleshoot efficiently, device-mapper can be configured to have human readable, user friendly device names under /dev/mapper instead of using the WWIDs. The user friendly names like /dev/mapper/mpath0 can be created by enabling the user_friendly_names option in /etc/multipath.conf file :

You can also control the name for a particular LUN by using the alias option :

Removing Multipath

After removing the all the paths for a multipathed device, run the below command to remove the multipath device completely :

To flush all the multipathed device after stopping the multipahtd daemon :

Источник

Use the Device Mapper storage driver

Estimated reading time: 28 minutes

Device Mapper is a kernel-based framework that underpins many advanced volume management technologies on Linux. Docker’s devicemapper storage driver leverages the thin provisioning and snapshotting capabilities of this framework for image and container management. This article refers to the Device Mapper storage driver as devicemapper , and the kernel framework as Device Mapper.

For the systems where it is supported, devicemapper support is included in the Linux kernel. However, specific configuration is required to use it with Docker.

The devicemapper driver uses block devices dedicated to Docker and operates at the block level, rather than the file level. These devices can be extended by adding physical storage to your Docker host, and they perform better than using a filesystem at the operating system (OS) level.

Prerequisites

  • devicemapper is supported on Docker Engine — Community running on CentOS, Fedora, SLES 15, Ubuntu, Debian, or RHEL.
  • devicemapper requires the lvm2 and device-mapper-persistent-data packages to be installed.
  • Changing the storage driver makes any containers you have already created inaccessible on the local system. Use docker save to save containers, and push existing images to Docker Hub or a private repository, so you do not need to recreate them later.

Configure Docker with the devicemapper storage driver

Before following these procedures, you must first meet all the prerequisites.

Configure loop-lvm mode for testing

This configuration is only appropriate for testing. The loop-lvm mode makes use of a ‘loopback’ mechanism that allows files on the local disk to be read from and written to as if they were an actual physical disk or block device. However, the addition of the loopback mechanism, and interaction with the OS filesystem layer, means that IO operations can be slow and resource-intensive. Use of loopback devices can also introduce race conditions. However, setting up loop-lvm mode can help identify basic issues (such as missing user space packages, kernel drivers, etc.) ahead of attempting the more complex set up required to enable direct-lvm mode. loop-lvm mode should therefore only be used to perform rudimentary testing prior to configuring direct-lvm .

Edit /etc/docker/daemon.json . If it does not yet exist, create it. Assuming that the file was empty, add the following contents.

See all storage options for each storage driver in the daemon reference documentation

Docker does not start if the daemon.json file contains badly-formed JSON.

Verify that the daemon is using the devicemapper storage driver. Use the docker info command and look for Storage Driver .

This host is running in loop-lvm mode, which is not supported on production systems. This is indicated by the fact that the Data loop file and a Metadata loop file are on files under /var/lib/docker/devicemapper . These are loopback-mounted sparse files. For production systems, see Configure direct-lvm mode for production.

Configure direct-lvm mode for production

Production hosts using the devicemapper storage driver must use direct-lvm mode. This mode uses block devices to create the thin pool. This is faster than using loopback devices, uses system resources more efficiently, and block devices can grow as needed. However, more setup is required than in loop-lvm mode.

After you have satisfied the prerequisites, follow the steps below to configure Docker to use the devicemapper storage driver in direct-lvm mode.

Warning: Changing the storage driver makes any containers you have already created inaccessible on the local system. Use docker save to save containers, and push existing images to Docker Hub or a private repository, so you do not need to recreate them later.

Allow Docker to configure direct-lvm mode

Docker can manage the block device for you, simplifying configuration of direct-lvm mode. This is appropriate for fresh Docker setups only. You can only use a single block device. If you need to use multiple block devices, configure direct-lvm mode manually instead. The following new configuration options are available:

Читайте также:  Информация при загрузке windows
Option Description Required? Default Example
dm.directlvm_device The path to the block device to configure for direct-lvm . Yes В dm.directlvm_device=»/dev/xvdf»
dm.thinp_percent The percentage of space to use for storage from the passed in block device. No 95 dm.thinp_percent=95
dm.thinp_metapercent The percentage of space to use for metadata storage from the passed-in block device. No 1 dm.thinp_metapercent=1
dm.thinp_autoextend_threshold The threshold for when lvm should automatically extend the thin pool as a percentage of the total storage space. No 80 dm.thinp_autoextend_threshold=80
dm.thinp_autoextend_percent The percentage to increase the thin pool by when an autoextend is triggered. No 20 dm.thinp_autoextend_percent=20
dm.directlvm_device_force Whether to format the block device even if a filesystem already exists on it. If set to false and a filesystem is present, an error is logged and the filesystem is left intact. No false dm.directlvm_device_force=true

Edit the daemon.json file and set the appropriate options, then restart Docker for the changes to take effect. The following daemon.json configuration sets all of the options in the table above.

See all storage options for each storage driver in the daemon reference documentation

Restart Docker for the changes to take effect. Docker invokes the commands to configure the block device for you.

Warning: Changing these values after Docker has prepared the block device for you is not supported and causes an error.

Configure direct-lvm mode manually

The procedure below creates a logical volume configured as a thin pool to use as backing for the storage pool. It assumes that you have a spare block device at /dev/xvdf with enough free space to complete the task. The device identifier and volume sizes may be different in your environment and you should substitute your own values throughout the procedure. The procedure also assumes that the Docker daemon is in the stopped state.

Identify the block device you want to use. The device is located under /dev/ (such as /dev/xvdf ) and needs enough free space to store the images and container layers for the workloads that host runs. A solid state drive is ideal.

Install the following packages:

RHEL / CentOS: device-mapper-persistent-data , lvm2 , and all dependencies

Ubuntu / Debian / SLES 15: thin-provisioning-tools , lvm2 , and all dependencies

Create a physical volume on your block device from step 1, using the pvcreate command. Substitute your device name for /dev/xvdf .

Warning: The next few steps are destructive, so be sure that you have specified the correct device!

Create a docker volume group on the same device, using the vgcreate command.

Create two logical volumes named thinpool and thinpoolmeta using the lvcreate command. The last parameter specifies the amount of free space to allow for automatic expanding of the data or metadata if space runs low, as a temporary stop-gap. These are the recommended values.

Convert the volumes to a thin pool and a storage location for metadata for the thin pool, using the lvconvert command.

Configure autoextension of thin pools via an lvm profile.

Specify thin_pool_autoextend_threshold and thin_pool_autoextend_percent values.

thin_pool_autoextend_threshold is the percentage of space used before lvm attempts to autoextend the available space (100 = disabled, not recommended).

thin_pool_autoextend_percent is the amount of space to add to the device when automatically extending (0 = disabled).

The example below adds 20% more capacity when the disk usage reaches 80%.

Apply the LVM profile, using the lvchange command.

Ensure monitoring of the logical volume is enabled.

If the output in the Monitor column reports, as above, that the volume is not monitored , then monitoring needs to be explicitly enabled. Without this step, automatic extension of the logical volume will not occur, regardless of any settings in the applied profile.

Double check that monitoring is now enabled by running the sudo lvs -o+seg_monitor command a second time. The Monitor column should now report the logical volume is being monitored .

If you have ever run Docker on this host before, or if /var/lib/docker/ exists, move it out of the way so that Docker can use the new LVM pool to store the contents of image and containers.

Источник

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