Add documentation for the new "vitastor-disk" tool

rm-left-on-dead
Vitaliy Filippov 2022-08-22 00:31:30 +03:00
parent 54ef2c389f
commit a537db8909
15 changed files with 608 additions and 100 deletions

View File

@ -58,6 +58,7 @@ Vitastor поддерживает QEMU-драйвер, протоколы NBD и
- [Метаданные образов в etcd](docs/config/inode.ru.md)
- Использование
- [vitastor-cli](docs/usage/cli.ru.md) (консольный интерфейс)
- [vitastor-disk](docs/usage/disk.ru.md) (управление дисками)
- [fio](docs/usage/fio.ru.md) для тестов производительности
- [NBD](docs/usage/nbd.ru.md) для монтирования ядром
- [QEMU и qemu-img](docs/usage/qemu.ru.md)

View File

@ -58,6 +58,7 @@ Read more details below in the documentation.
- [Image metadata in etcd](docs/config/inode.en.md)
- Usage
- [vitastor-cli](docs/usage/cli.en.md) (command-line interface)
- [vitastor-disk](docs/usage/disk.en.md) (disk management tool)
- [fio](docs/usage/fio.en.md) for benchmarks
- [NBD](docs/usage/nbd.en.md) for kernel mounts
- [QEMU and qemu-img](docs/usage/qemu.en.md)

View File

@ -34,6 +34,7 @@
- [Debian and CentOS packages](../installation/packages.en.md)
- [Image management CLI (vitastor-cli)](../usage/cli.en.md)
- [Disk management CLI (vitastor-disk)](docs/usage/disk.en.md)
- Generic user-space client library
- [Native QEMU driver](../usage/qemu.en.md)
- [Loadable fio engine for benchmarks](../usage/fio.en.md)
@ -47,7 +48,6 @@
The following features are planned for the future:
- Better OSD creation and auto-start tools
- Other administrative tools
- Web GUI
- OpenNebula plugin

View File

@ -36,6 +36,7 @@
- [Пакеты для Debian и CentOS](../installation/packages.ru.md)
- [Консольный интерфейс управления образами (vitastor-cli)](../usage/cli.ru.md)
- [Инструмент управления дисками (vitastor-disk)](docs/usage/disk.ru.md)
- Общая пользовательская клиентская библиотека для работы с кластером
- [Драйвер диска для QEMU](../usage/qemu.ru.md)
- [Драйвер диска для утилиты тестирования производительности fio](../usage/fio.ru.md)
@ -47,7 +48,6 @@
## Планы развития
- Более корректные скрипты разметки дисков и автоматического запуска OSD
- Другие инструменты администрирования
- Web-интерфейс
- Плагин для OpenNebula

View File

