ISCSI target на ubuntu

Автор George, Окт. 02, 2022, 06:55

« назад - далее »

George

Начиная с Debian 9 Stretch и Ubuntu 18.04 LTS пакет iSCSI Enterprise Target (iscsitarget) был удален и ему на смену пришел Linux SCSI target (tgt), работу с которым мы и будем рассматривать. Все указанные ниже команды следует вводить с правами суперпользователя или используя sudo. В нашем случае использовалась OC Debian 10, но все сказанное будет справедливо для любого основанного на нем дистрибутива, а с некоторыми поправками для любых Linux-систем.

Прежде всего установим Linux SCSI target, не забыв перед этим обновить список пакетов:

Код: bash
apt update
Код: bash
apt install tgt

Серверная часть в iSCSI называется порталом, который содержит цели (таргет, Target), каждая из которых предоставляет клиенту - инициатору (Initiator) доступ к одному или нескольким блочным устройствам. В качестве блочных устройств могут использоваться физические диски, логические тома, файлы (виртуальные диски) и т.д. и т.п. В нашем примере мы будем использовать файл. На наш взгляд это наиболее удобно, так как позволяет достаточно гибко управлять системой хранения - файлы виртуальных дисков можно легко перемещать между серверами или физическими дисками, а также управлять их размерами.

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

Какой же тип выбрать? Здесь все зависит от решаемых задач, если вы заранее знаете объем хранимых данных, и он не будет существенно изменяться - то выбирайте диск фиксированного размера, в иных случаях более предпочтителен динамический диск, как позволяющий более оптимально использовать дисковое пространство.

Для хранения файлов виртуальных дисков мы будем условно использовать директорию /storage, поэтому вам потребуется откорректировать пути в соответствии с реальным расположением данных.

Для создания диска фиксированного размера используйте команду:

Код: bash
dd if=/dev/zero of=/storage/lun0.img bs=1M count=2048

Она создаст файл размером 2 ГБ, так как мы указали размер блока - bs - равным 1 MБ и количество таких блоков - count - 2048.

Для создания динамического диска:

Код: bash
dd if=/dev/zero of=/storage/lun0.img bs=1 count=0 seek=200G

Данная команда создает разреженный файл с максимальным размером 200 ГБ, разреженными называются файлы, которые вместо последовательности нулей на диске хранят информацию об этих последовательностях в специальной таблице.

Для преобразования обычного файла в разреженный выполните команду:

Код: bash
cp --sparse=always filename newfilename
- Не пробовал, как создал размером с диск.

Где filename и newfilename - старое и новое имя файла.

Будем считать, что файлы виртуальных дисков вами созданы и перейдем к настройке Linux SCSI target. Для этого перейдем в /etc/tgt где мы увидим файл targets.conf и директорию conf.d. Предполагается что для каждой цели мы будем использовать отдельный конфигурационный файл, которые следует снабдить расширением .conf и размещать в указанной директории.

Следует помнить, что так как iSCSI-диск является аналогом обычного диска, то с одной целью может работать только один инициатор, исключение - кластерные системы, где одна цель может быть сразу подключена к нескольким узлам.

Создадим новый файл конфигурации:

Код: bash
nano /etc/tgt/conf.d/debain-test.conf

и внесем в него следующее содержимое:

Код: xml
<target iqn.2009-02.lab.interface31:deban-test-target> 
  backing-store /storage/lunO.img 
  initiator-address 192.168.111.150
  incominguser andrey secretpass12
</target>

В начале секции после директивы target указывается IQN - полностью определенное имя цели, которое имеет следующий формат:

iqn.<year-mo>.<reversed_domain_name>:<unique_name>

где:

    year-mo - год и месяц регистрации домена
    reversed_domain_name - доменное имя, записанное в обратном порядке
    unique_name - уникальное имя цели

Внутри секции цели мы указали следующие опции:

    backing-store - указывает путь к блочному устройству или файлу
    initiator-address - IP-адрес инициатора, , если он не указан, то доступ сможет получить любое устройство.
    incominguser - имя пользователя и пароль, необязательная опция, используется для дополнительной безопасности, по требованию стандарта длина пароля должна быть равна 12 символам.

Если вы хотите предоставлять в одной цели два и более блочных устройства, то для каждого из них добавьте отдельной строкой опцию backing-store, это же касается и initiator-address, их тоже можно указать несколько.

Сохраним файл конфигурации и перезапустим службу Linux SCSI target:

Код: bash
service tgt restart

Проверить работу портала можно командой:

Код: bash
tgtadm --mode target --op show

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

На этом настройку цели можно считать законченной. Как видим, никаких особых сложностей в создании iSCSI хранилища в Linux-системах нет.
  •  

