From a537db8909eee7ed19eb2d05a33623c25c4d931f Mon Sep 17 00:00:00 2001 From: Vitaliy Filippov Date: Mon, 22 Aug 2022 00:31:30 +0300 Subject: [PATCH] Add documentation for the new "vitastor-disk" tool --- README-ru.md | 1 + README.md | 1 + docs/intro/features.en.md | 2 +- docs/intro/features.ru.md | 2 +- docs/usage/cli.en.md | 19 --- docs/usage/cli.ru.md | 19 --- docs/usage/disk.en.md | 245 +++++++++++++++++++++++++++++++++++++ docs/usage/disk.ru.md | 248 ++++++++++++++++++++++++++++++++++++++ src/cli_create.cpp | 5 +- src/disk_tool.cpp | 128 +++++++++++++------- src/disk_tool_prepare.cpp | 10 ++ src/disk_tool_resize.cpp | 13 +- src/disk_tool_upgrade.cpp | 6 +- src/str_util.cpp | 7 +- src/str_util.h | 2 +- 15 files changed, 608 insertions(+), 100 deletions(-) create mode 100644 docs/usage/disk.en.md create mode 100644 docs/usage/disk.ru.md diff --git a/README-ru.md b/README-ru.md index 2a766bb7..33ce6b3e 100644 --- a/README-ru.md +++ b/README-ru.md @@ -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) diff --git a/README.md b/README.md index d4cf6b13..e4071175 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/docs/intro/features.en.md b/docs/intro/features.en.md index 0e879241..19947510 100644 --- a/docs/intro/features.en.md +++ b/docs/intro/features.en.md @@ -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 diff --git a/docs/intro/features.ru.md b/docs/intro/features.ru.md index 4f2a013d..b11b3baa 100644 --- a/docs/intro/features.ru.md +++ b/docs/intro/features.ru.md @@ -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 diff --git a/docs/usage/cli.en.md b/docs/usage/cli.en.md index cc94bed5..a21e19ab 100644 --- a/docs/usage/cli.en.md +++ b/docs/usage/cli.en.md @@ -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 ``..`` to `` `vitastor-cli alloc-osd` Allocate a new OSD number and reserve it by creating empty `/osd/stats/` key. - -## simple-offsets - -`vitastor-cli simple-offsets ` - -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 -``` diff --git a/docs/usage/cli.ru.md b/docs/usage/cli.ru.md index e71ba5f1..3704f6da 100644 --- a/docs/usage/cli.ru.md +++ b/docs/usage/cli.ru.md @@ -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 ] @ Атомарно выделить новый номер OSD и зарезервировать его, создав в etcd пустой ключ `/osd/stats/`. - -## simple-offsets - -`vitastor-cli simple-offsets ` - -Рассчитать смещения для простого и тупого создания 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 -``` diff --git a/docs/usage/disk.en.md b/docs/usage/disk.en.md new file mode 100644 index 00000000..ce4d9077 --- /dev/null +++ b/docs/usage/disk.en.md @@ -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 `` 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 `` 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 + Create 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 Use partition for data +--meta_device Use partition for metadata (optional) +--journal_device Use partition 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 ` + +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.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 [--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] [device2 device3 ...]` + +Manipulate Vitastor OSDs using systemd by their device paths. + +Commands are passed to `systemctl` with `vitastor-osd@` units as arguments. + +When `--now` is added to enable/disable, OSDs are also immediately started/stopped. + +## read-sb + +`vitastor-disk read-sb ` + +Try to read Vitastor OSD superblock from `` and print it in JSON format. + +## write-sb + +`vitastor-disk write-sb ` + +Read JSON from STDIN and write it into Vitastor OSD superblock on ``. + +## udev + +`vitastor-disk udev ` + +Try to read Vitastor OSD superblock from `` and print variables for udev. + +## exec-osd + +`vitastor-disk exec-osd ` + +Read Vitastor OSD superblock from `` 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 ` + +Read Vitastor OSD superblock from `` 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] ` + +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 ` + +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 ` + +Dump metadata in JSON format. + +## write-meta + +`vitastor-disk write-meta ` + +Write metadata from JSON taken from standard input in the same format as produced by `dump-meta`. + +## simple-offsets + +`vitastor-disk simple-offsets ` + +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 +``` diff --git a/docs/usage/disk.ru.md b/docs/usage/disk.ru.md new file mode 100644 index 00000000..448385a5 --- /dev/null +++ b/docs/usage/disk.ru.md @@ -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 режима. В первом режиме вы указываете список устройств ``, +которые должны быть целыми дисками (не разделами). На них автоматически создаются +разделы и инициализируются OSD. + +Во втором режиме вместо списка устройств вы указываете пути к отдельным устройствам +`--data_device`, `--journal_device` и/или `--meta_device`, которые должны быть +уже существующими GPT-разделами. В этом случае инициализируется ровно один OSD. + +Команде требуются утилиты `vitastor-cli`, `wipefs`, `sfdisk` и `partprobe` (из состава parted). + +Опции для автоматического режима: + +``` +--osd_per_disk + Создавать по несколько () 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 Использовать раздел для данных +--meta_device Использовать раздел для метаданных (опционально) +--journal_device Использовать раздел для журнала (опционально) +--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 ` + +Обновить 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.service`. + +Имейте в виду, что процедура обновления не атомарна и при прерывании может уничтожить данные OSD, +так что обновляйте ваши OSD по очереди. + +Команде требуется утилита `sfdisk`. + +## resize + +`vitastor-disk resize [--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] [device2 device3 ...]` + +Команды управления OSD по путям дисков через systemd. + +Команды транслируются `systemctl` с сервисами `vitastor-osd@` в виде аргументов. + +Когда к командам включения/выключения добавляется параметр `--now`, OSD также сразу +запускаются/останавливаются. + +## read-sb + +`vitastor-disk read-sb ` + +Прочитать суперблок OSD с диска `` и вывести его в формате JSON. + +## write-sb + +`vitastor-disk write-sb ` + +Прочитать JSON со стандартного ввода и записать его в суперблок OSD на диск ``. + +## udev + +`vitastor-disk udev ` + +Прочитать суперблок OSD с диска `` и вывести переменные для udev. + +## exec-osd + +`vitastor-disk exec-osd ` + +Прочитать суперблок OSD с диска `` и запустить исполняемый файл OSD с параметрами оттуда. + +Команда предназначена для использования из скриптов запуска (например, из сервисов systemd). + +## pre-exec + +`vitastor-disk pre-exec ` + +Прочитать суперблок OSD с диска `` и провести проверки OSD перед запуском. + +На данный момент только отключает кэш диска или проверяет, что он отключён, если в параметрах +OSD отключены fsync-и. + +Команда предназначена для использования из скриптов запуска (например, из сервисов systemd). + +## dump-journal + +`vitastor-disk dump-journal [OPTIONS] ` + +Вывести журнал в человекочитаемом или в JSON (с опцией `--json`) виде. + +Опции: + +``` +--all Просканировать всю область журнала и вывести даже старые записи +--json Вывести журнал в формате JSON +--format entries (По умолчанию) Вывести только актуальные записи журнала без данных +--format data Вывести только актуальные записи журнала с данными +--format blocks Вывести массив блоков журнала, а в каждом массив актуальных записей без данных +``` + +## write-journal + +`vitastor-disk write-journal ` + +Записать журнал из JSON со стандартного ввода в формате, аналогичном `dump-journal --json --format data`. + +## dump-meta + +`vitastor-disk dump-meta ` + +Вывести метаданные в формате JSON. + +## write-meta + +`vitastor-disk write-meta ` + +Записать метаданные из JSON со стандартного ввода в формате, аналогичном `dump-meta`. + +## simple-offsets + +`vitastor-disk simple-offsets ` + +Рассчитать смещения для старого ("простого и тупого") создания 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 +``` diff --git a/src/cli_create.cpp b/src/cli_create.cpp index a86d3456..1c802cb5 100644 --- a/src/cli_create.cpp +++ b/src/cli_create.cpp @@ -526,8 +526,9 @@ std::function 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) { diff --git a/src/disk_tool.cpp b/src/disk_tool.cpp index c6cbc16e..516d30a5 100644 --- a/src/disk_tool.cpp +++ b/src/disk_tool.cpp @@ -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 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 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" + " Create 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 Create OSDs on each disk (default 1)\n" - " --data_device Create a single OSD using partition for data\n" - " --meta_device Create a single OSD using partition for metadata\n" - " --journal_device Create a single OSD using partition 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 Use partition for data\n" + " --meta_device Use partition for metadata (optional)\n" + " --journal_device Use partition 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 \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.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.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 [--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 ] resize data area so it starts at \n" - " [--new_data_len ] resize data area to bytes\n" - " [--new_meta_device ] use for new metadata\n" - " [--new_meta_offset ] make new metadata area start at \n" - " [--new_meta_len ] make new metadata area bytes long\n" - " [--new_journal_device ] use for new journal\n" - " [--new_journal_offset ] make new journal area start at \n" - " [--new_journal_len ] make new journal area 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] [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]] \n" + "vitastor-disk dump-journal [OPTIONS] \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 \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 \n" " Dump metadata in JSON format.\n" "\n" "vitastor-disk write-meta \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 \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 for command details or vitastor-disk --help --all for all details.\n" ; diff --git a/src/disk_tool_prepare.cpp b/src/disk_tool_prepare.cpp index 278df3bd..a1187903 100644 --- a/src/disk_tool_prepare.cpp +++ b/src/disk_tool_prepare.cpp @@ -517,8 +517,13 @@ int disk_tool_t::prepare(std::vector devices) if (max_other_percent > 100) max_other_percent = 100; std::vector 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 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) diff --git a/src/disk_tool_resize.cpp b/src/disk_tool_resize.cpp index 9e5c7065..9f1e289f 100644 --- a/src/disk_tool_resize.cpp +++ b/src/disk_tool_resize.cpp @@ -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 && diff --git a/src/disk_tool_upgrade.cpp b/src/disk_tool_upgrade.cpp index 00fc2e9b..60aec357 100644 --- a/src/disk_tool_upgrade.cpp +++ b/src/disk_tool_upgrade.cpp @@ -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"]; diff --git a/src/str_util.cpp b/src/str_util.cpp index d0bbb252..abd8801f 100644 --- a/src/str_util.cpp +++ b/src/str_util.cpp @@ -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; } diff --git a/src/str_util.h b/src/str_util.h index ff74109d..4e0d55e8 100644 --- a/src/str_util.h +++ b/src/str_util.h @@ -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);