@ -20,7 +20,6 @@ It supports the following commands:
- [rm-data](#rm-data)
- [merge-data](#merge-data)
- [alloc-osd](#alloc-osd)
- [simple-offsets](#simple-offsets)
Global options:
@ -176,21 +175,3 @@ Merge layer data without changing metadata. Merge `<from>`..`<to>` to `<target>`
`vitastor-cli alloc-osd`
Allocate a new OSD number and reserve it by creating empty `/osd/stats/<n>` key.
## simple-offsets
`vitastor-cli simple-offsets <device>`
Calculate offsets for simple&stupid (no superblock) OSD deployment.
Options (see also [Cluster-Wide Disk Layout Parameters](../config/layout-cluster.en.md)):
```
--object_size 128k Set blockstore block size
--bitmap_granularity 4k Set bitmap granularity
--journal_size 32M Set journal size
--device_block_size 4k Set device block size
--journal_offset 0 Set journal offset
--device_size 0 Set device size
--format text Result format: json, options, env, or text
```

View File

@ -21,7 +21,6 @@ vitastor-cli - интерфейс командной строки для адм
- [rm-data](#rm-data)
- [merge-data](#merge-data)
- [alloc-osd](#alloc-osd)
- [simple-offsets](#simple-offsets)
Глобальные опции:
@ -187,21 +186,3 @@ vitastor-cli snap-create [-p|--pool <id|name>] <image>@<snapshot>
Атомарно выделить новый номер OSD и зарезервировать его, создав в etcd пустой
ключ `/osd/stats/<n>`.
## simple-offsets
`vitastor-cli simple-offsets <device>`
Рассчитать смещения для простого и тупого создания OSD на диске (без суперблока).
Опции (см. также [Дисковые параметры уровня кластера](../config/layout-cluster.ru.md)):
```
--object_size 128k Размер блока хранилища
--bitmap_granularity 4k Гранулярность битовых карт
--journal_size 32M Размер журнала
--device_block_size 4k Размер блока устройства
--journal_offset 0 Смещение журнала
--device_size 0 Размер устройства
--format text Формат результата: json, options, env или text
```

245
docs/usage/disk.en.md Normal file
View File

@ -0,0 +1,245 @@
[Documentation](../../README.md#documentation) → Usage → Disk Tool
-----
[Читать на русском](disk.ru.md)
# Disk management tool
vitastor-disk is a command-line tool for physical Vitastor disk management.
It supports the following commands:
- [prepare](#prepare)
- [upgrade-simple](#upgrade-simple)
- [resize](#resize)
- [start/stop/restart/enable/disable](#start/stop/restart/enable/disable)
- [read-sb](#read-sb)
- [write-sb](#write-sb)
- [udev](#udev)
- [exec-osd](#exec-osd)
- [pre-exec](#pre-exec)
- Debugging:
- [dump-journal](#dump-journal)
- [write-journal](#write-journal)
- [dump-meta](#dump-meta)
- [write-meta](#write-meta)
- [simple-offsets](#simple-offsets)
## prepare
`vitastor-disk prepare [OPTIONS] [devices...]`
Initialize disk(s) for Vitastor OSD(s).
There are two modes of this command. In the first mode, you pass `<devices>` which
must be raw disks (not partitions). They are partitioned automatically and OSDs
are initialized on all of them.
In the second mode, you omit `<devices>` and pass `--data_device`, `--journal_device`
and/or `--meta_device` which must be already existing partitions identified by their
GPT partition UUIDs. In this case a single OSD is created.
Requires `vitastor-cli`, `wipefs`, `sfdisk` and `partprobe` (from parted) utilities.
Options (automatic mode):
```
--osd_per_disk <N>
Create <N> OSDs on each disk (default 1)
--hybrid
Prepare hybrid (HDD+SSD) OSDs using provided devices. SSDs will be used for
journals and metadata, HDDs will be used for data. Partitions for journals and
metadata will be created automatically. Whether disks are SSD or HDD is decided
by the `/sys/block/.../queue/rotational` flag. In hybrid mode, default object
size is 1 MB instead of 128 KB, default journal size is 1 GB instead of 32 MB,
and throttle_small_writes is enabled by default.
--disable_data_fsync 1
Disable data device cache and fsync (1/yes/true = on, default on)
--disable_meta_fsync 1
Disable metadata/journal device cache and fsync (default on)
--meta_reserve 2x,1G
New metadata partitions in --hybrid mode are created larger than actual
metadata size to ease possible future extension. The default is to allocate
2 times more space and at least 1G. Use this option to override.
--max_other 10%
Use disks for OSD data even if they already have non-Vitastor partitions,
but only if these take up no more than this percent of disk space.
```
Options (single-device mode):
```
--data_device <DEV> Use partition <DEV> for data
--meta_device <DEV> Use partition <DEV> for metadata (optional)
--journal_device <DEV> Use partition <DEV> for journal (optional)
--disable_data_fsync 0 Disable data device cache and fsync (default off)
--disable_meta_fsync 0 Disable metadata device cache and fsync (default off)
--disable_journal_fsync 0 Disable journal device cache and fsync (default off)
--force Bypass partition safety checks (for emptiness and so on)
```
Options (both modes):
```
--journal_size 1G/32M Set journal size (area or partition size)
--object_size 1M/128k Set blockstore object size
--bitmap_granularity 4k Set bitmap granularity
--data_device_block 4k Override data device block size
--meta_device_block 4k Override metadata device block size
--journal_device_block 4k Override journal device block size
```
[immediate_commit](../config/layout-cluster.en.md#immediate_commit) setting is
automatically derived from "disable fsync" options. It's set to "all" when fsync
is disabled on all devices, and to "small" if fsync is only disabled on journal device.
When data/meta/journal fsyncs are disabled, the OSD startup script automatically
checks the device cache status on start and tries to disable cache for SATA/SAS disks.
If it doesn't succeed it issues a warning in the system log.
You can also pass other OSD options here as arguments and they'll be persisted
to the superblock: max_write_iodepth, max_write_iodepth, min_flusher_count,
max_flusher_count, inmemory_metadata, inmemory_journal, journal_sector_buffer_count,
journal_no_same_sector_overwrites, throttle_small_writes, throttle_target_iops,
throttle_target_mbs, throttle_target_parallelism, throttle_threshold_us.
See [Runtime OSD Parameters](../config/osd.en.md) for details.
## upgrade-simple
`vitastor-disk upgrade-simple <UNIT_FILE|OSD_NUMBER>`
Upgrade an OSD created by old (0.7.1 and older) `make-osd.sh` or `make-osd-hybrid.js` scripts.
Adds superblocks to OSD devices, disables old `vitastor-osdN` unit and replaces it with `vitastor-osd@N`.
Can be invoked with an osd number of with a path to systemd service file `UNIT_FILE` which
must be `/etc/systemd/system/vitastor-osd<OSD_NUMBER>.service`.
Note that the procedure isn't atomic and may ruin OSD data in case of an interrupt,
so don't upgrade all your OSDs in parallel.
Requires the `sfdisk` utility.
## resize
`vitastor-disk resize <ALL_OSD_PARAMETERS> <NEW_LAYOUT> [--iodepth 32]`
Resize data area and/or rewrite/move journal and metadata.
`ALL_OSD_PARAMETERS` must include all (at least all disk-related)
parameters from OSD command line (i.e. from systemd unit or superblock).
`NEW_LAYOUT` may include new disk layout parameters:
```
--new_data_offset SIZE resize data area so it starts at SIZE
--new_data_len SIZE resize data area to SIZE bytes
--new_meta_device PATH use PATH for new metadata
--new_meta_offset SIZE make new metadata area start at SIZE
--new_meta_len SIZE make new metadata area SIZE bytes long
--new_journal_device PATH use PATH for new journal
--new_journal_offset SIZE make new journal area start at SIZE
--new_journal_len SIZE make new journal area SIZE bytes long
```
SIZE may include k/m/g/t suffixes. If any of the new layout parameter
options are not specified, old values will be used.
## start/stop/restart/enable/disable
`vitastor-disk start|stop|restart|enable|disable [--now] <device> [device2 device3 ...]`
Manipulate Vitastor OSDs using systemd by their device paths.
Commands are passed to `systemctl` with `vitastor-osd@<num>` units as arguments.
When `--now` is added to enable/disable, OSDs are also immediately started/stopped.
## read-sb
`vitastor-disk read-sb <device>`
Try to read Vitastor OSD superblock from `<device>` and print it in JSON format.
## write-sb
`vitastor-disk write-sb <device>`
Read JSON from STDIN and write it into Vitastor OSD superblock on `<device>`.
## udev
`vitastor-disk udev <device>`
Try to read Vitastor OSD superblock from `<device>` and print variables for udev.
## exec-osd
`vitastor-disk exec-osd <device>`
Read Vitastor OSD superblock from `<device>` and start the OSD with parameters from it.
Intended for use from startup scripts (i.e. from systemd units).
## pre-exec
`vitastor-disk pre-exec <device>`
Read Vitastor OSD superblock from `<device>` and perform pre-start checks for the OSD.
For now, this only checks that device cache is in write-through mode if fsync is disabled.
Intended for use from startup scripts (i.e. from systemd units).
## dump-journal
`vitastor-disk dump-journal [OPTIONS] <journal_file> <journal_block_size> <offset> <size>`
Dump journal in human-readable or JSON (if `--json` is specified) format.
Options:
```
--all Scan the whole journal area for entries and dump them, even outdated ones
--json Dump journal in JSON format
--format entries (Default) Dump actual journal entries as an array, without data
--format data Same as "entries", but also include small write data
--format blocks Dump as an array of journal blocks each containing array of entries
```
## write-journal
`vitastor-disk write-journal <journal_file> <journal_block_size> <bitmap_size> <offset> <size>`
Write journal from JSON taken from standard input in the same format as produced by
`dump-journal --json --format data`.
## dump-meta
`vitastor-disk dump-meta <meta_file> <meta_block_size> <offset> <size>`
Dump metadata in JSON format.
## write-meta
`vitastor-disk write-meta <meta_file> <offset> <size>`
Write metadata from JSON taken from standard input in the same format as produced by `dump-meta`.
## simple-offsets
`vitastor-disk simple-offsets <device>`
Calculate offsets for old simple&stupid (no superblock) OSD deployment.
Options (see also [Cluster-Wide Disk Layout Parameters](../config/layout-cluster.en.md)):
```
--object_size 128k Set blockstore block size
--bitmap_granularity 4k Set bitmap granularity
--journal_size 32M Set journal size
--device_block_size 4k Set device block size
--journal_offset 0 Set journal offset
--device_size 0 Set device size
--format text Result format: json, options, env, or text
```

248
docs/usage/disk.ru.md Normal file
View File

@ -0,0 +1,248 @@
[Документация](../../README-ru.md#документация) → Использование → Управление дисками
-----
[Read in English](disk.en.md)
# Инструмент управления дисками
vitastor-disk - инструмент командной строки для управления дисками Vitastor OSD.
Поддерживаются следующие команды:
- [prepare](#prepare)
- [upgrade-simple](#upgrade-simple)
- [resize](#resize)
- [start/stop/restart/enable/disable](#start/stop/restart/enable/disable)
- [read-sb](#read-sb)
- [write-sb](#write-sb)
- [udev](#udev)
- [exec-osd](#exec-osd)
- [pre-exec](#pre-exec)
- Для отладки:
- [dump-journal](#dump-journal)
- [write-journal](#write-journal)
- [dump-meta](#dump-meta)
- [write-meta](#write-meta)
- [simple-offsets](#simple-offsets)
## prepare
`vitastor-disk prepare [OPTIONS] [devices...]`
Подготовить диск(и) для OSD Vitastor.
У команды есть 2 режима. В первом режиме вы указываете список устройств `<devices>`,
которые должны быть целыми дисками (не разделами). На них автоматически создаются
разделы и инициализируются OSD.
Во втором режиме вместо списка устройств вы указываете пути к отдельным устройствам
`--data_device`, `--journal_device` и/или `--meta_device`, которые должны быть
уже существующими GPT-разделами. В этом случае инициализируется ровно один OSD.
Команде требуются утилиты `vitastor-cli`, `wipefs`, `sfdisk` и `partprobe` (из состава parted).
Опции для автоматического режима:
```
--osd_per_disk <N>
Создавать по несколько (<N>) OSD на каждом диске (по умолчанию 1)
--hybrid
Инициализировать гибридные (HDD+SSD) OSD на указанных дисках. SSD будут
использованы для журналов и метаданных, а HDD - для данных. Разделы для журналов
и метаданных будут созданы автоматически. Является ли диск SSD или HDD, определяется
по флагу `/sys/block/.../queue/rotational`. В гибридном режиме по умолчанию
используется размер объекта 1 МБ вместо 128 КБ, размер журнала 1 ГБ вместо 32 МБ
и включённый throttle_small_writes.
--disable_data_fsync 1
Отключать кэш и fsync-и для устройств данных (1/yes/true = да, по умолчанию да)
--disable_meta_fsync 1
Отключать кэш и fsync-и для журналов и метаданных (по умолчанию да)
--meta_reserve 2x,1G
В гибридном режиме для метаданных выделяется больше места, чем нужно на самом
деле, чтобы оставить запас под будущее расширение. По умолчанию выделяется
в 2 раза больше места, и не менее 1 ГБ. Чтобы изменить это поведение,
воспользуйтесь данной опцией.
--max_other 10%
Использовать диски под данные OSD, даже если на них уже есть не-Vitastor-овые
разделы, но только в случае, если они занимают не более данного процента диска.
```
Опции для режима одного OSD:
```
--data_device <DEV> Использовать раздел <DEV> для данных
--meta_device <DEV> Использовать раздел <DEV> для метаданных (опционально)
--journal_device <DEV> Использовать раздел <DEV> для журнала (опционально)
--disable_data_fsync 0 Отключить кэш и fsync устройства данных (по умолчанию нет)
--disable_meta_fsync 0 Отключить кэш и fsync метаданных (по умолчанию нет)
--disable_journal_fsync 0 Отключить кэш и fsync журнала (по умолчанию нет)
--force Пропустить проверки разделов (на пустоту и т.п.)
```
Опции для обоих режимов:
```
--journal_size 1G/32M Задать размер журнала (области или раздела журнала)
--object_size 1M/128k Задать размер объекта
--bitmap_granularity 4k Задать гранулярность битовых карт
--data_device_block 4k Задать размер блока устройства данных
--meta_device_block 4k Задать размер блока метаданных
--journal_device_block 4k Задать размер блока журнала
```
Настройка [immediate_commit](../config/layout-cluster.ru.md#immediate_commit)
автоматически выводится из опций отключения кэша - она устанавливается в "all", если кэш
отключён на всех устройствах, и в "small", если он отключён только на устройстве журнала.
Когда fsync данных/метаданных/журнала отключён, скрипты запуска OSD автоматически
проверяют состояние кэша диска и стараются его отключить для SATA/SAS дисков. Если
это не удаётся, в системный журнал выводится предупреждение.
Вы можете передать данной команде и некоторые другие опции OSD в качестве аргументов
и они тоже будут сохранены в суперблок: max_write_iodepth, max_write_iodepth, min_flusher_count,
max_flusher_count, inmemory_metadata, inmemory_journal, journal_sector_buffer_count,
journal_no_same_sector_overwrites, throttle_small_writes, throttle_target_iops,
throttle_target_mbs, throttle_target_parallelism, throttle_threshold_us.
Читайте об этих параметрах подробнее в разделе [Изменяемые параметры OSD](../config/osd.ru.md).
## upgrade-simple
`vitastor-disk upgrade-simple <UNIT_FILE|OSD_NUMBER>`
Обновить OSD, созданный старыми (0.7.1 и старее) скриптами `make-osd.sh` и `make-osd-hybrid.js`.
Добавляет суперблок на разделы OSD, отключает старый сервис `vitastor-osdN` и заменяет его на `vitastor-osd@N`.
Можно вызывать, указывая либо номер OSD, либо путь к файлу сервиса `UNIT_FILE`, но он обязан
иметь вид `/etc/systemd/system/vitastor-osd<OSD_NUMBER>.service`.
Имейте в виду, что процедура обновления не атомарна и при прерывании может уничтожить данные OSD,
так что обновляйте ваши OSD по очереди.
Команде требуется утилита `sfdisk`.
## resize
`vitastor-disk resize <ALL_OSD_PARAMETERS> <NEW_LAYOUT> [--iodepth 32]`
Изменить размер области данных и/или переместить журнал и метаданные.
В `ALL_OSD_PARAMETERS` нужно указать все относящиеся к диску параметры OSD
из суперблока OSD или из файла сервиса systemd (в старых версиях).
В `NEW_LAYOUT` нужно указать новые параметры расположения данных:
```
--new_data_offset РАЗМЕР сдвинуть начало области данных на РАЗМЕР байт
--new_data_len РАЗМЕР изменить размер области данных до РАЗМЕР байт
--new_meta_device ПУТЬ использовать ПУТЬ как новое устройство метаданных
--new_meta_offset РАЗМЕР разместить новые метаданные по смещению РАЗМЕР байт
--new_meta_len РАЗМЕР сделать новые метаданные размером РАЗМЕР байт
--new_journal_device ПУТЬ использовать ПУТЬ как новое устройство журнала
--new_journal_offset РАЗМЕР разместить новый журнал по смещению РАЗМЕР байт
--new_journal_len РАЗМЕР сделать новый журнал размером РАЗМЕР байт
```
РАЗМЕР может быть указан с суффиксами k/m/g/t. Если любой из новых параметров
расположения не указан, он принимается равным старому значению.
## start/stop/restart/enable/disable
`vitastor-disk start|stop|restart|enable|disable [--now] <device> [device2 device3 ...]`
Команды управления OSD по путям дисков через systemd.
Команды транслируются `systemctl` с сервисами `vitastor-osd@<num>` в виде аргументов.
Когда к командам включения/выключения добавляется параметр `--now`, OSD также сразу
запускаются/останавливаются.
## read-sb
`vitastor-disk read-sb <device>`
Прочитать суперблок OSD с диска `<device>` и вывести его в формате JSON.
## write-sb
`vitastor-disk write-sb <device>`
Прочитать JSON со стандартного ввода и записать его в суперблок OSD на диск `<device>`.
## udev
`vitastor-disk udev <device>`
Прочитать суперблок OSD с диска `<device>` и вывести переменные для udev.
## exec-osd
`vitastor-disk exec-osd <device>`
Прочитать суперблок OSD с диска `<device>` и запустить исполняемый файл OSD с параметрами оттуда.
Команда предназначена для использования из скриптов запуска (например, из сервисов systemd).
## pre-exec
`vitastor-disk pre-exec <device>`
Прочитать суперблок OSD с диска `<device>` и провести проверки OSD перед запуском.
На данный момент только отключает кэш диска или проверяет, что он отключён, если в параметрах
OSD отключены fsync-и.
Команда предназначена для использования из скриптов запуска (например, из сервисов systemd).
## dump-journal
`vitastor-disk dump-journal [OPTIONS] <journal_file> <journal_block_size> <offset> <size>`
Вывести журнал в человекочитаемом или в JSON (с опцией `--json`) виде.
Опции:
```
--all Просканировать всю область журнала и вывести даже старые записи
--json Вывести журнал в формате JSON
--format entries (По умолчанию) Вывести только актуальные записи журнала без данных
--format data Вывести только актуальные записи журнала с данными
--format blocks Вывести массив блоков журнала, а в каждом массив актуальных записей без данных
```
## write-journal
`vitastor-disk write-journal <journal_file> <journal_block_size> <bitmap_size> <offset> <size>`
Записать журнал из JSON со стандартного ввода в формате, аналогичном `dump-journal --json --format data`.
## dump-meta
`vitastor-disk dump-meta <meta_file> <meta_block_size> <offset> <size>`
Вывести метаданные в формате JSON.
## write-meta
`vitastor-disk write-meta <meta_file> <offset> <size>`
Записать метаданные из JSON со стандартного ввода в формате, аналогичном `dump-meta`.
## simple-offsets
`vitastor-disk simple-offsets <device>`
Рассчитать смещения для старого ("простого и тупого") создания OSD на диске (без суперблока).
Опции (см. также [Дисковые параметры уровня кластера](../config/layout-cluster.ru.md)):
```
--object_size 128k Размер блока хранилища
--bitmap_granularity 4k Гранулярность битовых карт
--journal_size 32M Размер журнала
--device_block_size 4k Размер блока устройства
--journal_offset 0 Смещение журнала
--device_size 0 Размер устройства
--format text Формат результата: json, options, env или text
```

View File

@ -526,8 +526,9 @@ std::function<bool(cli_result_t &)> cli_tool_t::start_create(json11::Json cfg)
image_creator->new_parent = cfg["parent"].string_value();
if (cfg["size"].string_value() != "")
{
image_creator->size = parse_size(cfg["size"].string_value());
if (image_creator->size == UINT64_MAX)
bool ok;
image_creator->size = parse_size(cfg["size"].string_value(), &ok);
if (!ok)
{
return [size = cfg["size"].string_value()](cli_result_t & result)
{

View File

@ -12,63 +12,97 @@ static const char *help_text =
"\n"
"vitastor-disk prepare [OPTIONS] [devices...]\n"
" Initialize disk(s) for Vitastor OSD(s).\n"
" \n"
" There are two modes of this command. In the first mode, you pass <devices> which\n"
" must be raw disks (not partitions). They are partitioned automatically and OSDs\n"
" are initialized on all of them.\n"
" \n"
" In the second mode, you omit <devices> and pass --data_device, --journal_device\n"
" and/or --meta_device which must be already existing partitions identified by their\n"
" GPT partition UUIDs. In this case a single OSD is created.\n"
" \n"
" Requires `vitastor-cli`, `wipefs`, `sfdisk` and `partprobe` (from parted) utilities.\n"
" OPTIONS may include:\n"
" \n"
" Options (automatic mode):\n"
" --osd_per_disk <N>\n"
" Create <N> OSDs on each disk (default 1)\n"
" --hybrid\n"
" Prepare hybrid (HDD+SSD) OSDs using provided devices. SSDs will be used for\n"
" journals and metadata, HDDs will be used for data. Partitions for journals and\n"
" metadata will be created automatically. SSD/HDD are found by the `rotational`\n"
" flag of devices. In hybrid mode, object size is 1 MB instead of 128 KB by\n"
" default, and journal size is 1 GB instead of 32 MB by default.\n"
" --osd_per_disk <N> Create <N> OSDs on each disk (default 1)\n"
" --data_device <DEV> Create a single OSD using partition <DEV> for data\n"
" --meta_device <DEV> Create a single OSD using partition <DEV> for metadata\n"
" --journal_device <DEV> Create a single OSD using partition <DEV> for journal\n"
" --force Bypass checks on data/meta/journal partitions\n"
" --journal_size 1G/32M Set journal size\n"
" --object_size 1M/128k Set blockstore object size\n"
" --disable_ssd_cache 1 Disable cache and fsyncs for SSD journal and metadata\n"
" --disable_hdd_cache 1 Disable cache and fsyncs for HDD data\n"
" --bitmap_granularity 4k Set bitmap granularity\n"
" --data_device_block 4k Override data device block size\n"
" --meta_device_block 4k Override metadata device block size\n"
" --journal_device_block 4k Override journal device block size\n"
" metadata will be created automatically. Whether disks are SSD or HDD is decided\n"
" by the `/sys/block/.../queue/rotational` flag. In hybrid mode, default object\n"
" size is 1 MB instead of 128 KB, default journal size is 1 GB instead of 32 MB,\n"
" and throttle_small_writes is enabled by default.\n"
" --disable_data_fsync 1\n"
" Disable data device cache and fsync (1/yes/true = on, default on)\n"
" --disable_meta_fsync 1\n"
" Disable metadata/journal device cache and fsync (default on)\n"
" --meta_reserve 2x,1G\n"
" New metadata partitions in --hybrid mode are created larger than actual\n"
" metadata size to ease possible future extension. The default is to allocate\n"
" 2 times more space and at least 1G. Use this option to override.\n"
" --max_other 10%\n"
" In the automatic mode, use disks for OSD data even if they already have non-Vitastor\n"
" partitions, but only if these take up no more than this percent of disk space.\n"
" Use disks for OSD data even if they already have non-Vitastor partitions,\n"
" but only if these take up no more than this percent of disk space.\n"
" \n"
" Options (single-device mode):\n"
" --data_device <DEV> Use partition <DEV> for data\n"
" --meta_device <DEV> Use partition <DEV> for metadata (optional)\n"
" --journal_device <DEV> Use partition <DEV> for journal (optional)\n"
" --disable_data_fsync 0 Disable data device cache and fsync (default off)\n"
" --disable_meta_fsync 0 Disable metadata device cache and fsync (default off)\n"
" --disable_journal_fsync 0 Disable journal device cache and fsync (default off)\n"
" --force Bypass partition safety checks (for emptiness and so on)\n"
" \n"
" Options (both modes):\n"
" --journal_size 1G/32M Set journal size (area or partition size)\n"
" --object_size 1M/128k Set blockstore object size\n"
" --bitmap_granularity 4k Set bitmap granularity\n"
" --data_device_block 4k Override data device block size\n"
" --meta_device_block 4k Override metadata device block size\n"
" --journal_device_block 4k Override journal device block size\n"
" \n"
" immediate_commit setting is automatically derived from \"disable fsync\" options.\n"
" It's set to \"all\" when fsync is disabled on all devices, and to \"small\" if fsync\n"
" is only disabled on journal device.\n"
" \n"
" When data/meta/journal fsyncs are disabled, the OSD startup script automatically\n"
" checks the device cache status on start and tries to disable cache for SATA/SAS disks.\n"
" If it doesn't succeed it issues a warning in the system log.\n"
" \n"
" You can also pass other OSD options here as arguments and they'll be persisted\n"
" to the superblock: max_write_iodepth, max_write_iodepth, min_flusher_count,\n"
" max_flusher_count, inmemory_metadata, inmemory_journal, journal_sector_buffer_count,\n"
" journal_no_same_sector_overwrites, throttle_small_writes, throttle_target_iops,\n"
" throttle_target_mbs, throttle_target_parallelism, throttle_threshold_us.\n"
"\n"
"vitastor-disk upgrade-simple <UNIT_FILE|OSD_NUMBER>\n"
" Upgrade an OSD created by old (0.7.1 and older) make-osd.sh or make-osd-hybrid.js scripts.\n"
" \n"
" Adds superblocks to OSD devices, disables old vitastor-osdN unit and replaces it with vitastor-osd@N.\n"
" UNIT_FILE must be /etc/systemd/system/vitastor-osd<OSD_NUMBER>.service.\n"
" Note that the procedure isn't atomic and may ruin OSD data if an error happens.\n"
" Can be invoked with an osd number of with a path to systemd service file UNIT_FILE which\n"
" must be /etc/systemd/system/vitastor-osd<OSD_NUMBER>.service.\n"
" \n"
" Note that the procedure isn't atomic and may ruin OSD data in case of an interrupt,\n"
" so don't upgrade all your OSDs in parallel.\n"
" \n"
" Requires the `sfdisk` utility.\n"
"\n"
"vitastor-disk resize <ALL_OSD_PARAMETERS> <NEW_LAYOUT> [--iodepth 32]\n"
" Resize data area and/or rewrite/move journal and metadata\n"
" ALL_OSD_PARAMETERS must include all (at least all disk-related)\n"
" parameters from OSD command line (i.e. from systemd unit).\n"
" parameters from OSD command line (i.e. from systemd unit or superblock).\n"
" NEW_LAYOUT may include new disk layout parameters:\n"
" [--new_data_offset <NUMBER>] resize data area so it starts at <NUMBER>\n"
" [--new_data_len <NUMBER>] resize data area to <NUMBER> bytes\n"
" [--new_meta_device <PATH>] use <PATH> for new metadata\n"
" [--new_meta_offset <NUMBER>] make new metadata area start at <NUMBER>\n"
" [--new_meta_len <NUMBER>] make new metadata area <NUMBER> bytes long\n"
" [--new_journal_device <PATH>] use <PATH> for new journal\n"
" [--new_journal_offset <NUMBER>] make new journal area start at <NUMBER>\n"
" [--new_journal_len <NUMBER>] make new journal area <NUMBER> bytes long\n"
" If any of the new layout parameter options are not specified, old values\n"
" will be used.\n"
" --new_data_offset SIZE resize data area so it starts at SIZE\n"
" --new_data_len SIZE resize data area to SIZE bytes\n"
" --new_meta_device PATH use PATH for new metadata\n"
" --new_meta_offset SIZE make new metadata area start at SIZE\n"
" --new_meta_len SIZE make new metadata area SIZE bytes long\n"
" --new_journal_device PATH use PATH for new journal\n"
" --new_journal_offset SIZE make new journal area start at SIZE\n"
" --new_journal_len SIZE make new journal area SIZE bytes long\n"
" SIZE may include k/m/g/t suffixes. If any of the new layout parameter\n"
" options are not specified, old values will be used.\n"
"\n"
"vitastor-disk start|stop|restart|enable|disable [--now] <device> [device2 device3 ...]\n"
" Manipulate Vitastor OSDs using systemd by their device paths.\n"
@ -93,33 +127,35 @@ static const char *help_text =
" For now, this only checks that device cache is in write-through mode if fsync is disabled.\n"
" Intended for use from startup scripts (i.e. from systemd units).\n"
"\n"
"vitastor-disk dump-journal [--all] [--json [--format entries|blocks|data]] <journal_file> <journal_block_size> <offset> <size>\n"
"vitastor-disk dump-journal [OPTIONS] <journal_file> <journal_block_size> <offset> <size>\n"
" Dump journal in human-readable or JSON (if --json is specified) format.\n"
" Without --all, only actual part of the journal is dumped.\n"
" With --all, the whole journal area is scanned for journal entries,\n"
" some of which may be outdated.\n"
" In JSON mode, the journal by default is dumped with --format entries.\n"
" Options:\n"
" --all Scan the whole journal area for entries and dump them, even outdated ones\n"
" --json Dump journal in JSON format\n"
" --format entries (Default) Dump actual journal entries as an array, without data\n"
" --format data Same as \"entries\", but also include small write data\n"
" --format blocks Dump as an array of journal blocks each containing array of entries\n"
"\n"
"vitastor-disk write-journal <journal_file> <journal_block_size> <bitmap_size> <offset> <size>\n"
" Write journal from JSON taken from standard input in the same format as produced by\n"
" dump-journal --json --format data.\n"
" `dump-journal --json --format data`.\n"
"\n"
"vitastor-disk dump-meta <meta_file> <meta_block_size> <offset> <size>\n"
" Dump metadata in JSON format.\n"
"\n"
"vitastor-disk write-meta <meta_file> <offset> <size>\n"
" Write metadata from JSON taken from standard input in the same format as produced by\n"
" dump-meta --json.\n"
" `dump-meta`. Intended for debugging.\n"
"\n"
"vitastor-disk simple-offsets <device>\n"
" Calculate offsets for old simple&stupid (no superblock) OSD deployment. Options:\n"
" --object_size 128k Set blockstore block size\n"
" --bitmap_granularity 4k Set bitmap granularity\n"
" --journal_size 16M Set journal size\n"
" --device_block_size 4k Set device block size\n"
" --journal_offset 0 Set journal offset\n"
" --device_size 0 Set device size\n"
" --format text Result format: json, options, env, or text\n"
" --object_size 128k Set blockstore block size\n"
" --bitmap_granularity 4k Set bitmap granularity\n"
" --journal_size 16M Set journal size\n"
" --device_block_size 4k Set device block size\n"
" --journal_offset 0 Set journal offset\n"
" --device_size 0 Set device size\n"
" --format text Result format: json, options, env, or text\n"
"\n"
"Use vitastor-disk --help <command> for command details or vitastor-disk --help --all for all details.\n"
;

View File

@ -517,8 +517,13 @@ int disk_tool_t::prepare(std::vector<std::string> devices)
if (max_other_percent > 100)
max_other_percent = 100;
std::vector<vitastor_dev_info_t> ssds;
if (options.find("disable_data_fsync") == options.end())
options["disable_data_fsync"] = "1";
if (hybrid)
{
if (options.find("disable_meta_fsync") == options.end())
options["disable_meta_fsync"] = "1";
options["disable_journal_fsync"] = options["disable_meta_fsync"];
for (auto & dev: devinfo)
if (!dev.is_hdd)
ssds.push_back(dev);
@ -535,6 +540,11 @@ int disk_tool_t::prepare(std::vector<std::string> devices)
if (options["journal_size"] == "")
options["journal_size"] = DEFAULT_HYBRID_JOURNAL;
}
else
{
options.erase("disable_meta_fsync");
options.erase("disable_journal_fsync");
}
for (auto & dev: devinfo)
{
if (!hybrid || dev.is_hdd)

View File

@ -3,6 +3,7 @@
#include "disk_tool.h"
#include "rw_blocking.h"
#include "str_util.h"
#define DM_ST_EMPTY 0
#define DM_ST_TO_READ 1
@ -110,17 +111,17 @@ int disk_tool_t::resize_parse_params()
new_journal_device = options.find("new_journal_device") != options.end()
? options["new_journal_device"] : dsk.journal_device;
new_data_offset = options.find("new_data_offset") != options.end()
? strtoull(options["new_data_offset"].c_str(), NULL, 10) : dsk.data_offset;
? parse_size(options["new_data_offset"]) : dsk.data_offset;
new_data_len = options.find("new_data_len") != options.end()
? strtoull(options["new_data_len"].c_str(), NULL, 10) : dsk.data_len;
? parse_size(options["new_data_len"]) : dsk.data_len;
new_meta_offset = options.find("new_meta_offset") != options.end()
? strtoull(options["new_meta_offset"].c_str(), NULL, 10) : dsk.meta_offset;
? parse_size(options["new_meta_offset"]) : dsk.meta_offset;
new_meta_len = options.find("new_meta_len") != options.end()
? strtoull(options["new_meta_len"].c_str(), NULL, 10) : 0; // will be calculated in resize_init()
? parse_size(options["new_meta_len"]) : 0; // will be calculated in resize_init()
new_journal_offset = options.find("new_journal_offset") != options.end()
? strtoull(options["new_journal_offset"].c_str(), NULL, 10) : dsk.journal_offset;
? parse_size(options["new_journal_offset"]) : dsk.journal_offset;
new_journal_len = options.find("new_journal_len") != options.end()
? strtoull(options["new_journal_len"].c_str(), NULL, 10) : dsk.journal_len;
? parse_size(options["new_journal_len"]) : dsk.journal_len;
if (new_meta_device == dsk.meta_device &&
new_journal_device == dsk.journal_device &&
new_data_offset == dsk.data_offset &&

View File

@ -105,9 +105,9 @@ int disk_tool_t::upgrade_simple_unit(std::string unit)
{
return 1;
}
uint64_t j_o = stoull_full(options["journal_offset"]);
uint64_t m_o = stoull_full(options["meta_offset"]);
uint64_t d_o = stoull_full(options["data_offset"]);
uint64_t j_o = parse_size(options["journal_offset"]);
uint64_t m_o = parse_size(options["meta_offset"]);
uint64_t d_o = parse_size(options["data_offset"]);
bool m_is_d = options["meta_device"] == "" || options["meta_device"] == options["data_device"];
bool j_is_m = options["journal_device"] == "" || options["journal_device"] == options["meta_device"];
bool j_is_d = j_is_m && m_is_d || options["journal_device"] == options["data_device"];

View File

@ -107,10 +107,12 @@ uint64_t stoull_full(const std::string & str, int base)
return r;
}
uint64_t parse_size(std::string size_str)
uint64_t parse_size(std::string size_str, bool *ok)
{
if (!size_str.length())
{
if (ok)
*ok = false;
return 0;
}
uint64_t mul = 1;
@ -130,7 +132,8 @@ uint64_t parse_size(std::string size_str)
uint64_t size = stoull_full(size_str, 0) * mul;
if (size == 0 && size_str != "0" && (size_str != "" || mul != 1))
{
return UINT64_MAX;
if (ok)
*ok = false;
}
return size;
}

View File

@ -7,7 +7,7 @@
std::string base64_encode(const std::string &in);
std::string base64_decode(const std::string &in);
uint64_t parse_size(std::string size_str);
uint64_t parse_size(std::string size_str, bool *ok = NULL);
std::string strtolower(const std::string & in);
std::string trim(const std::string & in, const char *rm_chars = " \n\r\t");
std::string str_replace(const std::string & in, const std::string & needle, const std::string & replacement);