George

#1
Но как оказалось, сложности еcть. Первая из них, что scsi id у дисков получается одинаков. И vCenter не видит диск, который пытаешься подключить вторым. Поиски дали не слишком много, примеров не было с нужным параметром, а на одном англоязычном форуме - вообще дебри. Помогла мне вот такая статья, ее копий достаточно много в инете (штуки 3 видел)

targets.conf(5) - Linux man page
Name

targets.conf - Linux SCSI Target Configuration File
Description

tgt-admin uses /etc/tgt/targets.conf to initialize tgtd configuration, by default. Its layout uses a HTML-like structure, with a hierarchy of nested tags to define targets and LUNs.
Configuration File Syntax

Global directives configure options that are global to tgtd's configuration, as well as defining exported targets, via target sections.

Target sections contain directives specific to one target device. They define each target's exported LUNs via "backing-store" and "direct-store" directives, as well as other target-wide options.

LUN directives ("backing-store" and "direct-store") may contain options specific to a single exported logical unit.
Global Directives

With the exception of target directives, each of these should occur at most once.

<target <IQN>>

    Defines a the start of a target definition. IQN is an ISCSI Qualified Name such as "iqn.2001-04.com.example:storage1". See "ISCSI" on Wikipedia for more information on IQNs.

    Within this block should be target-level directives, as documented below.

    The target definition ends with "</target>"
default-driver <lld>
    Instead of specifying a driver type for each target, default-driver defines a default low-level driver for all exported targets. It may be overriden on a per-target basis. Valid lld values are "iscsi" or "iser". Since iscsi is assumed if this directive is not present, it is only generally needed if iser is the desired default.
include <path>
    Include the configuration from another configuration file. Wildcards are allowed, so an example like "include /etc/tgt/xen/*.conf" is allowed.
ignore-errors yes
    Errors from tgtadm will be ignored. Default is no.
control-port <port>
    Define a different local socket key for communicating with tgtd. Defaults to 0. This is only generally useful if multiple instances of tgtd are in use.
iSNSServerIP <addr>
    Define the address of the iSNS server in IPv4 dotted-quad address format. Required when using iSNS, otherwise ignored.
iSNSAccessControl <value>
    Set iSNS access control. Valid values are "On" or "Off". Required when using iSNS, otherwise ignored.
iSNSServerPort <port>
    Set a different iSNS server port. Default is 3205. Optional when using iSNS, otherwise ignored.
iSNS On
    Enable iSNS. Only valid value is "On". Default is off.
incomingdiscoveryuser <user> <userpassword>
    Define iscsi incoming discovery authentication setting. If no value is given, no authentication is performed.
outgoingdiscoveryuser <user> <userpassword>
    Define iscsi outgoing discovery authentication setting. If no value is given, no authentication is performed.

Target-level Directives

Each target may export multiple block devices, or logical units (LUNs). For the purposes of LUN numbering, backing-store directives are processed before direct-store directives.

backing-store <path>

    Defines a logical unit (LUN) exported by the target. This may specify either a regular file, or a block device.
direct-store <path>
    Defines a direct mapped logical unit (LUN) with the same properties as the physical device (such as VENDOR_ID, SERIAL_NUM, etc.)
driver <lld>
    Define the low-level driver to use for this target, either "iscsi" or "iser" (without quotes). This overrides the "default-driver" global directive.
initiator-address <addr>
    Allows connections only from the specified IP address. Defaults to ALL if no initiator-address directive is specified.
initiator-name <addr>
    Allows connections only from the specified initiator name.
incominguser <user> <userpassword>
    Define iscsi incoming authentication setting. If no "incominguser" is specified, it is not used. This directive may be used multiple times per target.
outgoinguser <user> <userpassword>
    Define iscsi outgoing authentication setting. If no "outgoinguser" is specified, it is not used. This directive may be used multiple times per target.
controller_tid <val>
    Define the tid of the controller. Default is next available integer.

Lun-level Directives

All of these may be listed at the target level (and apply to all LUNs) or within an individual LUN's definition, if it is defined using the container-style, multi-line definition, rather than single-line definition format:

    <backing-store /dev/sdb1>
      # LUN directives go here
    </backing-store>

    <direct-store /dev/sdb1>
      # LUN directives go here
    </direct-store>

It is recommended to use either single-line or container-style LUN definitions within a target. Mixing styles can cause parser errors.

write-cache <val>
    "on" or "off", default on.
scsi_id <val>
scsi_sn <val>
vendor_id <val>
product_id <val>
product_rev <val>
sense_format <val>
removable <val>
path <val>
mode_page <val>
readonly <val>
device-type <val>
bs-type <val>
allow-in-use <val>
block-size <val>
    Specify the block size for this LUN.
