Всем привет.
Есть сервер с большим RAID-массивом на котором решено было организовать iSCSI таргеты для подключения.
Ну это в плане обучения и приобретения практических навыков использования такого умения.
Ubuntu Server 24.04.2 + TGT
Выполним установку:
1 | sudo apt install tgt |
Проверим статус:
1 | systemctl status tgt |
Справка по команде:
1 | tgtadm --help |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | Usage: tgtadm [OPTION] --lld <driver> --mode target --op new --tid <id> --targetname <name> add a new target with <id> and <name>. <id> must not be zero. --lld <driver> --mode target --op delete [--force] --tid <id> delete the specific target with <id>. With force option, the specific target is deleted even if there is an activity. --lld <driver> --mode target --op show show all the targets. --lld <driver> --mode target --op show --tid <id> show the specific target's parameters. --lld <driver> --mode target --op update --tid <id> --name <param> --value <value> change the target parameters of the target with <id>. --lld <driver> --mode target --op bind --tid <id> --initiator-address <address> --lld <driver> --mode target --op bind --tid <id> --initiator-name <name> enable the target to accept the specific initiators. --lld <driver> --mode target --op unbind --tid <id> --initiator-address <address> --lld <driver> --mode target --op unbind --tid <id> --initiator-name <name> disable the specific permitted initiators. --lld <driver> --mode logicalunit --op new --tid <id> --lun <lun> --backing-store <path> --bstype <type> --bsopts <bs options> --bsoflags <options> add a new logical unit with <lun> to the specific target with <id>. The logical unit is offered to the initiators. <path> must be block device files (including LVM and RAID devices) or regular files. bstype option is optional. bsopts are specific to the bstype. bsoflags supported options are sync and direct (sync:direct for both). --lld <driver> --mode logicalunit --op delete --tid <id> --lun <lun> delete the specific logical unit with <lun> that the target with <id> has. --lld <driver> --mode account --op new --user <name> --password <pass> add a new account with <name> and <pass>. --lld <driver> --mode account --op delete --user <name> delete the specific account having <name>. --lld <driver> --mode account --op bind --tid <id> --user <name> [--outgoing] add the specific account having <name> to the specific target with <id>. <user> could be <IncomingUser> or <OutgoingUser>. If you use --outgoing option, the account will be added as an outgoing account. --lld <driver> --mode account --op unbind --tid <id> --user <name> [--outgoing] delete the specific account having <name> from specific target. The --outgoing option must be added if you delete an outgoing account. --lld <driver> --mode lld --op start Start the specified lld without restarting the tgtd process. --control-port <port> use control port <port> --help display this help and exit Report bugs to <stgt@vger.kernel.org>. |
Создадим образ для будущего подключения по iSCSI:
1 | sudo dd if=/dev/zero of=/media/hdd3/winr_swap.img count=0 bs=1 seek=20G |
где:
- of=/media/hdd3/winr_swap.img — путь и название образа.
У меня это /media/hdd3 — сам путь (тут диск с большим объемом), и winr_swap.img — сам образ. - count=0 — скопировать указанное количество блоков, размер одного блока указывается в параметре bs,
- bs=1 — указывает сколько байт читать и записывать за один раз,
- seek=20G — пропустить указанное количество байт в начале устройства для чтения,
- status=progress — можно добавить такой ключ, для указания подробного вывода.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | Usage: dd [OPERAND]... or: dd OPTION Copy a file, converting and formatting according to the operands. bs=BYTES read and write up to BYTES bytes at a time (default: 512); overrides ibs and obs cbs=BYTES convert BYTES bytes at a time conv=CONVS convert the file as per the comma separated symbol list count=N copy only N input blocks ibs=BYTES read up to BYTES bytes at a time (default: 512) if=FILE read from FILE instead of stdin iflag=FLAGS read as per the comma separated symbol list obs=BYTES write BYTES bytes at a time (default: 512) of=FILE write to FILE instead of stdout oflag=FLAGS write as per the comma separated symbol list seek=N (or oseek=N) skip N obs-sized output blocks skip=N (or iseek=N) skip N ibs-sized input blocks status=LEVEL The LEVEL of information to print to stderr; 'none' suppresses everything but error messages, 'noxfer' suppresses the final transfer statistics, 'progress' shows periodic transfer statistics N and BYTES may be followed by the following multiplicative suffixes: c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000, M=1024*1024, xM=M, GB=1000*1000*1000, G=1024*1024*1024, and so on for T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. If N ends in 'B', it counts bytes not blocks. Each CONV symbol may be: ascii from EBCDIC to ASCII ebcdic from ASCII to EBCDIC ibm from ASCII to alternate EBCDIC block pad newline-terminated records with spaces to cbs-size unblock replace trailing spaces in cbs-size records with newline lcase change upper case to lower case ucase change lower case to upper case sparse try to seek rather than write all-NUL output blocks swab swap every pair of input bytes sync pad every input block with NULs to ibs-size; when used with block or unblock, pad with spaces rather than NULs excl fail if the output file already exists nocreat do not create the output file notrunc do not truncate the output file noerror continue after read errors fdatasync physically write output file data before finishing fsync likewise, but also write metadata Each FLAG symbol may be: append append mode (makes sense only for output; conv=notrunc suggested) direct use direct I/O for data directory fail unless a directory dsync use synchronized I/O for data sync likewise, but also for metadata fullblock accumulate full blocks of input (iflag only) nonblock use non-blocking I/O noatime do not update access time nocache Request to drop cache. See also oflag=sync noctty do not assign controlling terminal from file nofollow do not follow symlinks Sending a USR1 signal to a running 'dd' process makes it print I/O statistics to standard error and then resume copying. Options are: --help display this help and exit --version output version information and exit GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Full documentation <https://www.gnu.org/software/coreutils/dd> or available locally via: info '(coreutils) dd invocation' |
Как видим, создался файл с размером 20 ГБ. Теперь надо его прописать для использования в качестве «таргета».
Конфигурационные файлы лежат вот тут — /etc/tgt/conf.d
Сам файл с описанием — /etc/tgt/conf.d/iscsi.conf
Добавим такую строку:
1 2 3 4 | <target iqn.2025-02.backup-srv:dlp.target04> backing-store /media/hdd3/winr_swap.img initiator-name iqn.1991-05.com.microsoft:win-route.server.local </target> |
где:
- target iqn.2025-02.backup-srv:dlp.target04 — название нашего «таргета»,
- backing-store /media/hdd3/winr_swap.img — подключаемый образ, созданный ранее,
- initiator-name iqn.1991-05.com.microsoft:win-route.server.local — тут я использовал конкретного инициатора подключения (посмотрел в свойствах iSCSI Initator Properties), но можно указать такие параметры:
initiator-address [client-ip-address] — адрес инициатора,
incominguser [client-scsi client-password] — пароль клиента,
outgoinguser [server-scsi server-password] — пароль сервера.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | В начале секции после директивы 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, их тоже можно указать несколько. |
Перезапустим сервис TGT после настройки:
1 | sudo systemctl restart tgt |
Проверим наши «таргеты»:
1 | sudo tgtadm --mode target --op show |
Теперь попробую подключить диск к системе. У меня Windows Server 2016 Standard.
Control Panel\All Control Panel Items\Administrative Tools — iSCSI Initiator
Тут же во вкладке «Configuration» я посмотрел Initiator Name, которое указал в файле iscsi.conf как инициатора подключения
На вкладке «Targets» в строке «Target» пишем IP-адрес сервера или его доменное имя и жмем «Quick Connect…»
В открывшемся окне выбираем наш созданный ранее «таргет» и жмем «Connect»
В «Progress report» должно быть такое — Login Succeeded
Жмем «Done».
На вкладке «Targets» стало так:
В «Disk Management» появился новый диск:
Дальше настройка диска по необходимой задаче.
Ссылки:
If you found an error, highlight it and press Shift + Enter or to inform us.