lbppbe <val>
    Specify the Logical blocks per physical block exponent. This is an internal option that should not be set directly.
la_lba <val>
    Specify the lowest aligned logical block address. This is an internal option that should not be set directly.
optimal_xfer_gran <val>
    Specify the optimal transfer granularity, to be reflected in the Block Limits VPD. This is an internal option that should not be set directly.
optimal_xfer_len <val>
    Specify the optimal transfer length, to be reflected in the Block Limits VPD. This is an internal option that should not be set directly.
params <vals>
    Pass additional parameters to tgtadm.

Configuration File Example

Example configuration file:

<target iqn.2007-04.com.example:san.monitoring>
  backing-store /dev/san/monitoring

 # if no "incominguser" is specified, it is not used
  incominguser backup secretpass12

 # defaults to ALL if no "initiator-address" is specified
  initiator-address 192.168.1.2
</target>

<target iqn.2007-02.com.example:san.xen1>
  backing-store /dev/san/xen1-disk1 # LUN1
  direct-store /dev/san/xen1-disk2  # LUN2

 initiator-address 192.168.1.2     # Allowed IP
  initiator-address 192.168.5.6     # Allowed IP

 incominguser user1 secretpass12
  incominguser user2 secretpass23

 outgoinguser userA secretpassA
</target>

<target iqn.2007-02.com.example:san.xen2>
  backing-store /dev/san/xen2
</target>

<target iqn.2007-06.com.example:san.vmware1>
  backing-store /dev/san/vmware1
</target>

Files

/etc/tgt/targets.conf

    Configuration file for tgt-admin.
/usr/share/doc/tgt/targets.conf.example
    Example configuration file for tgt-admin.


Здесь я увидел параметры scsi id и еще пару)) Они мне и помогли:

Код: bash
<target iqn.2022-10.site.im-cloud:esx2-iscsi>
  <backing-store /iscsi/lun1.img>
      vendor_id  G_K_A
      product_id   Target-esx2
      scsi_id GKA     00010002
  </backing-store>
   initiator-address 192.168.xx.xz
   initiator-address 192.168.xx.xy
   initiator-address 192.168.xx.xx
   incominguser user verystrongpassword12
</target>

  •  

George

Вот еще одна,не полная, но удобная
[1]    Install administration tools.
root@dlp:~# apt -y install tgt
[2]    Configure iSCSI Target.
For example, create an disk-image under the [/var/lib/iscsi_disks] directory and set it as a SCSI device.
# create a disk image

root@dlp:~# mkdir /var/lib/iscsi_disks

root@dlp:~# dd if=/dev/zero of=/var/lib/iscsi_disks/disk01.img count=0 bs=1 seek=10G
[root@dlp ~]# vi /etc/tgt/conf.d/target01.conf
# create new

Код: bash
# if you set some devices, add <target>-</target> and set the same way with follows

# naming rule : [ iqn.(year)-(month).(reverse of domain name):(any name you like) ]

<target iqn.2020-05.world.srv:dlp.target01>
    # provided devicce as a iSCSI target
    backing-store /var/lib/iscsi_disks/disk01.img
    # iSCSI Initiator's IQN you allow to connect
    initiator-name iqn.2020-05.world.srv:node01.initiator01
    # authentication info ( set anyone you like for "username", "password" )
    incominguser username password
</target> 

root@dlp:~# systemctl restart tgt
# show status

root@dlp:~# tgtadm --mode target --op show
Код: bash
Target 1: iqn.2020-05.world.srv:dlp.target01
    System information:
        Driver: iscsi
        State: ready
    I_T nexus information:
    LUN information:
        LUN: 0
            Type: controller
            SCSI ID: IET     00010000
            SCSI SN: beaf10
            Size: 0 MB, Block size: 1
            Online: Yes
            Removable media: No
            Prevent removal: No
            Readonly: No
            SWP: No
            Thin-provisioning: No
            Backing store type: null
            Backing store path: None
            Backing store flags:
        LUN: 1
            Type: disk
            SCSI ID: IET     00010001
            SCSI SN: beaf11
            Size: 10737 MB, Block size: 512
            Online: Yes
            Removable media: No
            Prevent removal: No
            Readonly: No
            SWP: No
            Thin-provisioning: No
            Backing store type: rdwr
            Backing store path: /var/lib/iscsi_disks/disk01.img
            Backing store flags:
    Account information:
        username
    ACL information:
        ALL
        iqn.2020-05.world.srv:node01.initiator01
  •  

🡱 🡳

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