shardmanctl

shardmanctl — вспомогательный клиент командной строки и средство развёртывания Shardman

Синтаксис

shardmanctl [общие_параметры] daemon check -n | --nodes имена_узлов:порт

shardmanctl [общие_параметры] cleanup [ -p | --processrepgroups ] --after-node-operation --after-rebalance

shardmanctl [общие_параметры] config generate [ -f | --file имя_файла]

shardmanctl [общие_параметры] config verify [ -f | --file имя_файла]

shardmanctl [общие_параметры] config get [ -f | --file ] [ -c | --choose-revision ] [ -r | --revision ]

shardmanctl [общие_параметры] config revisions rm [ -r | --revision ] [ -y | --yes ]

shardmanctl [общие_параметры] config update [[ -f | --file файл_конфигурации_stolon|файл_конфигурации_shardman] | текст_конфигурации [ --force ] [ -p | --patch ] [ -w | --wait длительность]]

shardmanctl [общие_параметры] config rollback [ -r | --revision ] [ -w | --wait длительность] [ --force ]

shardmanctl [общие_параметры] config update credentials [ -u | --user ] [ -p | --password ] [ -k | --ssl-key ] [ -c | --ssl-cert ] [ -w | --wait длительность] [ -f | --force ] [ -y | --yes ]

shardmanctl [общие_параметры] config revisions [ -f | --format json|text ]

shardmanctl [общие_параметры] config revisions set --keep-config-revisions

shardmanctl [общие_параметры] config update ip [ -u | ip_1=ip_2,hostname_1=hostname_2 ] [ -y | --yes ]

shardmanctl [общие_параметры] config update fdw [ -y | --yes ]

shardmanctl [общие_параметры] cluster repfactor set --value значение

shardmanctl [общие_параметры] cluster start

shardmanctl [общие_параметры] cluster stop [ -y | --yes ]

shardmanctl [общие_параметры] cluster topology [ -f | --format table|json|text ]

shardmanctl [общие_параметры] forall --sql query [ --twophase]

shardmanctl [общие_параметры] getconnstr --all

shardmanctl [общие_параметры] init [ -y | --yes ] [ -f | --spec-file имя_файла_конфигурации] | текст_конфигурации

shardmanctl [общие_параметры] intcheck [ -s | --system ] [ -c | --catalog ] [ -u | --user ] [ -o | --output ] [ -n | --node узел]

shardmanctl [общие_параметры] load [ -b | --batch-size предел_числа_строк] [ --destination-fields список_полей] [ --distributed-keys список_типов_ключей] [ -D | --delimiter символ] [ --null_marker строка] [ -e | --escape символ] [ -f | --file входной_файл] [ -F | --format text | csv ] [ -j | --jobs число_заданий] [ -q | --quote символ] [ --reject-file имя_файла] [ --schema имя_файла] [ --source файл | postgres ] [ --source-connstr строка_подключения] [ --source-fields список_полей] [ --source-table таблица|представление|функция] [ -t | --table целевая_таблица] [ -h | --help ]

shardmanctl [общие_параметры] nodes add -n | --nodes имена_узлов [ --no-rebalance]

shardmanctl [общие_параметры] nodes start -n | --nodes имена_узлов [ --no-wait]

shardmanctl [общие_параметры] nodes restart -n | --nodes имена_узлов [ --no-wait]

shardmanctl [общие_параметры] nodes stop -n | --nodes имена_узлов [ --no-wait]

shardmanctl [общие_параметры] nodes replace --old старый_узел --new новый_узел

shardmanctl [общие_параметры] nodes rm -n | --nodes имена_узлов

shardmanctl [общие_параметры] probackup [ init | archive-command | backup | checkdb | delete | merge | restore | set-config | show | validate | show-config ] [ параметры_подкоманды]

shardmanctl [общие_параметры] rebalance [ -f | --force ]

shardmanctl [общие_параметры] restart [ -y | --yes ] [ --no-wait ]

shardmanctl [общие_параметры] restart rolling [ -y | --yes ] [ --restore-masters ] [ --upgrade ]

shardmanctl [общие_параметры] set pgParam1=value1 [pgParam2=value2 [...]] [ -y | --yes ] [ -w | --wait длительность] [ -f | --force ]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента add -n | --node имена_узлов

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента master set [ -y | --yes ] -n | --node имена_узлов

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента master reset [ -y | --yes ]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента reset [ -y | --yes ] [ --new-primary | -p ]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента rm -n | --node имена_узлов [ -f | --force ]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента switch [ --new-primary имена_узлов]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента start [ --no-wait ] [ -n | --node имя_узла]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента stop [ -n | --node имя_узла]

shardmanctl [общие_параметры] shard -s | --shard имя_сегмента replicas reinit [ --no-wait ] [ -y | --yes ] [ -n | --node имена_узлов]

shardmanctl [общие_параметры] status [ --filter all | dictionary | primary | metadata | rg | shardmand | store | топология | restart_required_params ] [ -f | --format текст | json ] [ -s | --sort узел | группа_репликации | статус ]

shardmanctl [общие_параметры] status transactions [ -r | --repgroup имя_группы_репликации]

shardmanctl [общие_параметры] store dump [ -f | --file имя_файла]

shardmanctl [общие_параметры] store restore [ --delete-old-keys ] [ -f | --file имя_файла] [ -y | --yes ]

shardmanctl [общие_параметры] store get [ -a | --alias кластер | ковш | группы_репликации | конфигурация_stolon | конфигурация ] [ -k | --key имя_ключа] [ -f | --file имя_файла]

shardmanctl [общие_параметры] store keys

shardmanctl [общие_параметры] store set [ -a | --alias кластер | ковш | группы_репликации | конфигурация_stolon | конфигурация ] [ -k | --key имя_ключа] [ -f | --file имя_файла]

shardmanctl [общие_параметры] store lock [ -f | --format текст | json ]

shardmanctl [общие_параметры] tables sharded info [ -t | --table таблица ]

shardmanctl [общие_параметры] tables sharded list

shardmanctl [общие_параметры] tables sharded norebalance

shardmanctl [общие_параметры] tables sharded partmove [ -t | --table таблица ] [ -s | --shard имя_сегмента ] [ -p | --partnum номер_секции ]

shardmanctl [общие_параметры] tables sharded rebalance [ -t | --table таблица ] [ --skip-run-rebalance ]

shardmanctl [общие_параметры] upgrade

shardmanctl [общие_параметры] bench init [ --schema-type single|simple|shardman|custom ] [ -S | --schema-file имя_файла] [ -s | --scale значение_масштабирования] [ --partitions значение_секций] [ -n | --no-vacuum ] [ -F | --fillfactor значение_коэффициента_заполнения]

shardmanctl [общие_параметры] bench run [ --schema-type single|simple|shardman|custom ] [ -f | --file имя_файла] [ -c | --client число_клиентов] [ -C | --connect ] [ --full-output ] [ -j | --jobs число_процессов] [ -s | --scale коэффициент_масштаба] [ -T | --time секунды] [ -t | --transactions число_транзакций] [ -P | --progress секунды] [ -R | --rate скорость_передачи] [ -M | --protocol режим_запросов]

shardmanctl [общие_параметры] bench cleanup

shardmanctl [общие_параметры] bench generate [ -c | --config файл_конфигурации] [ -o | --output-file имя_файла]

shardmanctl [общие_параметры] script [ -s | --shard имя_сегмента] [[ -f | --file имя_файла | --sql query]]

shardmanctl [общие_параметры] psql -s | --shard имя_сегмента

shardmanctl [общие_параметры] daemon set [ --session-log-level | debug | info | warn | error ] [ --session-log-format | text | json ] [ --session-log-nodes ]

shardmanctl [общие_параметры] history [ -r | --reverse ] [ -f | --format текст | json ] [ -l | --limit число_команд ]

Здесь общие_параметры могут принимать следующие значения:

[ --cluster-name имя_кластера ] [ --log-level error | warn | info | debug ] [ --monitor-port порт] [ --retries число_повторов] [ --session-timeout секунды] [ --store-endpoints адреса_хранилища] [ --store-ca-file файл_сертификата_ca] [ --store-cert-file файл_сертификата_клиента] [ --store-key частный_ключ_клиента] [ --store-timeout длительность] [ --version] [ -h | --help ]

Описание #

shardmanctl — это утилита для управления кластером Shardman.

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

Команда cleanup используется для очистки после сбоя команды nodes add или команды rebalance утилиты shardmanctl . Окончательные изменения в хранилище etcd вносятся в конце выполнения команды. Это упрощает процесс очистки. Во время очистки неполные определения звена и определения соответствующих групп репликации удаляются из метаданных etcd. Определения соответствующих сторонних серверов удаляются из метаданных СУБД остальных групп репликации. Поскольку процесс cleanup может удалять данные, по умолчанию инструмент работает исключительно в режиме отчёта: он показывает только те действия, которые необходимо выполнить во время фактической очистки. Для выполнения реальной очистки нужно добавить ключ -p. Использование команды подробно описано в Подразделе «Выполнение очистки».

Команда daemon check используется, чтобы проверить, что демон shardmand работает на узлах, указанных в параметре --nodes, и настроен для того же кластера, что и shardmanctl . Использование команды подробно описано в Подразделе «Проверка работы службы shardmand на узлах».

Команда init используется для регистрации нового кластера Shardman в хранилище etcd или переинициализации существующего (будет задана новая конфигурация кластера, удалены все данные и узлы). В режиме инициализации утилита shardmanctl считывает спецификацию кластера, обрабатывает её и сохраняет в хранилище etcd как части двух документов JSON: ClusterSpec — как часть shardman/cluster0/data/cluster и LadleSpec — как часть shardman/cluster0/data/ladle (cluster0 — это имя кластера по умолчанию, используемое утилитами Shardman). Общие параметры, связанные с хранилищем etcd, например --store-endpoints, также сохраняются в хранилище etcd и передаются всем службам Shardman, запущенным расширением shardmand. Формат файла инициализации Shardman подробно описан в разделе sdmspec.json, а использование команды init — в Подразделе «Регистрация кластера Shardman».

Команда config generate используется для создания шаблона sdmspec.json по умолчанию. Результат записывается в стандартный вывод. Чтобы записать результат в файл, используйте флаг -f имя_файла. Формат файла инициализации Shardman описан в sdmspec.json.

Команда config verify используется для проверки корректности входного файла инициализации Shardman. По умолчанию конфигурация считывается со стандартного ввода. Чтобы конфигурация читалась из файла, используйте флаг -f имя файла. За описанием формата файла инициализации Shardman обратитесь к sdmspec.json.

Команда config get используется для вывода текущей полной конфигурации кластера или конфигурации указанной версии. Текущая конфигурация кластера берётся из хранилища кластера. Формат файла инициализации Shardman описан в sdmspec.json.

Команда config update используется для обновления конфигурации stolon или конфигурации всего Shardman. Новая конфигурация применяется ко всем группам репликации и сохраняется в ключе etcd shardman/cluster0/data/cluster. Обратите внимание, что config update может привести к перезапуску СУБД.

Команда forall используется для выполнения оператора SQL во всех группах репликации в кластере Shardman.

Команда getconnstr используется для получения строки подключения libpq и подключения к кластеру в роли администратора.

Команда load используется для загрузки данных из текстового файла в распределённую таблицу или для загрузки схемы базы данных из базы данных PostgreSQL в Shardman. При загрузке данных из файла поддерживаются форматы text и csv (файлы могут быть сжаты при помощи gzip, тогда при чтении они декодируются автоматически); если нужно прочесть данные из stdin, то следует указать параметр --file=-. Процесс загрузки данных можно оптимизировать, указав число параллельных рабочих процессов (ключ -j).

Команда nodes add используется для добавления новых узлов в кластер Shardman. Со стандартной политикой размещения cross узлы добавляются в кластер в виде звеньев. На каждом узле в звене работает ведущий экземпляр СУБД и, возможно, несколько реплик других узлов этого звена. Число реплик определяется параметром конфигурации Repfactor. Таким образом, каждое звено состоит из Repfactor + 1 узлов и может выдержать потерю Repfactor узлов.

При ручной политике размещения каждый новый узел добавляется как группа репликации, состоящая из одного ведущего сервера. После добавления ведущих узлов можно добавить реплики в новую группу репликации, используя команду shard add.

Утилита shardmanctl выполняет операцию nodes add в несколько этапов:

  1. Получает глобальную блокировку метаданных.

  2. Для каждого указанного узла проверяет, работает ли на нём служба shardmand и видит ли он текущую конфигурацию кластера.

  3. Вычисляет службы, которые должны присутствовать на каждом узле, и сохраняет эту информацию в etcd как часть Layout объекта shardman/cluster0/data/ladle.

  4. Создаёт конфигурацию для новых кластеров stolon (также называемых группами репликации) и инициализирует их.

  5. Регистрирует добавленные группы репликации в ключе etcd shardman/cluster0/data/ladle.

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

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

  8. Для каждой новой группы репликации в кластере копирует все схемы и данные схем shardman из случайно выбранной существующей группы репликации в новую группу, а также проверяет, что расширение Shardman установлено в новой группе репликации, и пересчитывает OID, используемые в таблицах конфигурации расширения.

  9. В каждой существующей группе репликации определяет сторонние серверы, ссылающиеся на новую группу репликации, и воссоздаёт определения сторонних серверов в новой группе репликации.

  10. Пересоздаёт все секции сегментированных таблиц как сторонние таблицы, ссылающиеся на данные из старых групп репликации, и регистрирует изменения в хранилище etcd.

  11. Для каждой новой группы репликации копирует данные глобальной таблицы из существующих групп репликации в новую.

  12. Выполняет перебалансировку секции сегментированных таблиц. В процессе перебалансировки для каждой сегментированной таблицы итерационно определяется группа репликации с максимальным и минимальным количеством секций и создаётся задача на перемещение одной секции в группу репликации с минимальным количеством секций. Этот процесс повторяется, пока max - min > 1. Для перемещения секций используется логическая репликация. Секции совместно размещённых таблиц перемещаются совместно с секциями распределённых таблиц, на которые они ссылаются. Можно пропустить этот шаг, используя --no-rebalance.

Использование данной команды подробно описано в Подразделе «Добавление узлов в кластер Shardman».

Команда nodes rm используется для удаления узлов из кластера Shardman. В режиме manual удаляются только указанные узлы. Если узел является последним в репликационной группе, то удаляется и вся группа репликации. В режиме cross команда удаляет из кластера звенья, содержащие указанные узлы. Последнее звено в кластере не может быть удалено. Любые данные (например, секции сегментированных отношений) в удалённых группах репликации переносятся в оставшиеся группы посредством логической репликации, а все ссылки на удалённые группы репликации (включая определения сторонних серверов) удаляются из метаданных оставшихся групп репликации. Наконец, обновляются метаданные в etcd. Использование команды подробно описано в Подразделе «Удаление узлов из кластера Shardman».

Команда probackup выполняет резервное копирование и восстановление кластера Shardman, используя утилиту резервного копирования pg_probackup. Логика команды probackup описана в разделе Резервное копирование и восстановление резервных копий Shardman посредством pg_probackup. Более подробное использование команды probackup описано в Подразделе « probackup ».

Команда rebalance используется для равномерной перебалансировки сегментированных таблиц в кластере. Это может быть полезно, например, если перебалансировка не выполнялась при добавлении узлов в кластер. Если не указан параметр --force, таблицы с разделами, перемещёнными вручную, будут пропущены.

Команда cleanup с флагом --after-rebalance используется для выполнения очистки после сбоя команды rebalance. На каждом узле она удаляет подписки и публикации, оставшиеся после команды rebalance, а также таблицы, в которых хранятся данные частично переданных секций сегментированных таблиц.

Команда cluster repfactor set используется для установки значения коэффициента репликации для кластера Shardman. Эту команду можно использовать только в ручном (manual) режиме топологии кластера. Значение нового коэффициента репликации передаётся через флаг командной строки --value коэффициент_репликации.

Команда cluster start используется для запуска всех экземпляров PostgreSQL, остановленных командой cluster stop. Чтобы команда работала, должен быть запущен shardmand.

Команда cluster stop используется для остановки всех экземпляров PostgreSQL для кластера Shardman. При этом демоны shardmand продолжают работать.

Команда cluster topology используется для визуализации топологии кластера. По умолчанию топология возвращается в виде таблицы. Если необходимо получить представление в формате JSON, используйте флаг --format json|text.

Команда restart используется для перезапуска кластера Shardman, включая все экземпляры shardmand. Если экземпляры PostgreSQL были предварительно остановлены командой cluster stop, они будут запущены. Команда возвращает управление после перезапуска всех ведущих серверов в кластере.

Команда set используется для установки одного или нескольких параметров экземпляров СУБД кластера Shardman. Параметры передаются в командной строке в качестве аргументов, каждый из них имеет вид param=value. Эта команда является аналогом shardmanctl config update -p для изменения параметров базы данных.

Команда status используется для отображения состояния работоспособности подсистем кластера Shardman. Она может отображать состояние нескольких компонентов: хранилища, метаданных, shardmand, групп репликации, ведущих серверов, словаря и перезапуска необходимых параметров. Если нужна информация об определённых подсистемах, можно использовать параметр --filter. Также status поддерживает сортировку своих результатов по значениям status, node или replication group и выводит их в виде таблицы (table), текста (text) или в формате JSON (json) на stdout, значение по умолчанию — table. Использование команды описано в разделе «Получение статуса подсистем кластера».

Команда store dump получает все ключи и их значения из хранилища etcd и выводит их в --file, причём значение - используется для вывода в стандартный вывод (по умолчанию). Она предназначена для отладки, поэтому во время выполнения могут возникать некоторые некритичные ошибки, но при этом вся доступная информация будет сохранена. Будут выгружены только ключи для текущего кластера (с текущим префиксом кластера, например shardman/cluster0/). Использование команды описано в разделе «Выгрузка всех ключей из хранилища для отладки конфигурации ошибок».

Команда store get получает конкретное значение из хранилища по имени ключа. Ожидается, что это значение JSON, поэтому, если это не так (что не запрещено), могут возникать некоторые некритичные ошибки. Ключ для извлечения из хранилища можно указать в параметре --key; несколько ключей имеют псевдонимы — короткие имена для удобства использования. Чтобы получить ключ по его псевдониму, используйте параметр --alias с одним из доступных псевдонимов (используйте --help или примеры ниже для справки). Также псевдонимы stolonspec и spec можно использовать для явного управления начальным кластером и конфигурацией stolon, не извлекая их из полной конфигурации кластера. Рекомендуется использовать существующие псевдонимы вместо полных имён ключей, так как при обработке псевдонимов есть некоторые дополнительные проверки, которые помогают достичь более надёжных результатов. По умолчанию ключ выводится на стандартный вывод (явно — с параметром --file=-), но может быть выведен в любой желаемый файл. Использование команды описано в разделе «Получение текущей конфигурации stolon».

Команда store keys показывает все сохранённые ключи для текущего кластера (с префиксом кластера) и его псевдонимов. Псевдонимы stolonspec и spec не показаны, так как они являются частями других ключей. Использование команды описано в разделе «Получение имён ключей кластера и ковша для текущего кластера».

Команда store set создаёт или перезаписывает один конкретный ключ в хранилище. Это не обязательно должно быть значение JSON для случайного ключа, но если это один из ключей с известным сопоставлением псевдонимов (например, ladle или cluster), команда не примет некорректные структуры JSON. Как и store get команда store set принимает имя ключа в параметре --key или --alias и входной файл в параметре --file (stdin указывается со значением -). Использование команды описано в разделе «Установка новой конфигурации для кластера».

Команда store lock показывает информацию о текущей блокировке метаданных кластера. Если блокировки не существует, возвращает Lock not found. Отображает идентификатор кластера, команду, которая получила блокировки, имя узла и время блокировки. Вы можете указать в параметре --format формат вывода: json или text (по умолчанию). Использование команды описано в разделе «Вывод информации о текущей блокировке метаданных кластера».

Команда upgrade используется для обновления версии расширения PostgreSQL Shardman на всех узлах кластера. Перед обновлением расширений необходимо установить новые пакеты и выполнить команду restart. В результате выполнения upgrade утилиты обновят shardman и все остальные расширения на сервере.

Иногда после запуска команды upgrade или некоторых действий пользователя при выводе команды status могут обнаруживаться ошибки словаря. Они возникают в том числе потому, что значения полей srvoptions таблицы pg_foreign_server отличаются от ожиданий системы. Чтобы решить эту проблему, воспользуйтесь командой config update fdw, которая вернёт srvoptions в ожидаемое состояние.

Примечание

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

Справка по командной строке

В этом разделе описываются команды shardmanctl. Общие параметры команд Shardman описаны в разделе «Общие параметры».

cleanup #

Синтаксис:

shardmanctl [общие_параметры] cleanup [-p|--processrepgroups] --after-node-operation|--after-rebalance

Выполняет очистку после команды nodes add или rebalance.

-p имена_узлов
--processrepgroups=имена_узлов #

Выполняет фактическую очистку. По умолчанию утилита показывает только действия, которые необходимо выполнить во время фактической очистки. За дополнительными сведениями обратитесь к разделу Подразделу «Выполнение очистки».

--after-node-operation #

Выполняет очистку после сбоя команды nodes add.

--after-rebalance #

Выполняет очистку после сбоя команды rebalance.

config update credentials #

Синтаксис:

shardmanctl [общие_параметры] config update credentials [-u | --user] [-p | --password] [-k | --ssl-key] [-c | --ssl-cert] [-w|--wait длительность] [--force] [-y | --yes] [--from-primary-cluster]

Изменяет пароль или сертификат/ключ пользователя для подключения к кластеру Shardman. Изменяет только тип аутентификации, указанный пользователем (scram-sha-256, ssl), а не сам тип.

-u
--user #

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

-p
--password #

Новый пароль.

-k
--ssl-key #

Новый SSL-ключ.

-c
--ssl-cert #

Новый SSL-сертификат.

-w
--wait #

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

--force #

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

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--from-primary-cluster #

Необходим для переноса конфигурации ведущего кластера на резервный. Если задан, следующие параметры конфигурации игнорируются: StandbyMode, StandbySettings, additionalReplicationSlots, createSlotsOnFollowers, additionalSlotsLagLimit.

cluster repfactor set #

Синтаксис:

shardmanctl [общие_параметры] cluster repfactor set --value новый_коэффициент_репликации

Устанавливает коэффициент репликации для режима топологии manual.

--value=новый_коэффициент_репликации #

Новое значение коэффициента репликации

cluster start #

Синтаксис:

shardmanctl [common_options] cluster start

Запускает все экземпляры сервера PostgreSQL.

cluster stop #

Синтаксис:

shardmanctl [общие_параметры] cluster stop [-y|--yes]

Останавливает все экземпляры сервера PostgreSQL.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

cluster standby enable #

Синтаксис:

shardmanctl [общие_параметры] cluster standby enable [-y | --yes][--no-wait]

Переключает кластер в режим резерва.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--no-wait #

Не ждать запуска keeper на резервном кластере.

cluster standby disable #

Синтаксис:

shardmanctl [общие_параметры] cluster standby disable [-y | --yes][--no-wait]

Проверяет, что все экземпляры кластера восстановлены на одну и ту же контрольную точку, после чего переключает кластер из режима резерва в режим ведущего. Как только режим резерва отключён, все экземпляры кластера читают ключ etcd shardman/<cluster_name>/data/last-replay-lsn/<shard_name>/<node_address>, который проверяет, что все экземпляры восстановлены на одну и ту же точку синхронизации.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--no-wait #

Не ждать запуска кластера.

Обратите внимание, что при наличии ошибок словаря после запуска кластера, их можно исправить с помощью команды shardmanctl config update fdw.

cluster standby catchup #

Синтаксис:

shardmanctl [общие_параметры] cluster standby catchup
[-s|--shard имя_сегмента]
[-n|--node имя_узла --soutce-datadir каталог]
[--remote-port порт]
[--remote-user имя_пользователя]
[-j|--jobs число]
[--log-directory путь]
[--log-to-console]

Копирует данные с экземпляра ведущего кластера на экземпляр резервного кластера, если один из резервных кластеров отстаёт. Запускается на узле резервного кластера и использует значение StandbySettings из файла sdmspec.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента резервного кластера.

-n имена_узлов
--node=имена_узлов #

Задаёт список добавляемых узлов резервного кластера, разделённых запятыми. Необходимо запускать на отстающем узле.

--source-datadir каталог #

Задаёт абсолютный путь к каталогу данных ведущего кластера.

--remote-port порт #

Указывает удалённый порт SSH для получения данных.

По умолчанию: 22.

--remote-user имя_пользователя #

Указывает удалённого пользователя, подключаемого по SSH для получения данных.

По умолчанию: postgres.

--jobs число
-j число #

Число параллельных потоков, которые используются pg_probackup при создании резервной копии.

По умолчанию: 1.

--log-directory путь #

Указывает каталог для хранения журналов команды catchup приложения pg_probackup.

--log-to-console #

Включает вывод журналов pg_probackup catchup на консоль.

cluster topology #

Синтаксис:

shardmanctl [общие_параметры] cluster topology -f|--format table|json|text

Выводит топологию кластера.

-f table|json|text
--format=table|json|text #

Формат вывода. За подробностями обратитесь к Подразделу «Отображение топологии кластера».

daemon check #

Синтаксис:

shardmanctl [общие_параметры] daemon check -n|--nodes имя_узла:порт

Проверяет shardmand на узлах.

-n имя_узла:порт
--nodes=имя_узла:порт #

Список узлов, на которых будет проведена проверка shardmand. За подробностями обратитесь к Подразделу «Проверка работы службы shardmand на узлах».

forall #

Синтаксис:

shardmanctl [общие_параметры] forall --sql запрос[ --sql запрос[ --sql запрос ...]] [--twophase]

Выполнение оператора SQL для всех групп репликации в кластере Shardman.

--sql query #

Указывает оператор, который должен быть выполнен.

--twophase #

Указывает использовать протокол двухфазной фиксации для выполнения оператора.

getconnstr #

Синтаксис:

shardmanctl [общие_параметры] getconnstr --all

Получает строку подключения libpq для подключения к кластеру в роли администратора.

--all #

Добавляет информацию о репликах в результат команды getconnstr.

init #

Синтаксис:

    shardmanctl [общие_параметры] init [-y|--yes] [-f|--spec-file имя_файла_конфигурации]|текст_конфигурации
   

Регистрирует новый кластер Shardman в хранилище etcd или повторно инициализирует уже существующий кластер, задавая новую конфигурацию кластера и удаляя все его данные и узлы.

-f имя_файла_конфигурации
--specfile=имя_файла_конфигурации #

Задаёт файл со строкой конфигурации кластера. Значение - означает стандартный ввод. По умолчанию строка передаётся в тексте_конфигурации. Использование данной команды подробно описано в разделе «Регистрация кластера Shardman».

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

intcheck #

Синтаксис:

    shardmanctl [общие_параметры] intcheck [-s|--system] [-u|--user] [-c|--catalog] [-o|--output]  [-n|--node узел]
   

Запускает pg_integrity_check на всех узлах кластера Shardman или на выбранном одном узле.

-s
--system #

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

-u
--user #

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

-c
--catalog #

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

-o
--output #

Пересчитать контрольные суммы и записать их в файл

-n имена_узлов
--node=имена_узлов #

Выполнять команду pg_integrity_check только на выбранном узле

load #

Синтаксис:

     shardmanctl [общие_параметры] load [ -b | --batch-size предел_числа_строк] [ --destination-fields список_полей]
     [ --distributed-keys список_типов_ключей] [ -D | --delimiter символ]
     [--null_marker строка] [ -e | --escape символ] [ -f | --file входной_файл]
     [ -F | --format текст|csv ] [ -j | --jobs общее_число_заданий] [ -q | --quote символ]
     [ --reject-file имя_файла] [ --schema имя_файла] [ --source файл|postgres]
     [ --source-connstr строка_подключения] [ --source-fields список_полей] [ --source-table исходная_таблица]
     [ -t | --table целевая_таблица]
   

Загрузка данных в кластер Shardman.

-b предел_числа_строк
--batch-size=предел_числа_строк #

Показывает список резервных копий кластера Shardman.

По умолчанию: 1000.

--destination-fields=список_полей #

Список полей целевой таблицы, разделённых запятыми. Если значение не задано, то используются все поля таблицы в порядке их объявления.

--distributed-keys=список_типов_ключей #

Список пар, разделённых запятыми. Каждая пара состоит из номера поля (начиная с ноля) и типа, разделённых двоеточием. Поддерживаются следующие типы: bool, char, float4, float8, int2, int4, int8, name, text, varchar и uuid.

-D символ
--delimiter=символ #

Задаёт символ, разделяющий столбцы в строках файла. Задаваемый символ должен быть однобайтовым.

По умолчанию: табуляция для текстового формата, запятая для формата CSV.

--null_marker=строка #

Указывает строку, представляющую нулевое значение.

По умолчанию: \N для текстового формата, пустая строка без кавычек для формата CSV.

-e символ
--escape=символ #

Задаёт символ, который будет выводиться перед символом данных, совпавшим со значением QUOTE. По умолчанию это тот же символ, что и QUOTE (то есть при появлении в данных кавычек они дублируются). Задаваемый символ должен быть однобайтовым. Этот параметр допускается только для режима CSV.

-f имя_файла
--file=имя_файла #

Имя файла входных данных (или - для стандартного ввода)

-F текст|csv
--format=текст|csv #

Формат входных данных. Возможные значения: text и csv.

По умолчанию: text.

-j число
--jobs=число #

Число параллельных процессов для загрузки данных.

По умолчанию равно числу групп репликации.

-q символ
--quote=символ #

Указывает символ кавычек, используемый для заключения данных в кавычки. По умолчанию это символ двойных кавычек. Задаваемый символ должен быть однобайтовым. Этот параметр поддерживается только для формата CSV.

--reject-file=имя_файла #

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

--schema=имя_файла #

Схема, определяющая правила передачи данных из PostgreSQL в Shardman. Если установлен данный параметр, то все остальные параметры не используются.

--source=файл|postgres #

Тип источника данных — file или postgres.

По умолчанию: file.

--source-connstr=строка #

Строка подключения к базе источника данных

--source-fields=список_полей #

Список полей исходной таблицы, разделённых запятыми. Если значение не задано, то используются все поля таблицы в порядке их объявления.

--source-table=таблица #

Исходная таблица, представление или функция (funcname(param1,...,paramN)).

-t таблица
--table=таблица #

Целевая таблица.

nodes add #

Синтаксис:

shardmanctl [общие_параметры] nodes add -n|--nodes имена_узлов [--no-rebalance]

Добавляет узлы в кластер Shardman.

-n имена_узлов
--nodes=имена_узлов #

Обязательный параметр.

Задаёт список добавляемых узлов, разделённых запятыми.

--no-rebalance #

Пропуск шага перебалансировки секций сегментированных таблиц. За подробностями обратитесь к Подразделу «Добавление узлов в кластер Shardman».

nodes rm #

Синтаксис:

shardmanctl [общие_параметры] nodes rm -n|--nodes имена_узлов

Удаляет узлы из кластера Shardman.

-n имена_узлов
--nodes=имена_узлов #

Задаёт список узлов, разделённых запятыми, которые необходимо удалить. За подробностями обратитесь к Подразделу «Удаление узлов из кластера Shardman».

probackup #

Синтаксис:

shardmanctl [общие_параметры] probackup
       [init|archive-command|backup|checkdb|delete|merge|restore|set-config|show|validate|show-config]
       [--log-to-console][--help]
       [параметры_подкоманды]

Создаёт резервную копию кластера Shardman и восстанавливает кластер Shardman из резервной копии, используя pg_probackup.

Список подкоманд: #

init #

Инициализирует новый каталог репозитория для резервной копии кластера Shardman, а также создаёт конфигурационный файл для подключения к хранилищу резервных копий, если для параметра --storage-type установлено значение S3.

archive-command #

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

backup #

Создаёт резервную копию кластера Shardman.

checkdb #

Проверяет кластер Shardman на наличие физических повреждений или логических нарушений.

delete #

Удаляет резервную копию кластера Shardman с заданным идентификатором backup_id.

merge #

Объединяет резервные копии, относящиеся к одной цепочке инкрементальных копий. При полном копировании резервные копии объединяются с их первой инкрементальной копией. При инкрементальном резервном копировании резервные копии объединяются с их родительской полной копией и всеми инкрементальными копиями между ними. После выполнения команды полная копия содержит все объединённые данные, а инкрементальные копии удаляются как ненужные. В текущей версии не поддерживается выполнение команды merge через интерфейс S3.

restore #

Восстанавливает кластер Shardman из выбранной резервной копии.

show #

Показывает список резервных копий кластера Shardman.

validate #

Проверяет целостность выбранной резервной копии кластера Shardman.

show-config #

Выводит все текущие параметры конфигурации pg_probackup, в том числе те, что содержатся в файле pg_probackup.conf, размещённом в каталоге каталог_копий/backups/имя_сегмента, а также те, что были заданы в командной строке.

set-config #

Добавляет указанные параметры в файл pg_probackup.conf или изменяет значения, добавленные в него ранее.

Следующие параметры можно использовать во всех подкомандах probackup:

--log-to-console #

Выводит полный журнал probackup в консоль. По умолчанию для каждой группы репликации файл журнала probackup появляется в каталоге резервного копирования (см. --backup-path ниже) в виде <backup-directory>/backup/log/pg_probackup-<repgroup-name>.log. Максимальный размер файла журнала составляет 20 МБ. По достижении этого лимита происходит ротация журнала при запуске команды shardmanctl probackup validate или shardmanctl probackup backup.

--help #

Показывает справку по подкомандам.

init #

Синтаксис:

shardmanctl [общие_параметры] probackup init
-B|--backup-path путь
-E|--etcd-path путь
[--remote-port порт]
[--remote-user имя_пользователя]
[--ssh-key путь]
[-t|--timeout секунды]
[-m|--maxtasks число_заданий]
[--storage-type mount|remote|S3]
[--s3-config-only]
[--s3-config-path путь]
[--s3-host узел_S3]
[--s3-port порт_S3]
[--s3-access-key ключ_доступа_S3]
[--s3-secret-key секретный_ключ_S3]
[--s3-bucket корзина_S3]
[--s3-region регион_S3]
[--s3-buffer-size размер_буфера_S3]
[--s3-retries число_повторов]
[--s3-timeout время]
[--s3-https]
[-y|--yes]

Инициализирует новый каталог репозитория для резервной копии кластера Shardman.

-B путь
--backup-path путь #

Требуется при отсутствии параметра --s3-config-only. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman.

-E путь
--etcd-path путь #

Требуется при отсутствии параметра --s3-config-only. Указывает путь к каталогу, в котором должны храниться копии etcd.

--remote-port порт #

Указывает удалённый порт SSH для экземпляров группы репликации.

По умолчанию: 22.

--remote-user имя_пользователя #

Указывает удалённого пользователя для подключения по SSH для экземпляров группы репликации.

По умолчанию: postgres.

--ssh-key путь #

Указывает закрытый ключ SSH для удалённого выполнения команд по SSH.

По умолчанию: $HOME/.ssh/id_rsa.

--storage-type mount|remote|S3 #

Тип хранилища резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно.

По умолчанию: remote.

--s3-config-path путь #

Задаёт путь к каталогу, в котором создаётся файл конфигурации S3 на всех узлах Shardman.

По умолчанию: <shardman-data-dir>/s3.config.

--s3-config-only #

Создаёт файлы конфигурации S3 на всех узлах, не инициализируя хранилище резервных копий. Этот флаг следует использовать, если параметр --storage-type имеет значение S3.

--s3-host узел #

Задаёт узел сервера S3 для подключения к S3-совместимому хранилищу.

--s3-port порт #

Задаёт порт сервера S3 для подключения к S3-совместимому хранилищу.

--s3-access-key ключ_доступа #

Задаёт ключ доступа сервера S3 для подключения к S3-совместимому хранилищу.

--s3-secret-key ключ_доступа #

Задаёт секретный ключ сервера S3 для подключения к S3-совместимому хранилищу.

--s3-bucket корзина #

Задаёт имя корзины для хранения резервных копий в S3-совместимом объектном хранилище.

--s3-region корзина #

Задаёт регион выбора сервера для S3-совместимого объектного хранилища.

--s3-buffer-size размер_буфера #

Размер буфера чтения/записи приложения pg_probackup для организации связи S3-совместимым объектным хранилищем, в МиБ.

По умолчанию: 16.

--s3-retries число_повторов #

Максимальное количество попыток выполнения запроса к S3 в случае сбоя.

По умолчанию: 5.

--s3-timeout время #

Максимальное время передачи объёма данных, заданного параметром --s3-buffer-size, в S3-совместимое объектное хранилище или из него (в секундах).

По умолчанию: 300.

--s3-https #

Задаёт протокол HTTPS для подключения к S3-совместимому объектному хранилищу.

-y|--yes #

Подтверждает операцию независимо от наличия файла, указанного в параметре --s3-config-path.

archive-command #

Синтаксис:

shardmanctl [общие_параметры] probackup archive-command [add|rm]
        -B|--backup-path путь
        [-j|--jobs число]
        [--compress]
        [--compress-algorithm алгоритм]
        [--compress-level уровень]
        [--batch-size размер_порции]
        [--storage-type mount|remote|S3]
        [--remote-port порт]
        [--remote-user имя_пользователя]
        [-s|--shard имя_сегмента]
        [--s3-config-path путь]
        [-y|--yes]
    

Добавляет/удаляет и включает/отключает команду архивирования для каждой группы репликации в кластере Shardman для размещения журналов WAL в инициализированном репозитории резервных копий.

add #

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

rm #

Отключает команду archive в каждой группе репликации в кластере Shardman. Никаких дополнительных параметров не требуется.

-B путь
--backup-path путь #

Требуется при добавлении archive_command. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman.

--batch-size batch_size #

Для ускорения архивирования используется параметр --batch-size, определяющий размер порции из нескольких копируемых сегментов WAL. Вместе с параметром --batch-size также можно применить указание -j, чтобы порции копировались в несколько потоков.

--jobs число
-j число #

Число параллельных потоков, которые используются pg_probackup при создании резервной копии. По умолчанию: 1.

--compress #

Если этот флаг не установлен, сжатие будет отключено. Если флаг установлен, используется принятый по умолчанию алгоритм zstd с уровнем сжатия 1, в то время как остальные параметры сжатия игнорируются, даже если они заданы.

--compress-algorithm алгоритм #

Определяет алгоритм сжатия: zlib, lz4, zstd, pglz или none. Как только алгоритм задан, этот параметр проверяет, что значение уровня сжатия находится в пределах возможных значений для заданного алгоритма.

Список поддерживаемых алгоритмов сжатия зависит от версии Postgres Pro Enterprise, включающей используемое приложение pg_probackup. Подробная информация описана в статье Параметры сжатия.

По умолчанию: none.

--compress-level уровень #

Определяет уровень сжатия: 0-9 для zlib, 1 для pglz, 0-22 для zstd и 0-12 для lz4.

По умолчанию: 1.

--storage-type mount|remote|S3 #

Тип хранилища резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно.

По умолчанию: remote.

--remote-port порт #

Указывает удалённый порт SSH для экземпляров группы репликации.

По умолчанию: 22.

--remote-user имя_пользователя #

Указывает удалённого пользователя для подключения по SSH для экземпляров группы репликации.

По умолчанию: postgres.

-s|--shard имя_сегмента #

Задаёт имя сегмента, в котором необходимо добавить, включить или выключить команду archive. Если параметр не указан, команда archive включается или выключается во всех сегментах.

--s3-config-path путь #

Задаёт путь к файлу конфигурации S3.

По умолчанию: <shardman-data-dir>/s3.config.

-y
--yes #

Подтвердить перезапуск вместо того, чтобы запрашивать подтверждение из стандартного ввода. Применяется только для команды add.

backup #

Синтаксис:

shardmanctl [common_options] probackup backup -B|--backup-path path
        -E|--etcd-path path
        -b|--backup-mode MODE
        [-j|--jobs count]
        [--compress-algorithm algorithm]
        [--compress-level level]
        [--batch-size batch_size]
        [--storage-type mount|remote|S3]
        [--remote-port port]
        [--remote-user username]
        [--ssh-key path]
        [-t|--timeout seconds]
        [-m|--maxtasks number_of_tasks]
        [--log-directory path]
        [--s3-config-path path]
        [--no-validate]
        [--skip-block-validation]
        [--log-to-console]
        [--retention-redundancy]
        [--retention-window]
        [--wal-depth]
        [--delete-wal]
        [--delete-expired]
        [--merge-expired]
        [-y | --yes]
        [--lock-lifetime]
    

Создаёт резервную копию кластера Shardman.

-B путь
--backup-path путь #

Обязательный параметр. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman.

-E путь
--etcd-path путь #

Обязательный параметр. Указывает путь к каталогу хранения копий etcd.

-b РЕЖИМ
--backup-mode РЕЖИМ #

Обязательный параметр. Определяет режим резервного копирования: FULL, PAGE, DELTA, PTRACK.

--batch-size batch_size #

Для ускорения архивирования используется параметр --batch-size, определяющий размер порции из нескольких копируемых сегментов WAL. Вместе с параметром --batch-size также можно применить указание -j, чтобы порции копировались в несколько потоков.

--jobs число
-j число #

Число параллельных потоков, которые используются pg_probackup при создании резервной копии. По умолчанию: 1.

--compress-algorithm алгоритм #

Определяет алгоритм сжатия: zlib, lz4, zstd, pglz, или none.

Список поддерживаемых алгоритмов сжатия зависит от версии Postgres Pro Enterprise, включающей используемое приложение pg_probackup. Подробная информация описана в статье Параметры сжатия.

По умолчанию: none.

--compress-level уровень #

Определяет уровень сжатия: 0-9 для zlib, 1 для pglz, 0-22 для zstd и 0-12 для lz4.

По умолчанию: 1.

--remote-port порт #

Указывает удалённый порт SSH для экземпляров группы репликации.

По умолчанию: 22.

--remote-user имя_пользователя #

Указывает удалённого пользователя для подключения по SSH для экземпляров группы репликации.

По умолчанию: postgres.

--ssh-key путь #

Указывает закрытый ключ SSH для удалённого выполнения команд по SSH.

По умолчанию: $HOME/.ssh/id_rsa.

-t секунды
--timeout секунды #

Выход с ошибкой после указанной в секундах задержки при ожидании готовности кластера.

-m число_заданий
--maxtasks число_заданий #

Задаёт максимальное количество одновременно выполняемых задач (команды pg_probackup).

По умолчанию соответствует числу логических CPU в системе.

--no-validate #

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

По умолчанию: false.

--skip-block-validation #

Отключает проверку контрольных сумм на уровне блоков в процессе резервного копирования.

По умолчанию: false.

--storage-type mount|remote|S3 #

Тип хранилища резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно.

По умолчанию: remote.

--log-to-console #

Включает вывод журналов pg_probackup на консоль.

По умолчанию: false.

--log-directory путь #

Задаёт путь к каталогу журналов для приложения pg_probackup. Обязательный параметр в случаях, если для параметра --storage-type установлено значение S3 и не задана переменная окружения SDM_LOG_DIRECTORY.

По умолчанию: <backup-directory>/backup/log.

--s3-config-path путь #

Задаёт путь к файлу конфигурации S3.

По умолчанию: <shardman-data-dir>/s3.config.

--retention-redundancy=избыточность
#

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

По умолчанию: текущее значение в файле pg_probackup.conf, если не задано, то 0.

--retention-window=окно
#

Количество дней, в течение которых возможно восстановление. Должно быть неотрицательным целым числом. При нулевом значении окно восстановления отсутствует.

По умолчанию: текущее значение в файле pg_probackup.conf, если не задано, то 0.

--wal-depth=глубина_wal #

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

По умолчанию: текущее значение в файле pg_probackup.conf, если не задано, то 0.

--delete-wal #

Удаляет файлы WAL, которые не требуются для восстановления никаких резервных копий.

По умолчанию: false.

--delete-expired #

Удаляет резервные копии, не удовлетворяющие политике хранения.

По умолчанию: false.

--merge-expired
#

Объединяет самую старую инкрементальную копию, удовлетворяющую требованиям политики хранения, с её родительскими копиями, срок хранения которых истёк.

По умолчанию: false.

-y
--yes #

Подтвердить перезапуск вместо того, чтобы запрашивать подтверждение из стандартного ввода.

--lock-lifetime #

Позволяет задать максимальное время удержания блокировки утилитой probackup (в секундах).

По умолчанию: 1800.

checkdb #

Синтаксис:

shardmanctl [общие_параметры] probackup checkdb
[--amcheck [--skip-block-validation] [--heapallindexed]] [--shard сегмент]
[-m|--maxtasks число_заданий]

Проверяет кластер Shardman на наличие физических повреждений или логических нарушений.

--amcheck #

Выполняет логическую проверку индексов при отсутствии повреждений в ходе проверки файлов данных. Для проверки индексов в базе данных должны быть установлены расширения amcheck или amcheck_next. Для баз данных без расширения amcheck проверка индексов пропускается. Расширение amcheck входит в состав установочного пакета Shardman.

--heapallindexed #

Проверяет, что все кортежи из кучи, требующие индексирования, действительно проиндексированы. Этот параметр используется только совместно с параметром --amcheck. Поддержка данного параметра зависит от версии установленного amcheck/amcheck_next. Расширение amcheck из установочного пакета Shardman поддерживает такую проверку.

--skip-block-validation #

Пропускает проверку файлов данных. Этот флаг используется только совместно с флагом --amcheck, что позволяет выполнить только логическую проверку индексов.

--shard сегмент #

Выполнять проверку только в указанном сегменте. По умолчанию проверка выполняется во всех сегментах.

-m число_заданий
--maxtasks число_заданий #

Задаёт максимальное количество одновременно выполняемых задач (команды pg_probackup).

По умолчанию соответствует числу логических CPU в системе.

delete #

Синтаксис:

shardmanctl [общие_параметры] probackup delete -B|--backup-path путь
        -i|--backup-id ид_резервной_копии
        [-j|--jobs число]
        [-m|--maxtasks число_заданий]
        [--storage-type mount|remote|S3]
        [--s3-config-path путь]
        [--delete-wal]
        [-y|--yes]
        [--retention-redundancy]
        [--retention-window]
        [--wal-depth]
        [--delete-expired]
        [--merge-expired]

Удаляет резервную копию кластера Shardman с заданным идентификатором backup_id или запускает процедуру удаления резервных копий или заархивированных файлов WAL, не удовлетворяющих текущей политике хранения.

Обратите внимание, что backup_id нельзя использовать одновременно с merge-expired или delete-expired.

-B путь
--backup-path путь #

Обязательный параметр. Указывает путь к каталогу (или ключ в корзине S3-совместимого хранилища), в котором должны храниться резервные копии кластера Shardman.

-i ид_резервной_копии
--backup-id ид_резервной_копии #

Задаёт уникальный идентификатор резервной копии.

--jobs число
-j число #

Число параллельных потоков, которые используются pg_probackup при создании резервной копии. По умолчанию: 1.

-m число_заданий
--maxtasks число_заданий #

Задаёт максимальное количество одновременно выполняемых задач (команды pg_probackup).

По умолчанию соответствует числу логических CPU в системе.

--storage-type mount|remote|S3 #

Тип хранилища резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно.

По умолчанию: remote.

Для удаления резервной копии, у которой параметр --storage-type имеет значение S3, при запуске команды delete необходимо установить значение S3 для параметра --storage-type.

--s3-config-path путь #

Задаёт путь к файлу конфигурации S3.

По умолчанию: <shardman-data-dir>/s3.config.

--delete-wal #

Удаляет файлы WAL, которые не требуются для восстановления никаких резервных копий.

По умолчанию: false.

-y
--yes #

Подтверждает операцию.

По умолчанию: false.

--retention-redundancy=избыточность
#

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

По умолчанию: текущее значение в файле pg_probackup.conf, если не задано, то 0.

--retention-window=окно
#

Количество дней, в течение которых возможно восстановление. Должно быть неотрицательным целым числом. При нулевом значении окно восстановления отсутствует.

По умолчанию: текущее значение в файле pg_probackup.conf, если не задано, то 0.

--wal-depth=глубина_wal #

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

По умолчанию: текущее значение в файле pg_probackup.conf, если не задано, то 0.

--delete-expired #

Удаляет резервные копии, не удовлетворяющие политике хранения.

По умолчанию: false.

--merge-expired
#

Объединяет самую старую инкрементальную копию, удовлетворяющую требованиям политики хранения, с её родительскими копиями, срок хранения которых истёк.

По умолчанию: false.

merge #

Синтаксис:

shardmanctl [общие_параметры] probackup merge -B|--backup-path путь
        -i|--backup-id ид_резервной_копии
        [-j|--jobs число]
        [-m|--maxtasks число_заданий]
        [--no-validate]
        [--no-sync]
        [-y|--yes]

Объединяет резервные копии, относящиеся к одной цепочке инкрементальных копий. При полном копировании резервные копии объединяются с их первой инкрементальной копией. При инкрементальном резервном копировании резервные копии объединяются с их родительской полной копией и всеми инкрементальными копиями между ними. После выполнения команды полная копия содержит все объединённые данные, а инкрементальные копии удаляются как ненужные.

-B путь
--backup-path путь #

Обязательный параметр. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman.

-i ид_резервной_копии
--backup-id ид_резервной_копии #

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

--jobs число
-j число #

Число параллельных потоков, которые используются pg_probackup при создании резервной копии. По умолчанию: 1.

-m число_заданий
--maxtasks число_заданий #

Задаёт максимальное количество одновременно выполняемых задач (команды pg_probackup).

По умолчанию соответствует числу логических CPU в системе.

--no-sync #

Не сбрасывать объединяемые файлы на диск. Этот флаг позволяет несколько ускорить процесс объединения. Использование этого флага может привести к повреждению данных при сбое операционной системы или аппаратного сбоя.

По умолчанию: false.

--no-validate #

Пропускает автоматическую проверку созданной резервной копии до и после объединения.

По умолчанию: false.

-y
--yes #

Подтверждает операцию.

По умолчанию: false.

restore #

Синтаксис:

shardmanctl [общие_параметры] probackup restore
        -B|--backup-path путь
        -i|--backup-id идентификатор
        -j|--jobs число
        [--recovery-target-time дата_время]
        [-I|--recovery-mode инкрементальный_режим]
        [-t|--timeout секунды]
        [-m|--maxtasks число_заданий]
        [--metadata-only] [--schema-only] [--shard сегмент]
        [--no-validate]
        [--skip-block-validation]
        [--s3-config-path путь]
        [--storage-type mount|remote|S3]
        [--wal-limit число_сегментов_wal]
        [--log-directory путь]
        [--data-validate]
    

Восстанавливает кластер Shardman из выбранной резервной копии.

-B путь
--backup-path путь #

Обязательный параметр. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman. Можно использовать для развёртывания резервного кластера на основании резервной копии ведущего кластера через указание пути к каталогу резервной копии из центра обработки данных.

-i идентификатор
--backup-id идентификатор #

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

--jobs число
-j число #

Число параллельных потоков, которые используются pg_probackup при восстановлении из резервной копии. По умолчанию: 1.

--recovery-target-time временная_метка #

Параметр PITR (восстановление на момент времени). Указывает метку времени для восстановления. Пример: «2024-01-25 15:30:36» в часовом поясе UTC.

-I инкрементальный_режим
--recovery-mode инкрементальный_режим #

Выбирает инкрементальный режим восстановления. Поддерживаются следующие режимы:

  • checksum — заменять только страницы с неподходящей контрольной суммой и LSN.

  • lsn — заменять только те страницы, LSN которых больше точки расхождения.

  • none — обычное восстановление, по умолчанию.

-t секунды
--timeout секунды #

Выход с ошибкой после указанной в секундах задержки при ожидании готовности кластера или завершения восстановления.

--metadata-only #

Выполняет восстановление только метаданных. По умолчанию выполняется полное восстановление.

--schema-only #

Выполняет восстановление только схемы. По умолчанию выполняется полное восстановление.

--shard сегмент #

Выполнять восстановление только в указанном сегменте. По умолчанию восстановление выполняется во всех сегментах.

--no-validate #

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

По умолчанию: false.

--skip-block-validation #

Отключает проверку контрольных сумм на уровне блоков для ускорения проверки целостности. При автоматической проверке перед восстановлением будут проверяться только контрольные суммы на уровне файлов.

По умолчанию: false.

--s3-config-path путь #

Задаёт путь к файлу конфигурации S3.

По умолчанию: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Тип хранения резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно. Чтобы создать резервную копию с параметром --storage-type со значением S3, укажите их при запуске команды restore.

По умолчанию: remote.

--wal-limit число_сегментов_wal #

Задаёт число сегментов WAL, по которым при восстановлении PITR будет производиться поиск ближайших точек синхронизации.

По умолчанию: 0 — без ограничений.

--log-directory путь #

Задаёт путь к каталогу журналов для приложения pg_probackup. Обязательный параметр в случаях, если для параметра --storage-type установлено значение S3 и не задана переменная окружения SDM_LOG_DIRECTORY.

По умолчанию: <backup-directory>/backup/log.

--data-validate #

Если включен, перед восстановлением проверяет данные с помощью команды probackup validate.

По умолчанию: отключено.

show #

Синтаксис:

shardmanctl [общие_параметры] probackup show
        -B|--backup-path путь
        [-f|--format таблица|json]
        [--archive ]
        [-i|--backup-id ид_резервной_копии]
        [--instance экземпляр]
        [--storage-type mount|remote|S3]
        [--s3-config-path путь]
    

Показывает список резервных копий кластера Shardman.

-B путь
--backup-path путь #

Обязательный параметр. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman.

-f table|json
--format table|json #

Указывает выходной формат.

По умолчанию: table.

--archive #

Показывает информацию об архиве WAL.

-i ид_резервной_копии
--backup-idид_резервной_копии #

Показывает информацию о конкретных резервных копиях.

--instanceэкземпляр #

Показывает информацию о конкретных экземплярах.

--s3-config-path путь #

Задаёт путь к файлу конфигурации S3.

По умолчанию: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Тип хранения резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно. Чтобы показать резервную копию с параметром --storage-type со значением S3, укажите их при запуске команды show.

По умолчанию: remote.

show-config #

Синтаксис:

shardmanctl [общие_параметры] probackup show-config
        -B путь
        [-f|--format text|json]
         [--no-scale-units]
         -s|--shard имя_сегмента
        [--s3-config-path путь]
        [--storage-type mount|remote|S3]

Выводит все текущие параметры конфигурации pg_probackup, в том числе те, что содержатся в файле pg_probackup.conf, размещённом в каталоге каталог_копий/backups/имя_сегмента, а также те, что были заданы в командной строке.

-B строка
--backup-path=строка #

Обязательный параметр. Задаёт абсолютный путь к каталогу резервных копий.

--format text|json #

Указывает выходной формат.

По умолчанию: text.

--no-scale-units #

Выводить значения конфигурационных параметров времени и объёма памяти в единицах измерения по умолчанию.

По умолчанию: false.

-s строка
--shard=строка #

Имя сегмента, для которого необходимо выполнить команду show-config.

--s3-config-path путь #

Задаёт путь к каталогу, в котором создаётся файл конфигурации S3 на всех узлах Shardman.

По умолчанию: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Тип хранилища резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно.

По умолчанию: remote.

validate #

Синтаксис:

shardmanctl [общие_параметры] probackup validate
        -B|--backup-path путь
        -i|--backup-id идентификатор
        [-t|--timeout секунды]
        [-m|--maxtasks число_заданий]
        [--log-to-console]
        [--storage-type mount|remote|S3]
        [--s3-config-path путь]
        [--log-directory путь]
        [--remote-port порт]
        [--remote-user имя_пользователя]
    

Проверяет целостность выбранной резервной копии кластера Shardman.

-B путь
--backup-path путь #

Обязательный параметр. Указывает путь к каталогу, в котором должны храниться резервные копии кластера Shardman.

-i идентификатор
--backup-id идентификатор #

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

--log-to-console #

Включает вывод журналов pg_probackup на консоль.

По умолчанию: false.

-t секунды
--timeout секунды #

Выход с ошибкой после указанной в секундах задержки при ожидании готовности кластера.

-m число_заданий
--maxtasks число_заданий #

Задаёт максимальное количество одновременно выполняемых задач (команды pg_probackup).

По умолчанию соответствует числу логических CPU в системе.

--s3-config-path путь #

Задаёт путь к файлу конфигурации S3.

По умолчанию: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Тип хранения резервных копий. При значении remote протокол SSH используется для копирования файлов с данными в удалённый каталог резервных копий. Но это поведение можно изменить, если для хранения резервных копий используется каталог, смонтированный на всех узлах, или S3-совместимое объектное хранилище. Чтобы это сделать, установите для параметра --storage-type значение mount или S3 соответственно. Чтобы проверить резервную копию с параметром --storage-type со значением S3, укажите их при запуске команды validate.

По умолчанию: remote.

--log-directory путь #

Задаёт путь к каталогу журналов для приложения pg_probackup. Обязательный параметр в случаях, если для параметра --storage-type установлено значение S3 и не задана переменная окружения SDM_LOG_DIRECTORY.

По умолчанию: <backup-directory>/backup/log.

--remote-port порт #

Указывает удалённый порт SSH для экземпляров группы репликации.

По умолчанию: 22.

--remote-user имя_пользователя #

Указывает удалённого пользователя для подключения по SSH для экземпляров группы репликации.

По умолчанию: postgres.

--ssh-key путь #

Указывает закрытый ключ SSH для удалённого выполнения команд по SSH.

По умолчанию: $HOME/.ssh/id_rsa.

set-config #

Синтаксис:

shardmanctl [общие_параметры] probackup set-config
        [--archive-timeout целое]
        [-B | --backup-path строка]
        [-m |--maxtasks целое]
        [--remote-port целое]
        [--remote-user строка]
        [--retention-redundancy целое]
        [--retention-window целое]
        [--wal-depth целое]
        [--s3-config-path строка]
        [-s |--shard строка]
        [--storage-type строка]

Добавляет указанные параметры в файл pg_probackup.conf или изменяет существующие.

--archive-timeout целое #

Устанавливает время ожидания для архивирования или потоковой репликации сегментов WAL, в секундах.

По умолчанию: pg_probackup ждёт 300 секунд.

-B строка
--backup-path=строка #

Задаёт абсолютный путь к каталогу резервных копий.

-m целое
--maxtasks=целое #

Задаёт максимальное количество одновременно выполняемых задач (команды pg_probackup).

По умолчанию соответствует числу логических CPU в системе.

--remote-port целое #

Порт для подключения к SSH серверу, где создаётся резервная копия.

По умолчанию: 22.

--remote-user строка #

Пользователь, который подключается к удалённому SSH серверу для создания резервной копии.

--retention-redundancy целое #

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

По умолчанию: 0.

--retention-window целое #

Количество дней, в течение которых возможно восстановление. Должно быть неотрицательным целым числом. При нулевом значении окно восстановления отсутствует.

По умолчанию: 0.

--wal-depth целое #

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

--s3-config-path строка #

Задаёт путь к файлу конфигурации S3.

По умолчанию: /var/lib/pgpro/sdm-14/data/s3.config.

-s строка
--shard=строка #

Имя сегмента, для которого необходимо запустить команду set-config. Если сегмент не указан, команда запускается для всех сегментов.

По умолчанию: текущее значение в файле pg_probackup.conf.

--storage-type строка #

Тип хранилища резервных копий, возможные значения: remote, mount, S3.

По умолчанию: remote.

rebalance

Синтаксис:

shardmanctl [общие_параметры] rebalance [-f|--force]

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

-f
--force #

Выполнить принудительную перебалансировку сегментированных таблиц, секции которых были перемещены вручную.

restart #

Синтаксис:

     shardmanctl [общие_параметры] restart [-y|--yes] [--no-wait]
   

Перезапускает кластер Shardman.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--no-wait #

Не ждать запуска реплик.

restart rolling #

Синтаксис:

     shardmanctl [общие_параметры] restart rolling [-y|--yes] [--restore-masters] [--upgrade]
   

Последовательно перезапускает кластер Shardman с минимальным временем простоя. Перезапускает shardmand, последовательно перезапускает все резервные экземпляры, переключает ведущий на один из резервных, после чего перезапускает прошлый ведущий экземпляр.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--restore-masters #

Возвращает роли ведущих тем экземплярам, которые были ведущими до команды.

--upgrade #

Запускает shardmanctl upgrade на всех перезапущенных экземпярах.

shard add #

Синтаксис:

shardmanctl [общие_параметры] shard -s|--shard имя_сегмента add -n|--nodes имена_узлов [--no-wait]

Добавляет реплику в сегмент.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

-n имена_узлов
--nodes=имена_узлов #

Задаёт список добавляемых узлов реплики через запятую.

--no-wait #

Не ждать запуска сегмента.

shard master set #

Синтаксис:

shardmanctl [общие_параметры] shard -s|--shard имя_сегмента master set [--yes | -y] [-n| node имена_узлов]

Задаёт приоритет для определённого главного сервера для заданного сегмента.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

master set #

Приоритетный главный сервер.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

-n имена_узлов
--nodes=имена_узлов #

Задаёт список узлов реплики через запятую.

shard master reset #

Синтаксис:

shardmanctl [общие_параметры] shard -s|--shard имя_сегмента master reset [--yes | -y] -n| node имена_узлов

Сбрасывает параметры приоритетного главного сервера для сегмента.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

master reset #

Сбрасывает параметры приоритетного главного сервера для сегмента.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

-n имена_узлов
--nodes=имена_узлов #

Задаёт список узлов реплики через запятую.

shard add #

Синтаксис:

shardmanctl [общие_параметры] shard -s|--shard shard_name reset [--yes | -y][--new-primary | -p]

Сбрасывает узлы группы репликации, если они зависли.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--new-primary
-p #

Имя нового ведущего узла.

shard rm #

Синтаксис:

     shardmanctl [общие_параметры] shard -s|--shard имя_сегмента rm -n|--nodes имя_узла [-f|--force]
   

Удаляет реплику из сегмента.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента

-n имена_узлов
--nodes=имена_узлов #

Задаёт список удаляемых узлов реплики, разделённых запятыми.

-f
--force #

Выполнить принудительное удаление узла, даже если он «мёртв».

shard switch #

Синтаксис:

     shardmanctl [общие_параметры] shard -s|--shard имя_сегмента switch [--new-primary имена_узлов]
   

Переключает ведущий узел. При запуске команды пользователю будет предложено задать текущему узлу статус ведущего во избежание обратного переключения.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

--new-primary=имена_узлов #

Имя нового ведущего узла.

shard start #

Синтаксис:

     shardmanctl [общие_параметры] shard -s |--shard имя_сегмента start [--no-wait] [-n|--node имя_узла]
   

Запускает сегмент.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

--no-wait #

Не ждать запуска сегмента.

-n имя_узла
--node=имя_узла #

Указывает узел, который необходимо запустить.

shard stop #

Синтаксис:

     shardmanctl [общие_параметры] shard -s |--shard имя_сегмента stop [-n|--node имя_узла]
   

Останавливает сегмент.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

-n имя_узла
--node=имя_узла #

Указывает узел, который необходимо остановить.

shard replicas reinit #

Синтаксис:

     shardmanctl [общие_параметры] shard -s|--shard имя_сегмента replicas reinit [-n|--node имена_узлов] [-y|--yes] [--no-wait]

Сбрасывает реплики определённого сегмента.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

-n имена_узлов
--node=имена_узлов #

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

-y
--yes #

Подтверждает операцию вместо того, чтобы запрашивать подтверждение от стандартного ввода.

--no-wait #

Не ждать готовности реплик.

За подробностями обратитесь к Подразделу «Переинициализация реплик».

nodes start #

Синтаксис:

     shardmanctl [общие_параметры] nodes start -n|--nodes имена_узлов [--no-wait]
   

Запускает узлы.

-n имена_узлов
--nodes=имена_узлов

Имена узлов.

--no-wait

Задаёт поведение shardmanctl, при котором не ожидается запуск узлов.

nodes restart #

Синтаксис:

     shardmanctl [общие_параметры] nodes restart -n|--nodes имена_узлов [--no-wait]
   

Перезапускает узлы.

-n имена_узлов
--nodes=имена_узлов

Имена узлов.

--no-wait

Не ждать перезапуска узлов.

nodes stop #

Синтаксис:

     shardmanctl [общие_параметры] nodes stop -n|--nodes имена_узлов [--no-wait]
   

Останавливает узлы.

-n имена_узлов
--nodes=имена_узлов

Имена узлов.

--no-wait

Не ждать остановки узлов.

status #

Синтаксис:

     shardmanctl [общие_параметры] status [-f|--format table|json] [--filter store|metadata|shardmand|rg|master|dictionary|all|biharestart_required_params] [-s|--sort node|rg|status]
   

Отчёт о состоянии подсистем кластера Shardman.

-f table|json
--format=table|json #

Указывает формат отчёта.

По умолчанию: table.

За подробностями обратитесь к Подразделу «Получение статуса подсистем кластера».

--filter store|metadata|shardmand|rg|master|dictionary|allrestart_required_params #

Указывает подсистемы, информация о состоянии которых должна быть включена в вывод.

По умолчанию: all.

За подробностями обратитесь к Подразделу «Получение статуса подсистем кластера».

-s node|rg|status
--sort node|rg|status #

Сортирует сообщения внутри одной группы (таблицы) указанным способом.

По умолчанию: node.

За подробностями обратитесь к Подразделу «Получение статуса подсистем кластера».

status transactions #

Синтаксис:

     shardmanctl [общие_параметры] status transactions [-r|--repgroup имя_группы_репликации
     

Показывает распредёленные транзакции, которые не удалось разобрать встроенными инструментами мониторинга Shardman.

-r имя_группы_репликации
--repgroup=имя_группы_репликации #

Указывает группу репликации, для которой необходимо выводить транзакции.

По умолчанию: все группы репликации.

За подробностями обратитесь к Подразделу «Вывод списка неразобранных распределённых транзакций».

store dump #

Синтаксис:

     shardmanctl [общие_параметры] store dump [-f|--file имя_файла]
   

Выгружает текущие конфигурации кластеров из хранилища.

-f имя_файла
--file=имя_файла #

Задаёт выходной файл (- для стандартного вывода).

По умолчанию: -.

За подробностями обратитесь к Подразделу «Выгрузка всех ключей из хранилища для отладки конфигурации ошибок».

store restore #

Синтаксис:

     shardmanctl [общие_параметры] store restore [--delete-old-keys][-f|--file имя_файла][-y|--yes]
   

Позволяет безопасно восстановить кластер etcd из дампа. Для этого необходимо отключить shardmand на всех сегментах. Работает только при холодном резервном копировании.

--delete-old-keys #

Удалить все ключи etcd перед восстановлением.

-f имя_файла
--file=имя_файла #

Задаёт имя дампа ключей etcd.

-y
--yes #

Выполнять автоматическое подтверждение.

store lock #

Синтаксис:

     shardmanctl [общие_параметры] store lock [-f|--format text|json]
   

Показывает информацию о текущей блокировке метаданных кластера.

-f=text|json
--format=text|json #

Указывает выходной формат.

По умолчанию: text.

За подробностями обратитесь к Подразделу «Вывод информации о текущей блокировке метаданных кластера».

store get #

Синтаксис:

    shardmanctl [общие_параметры] store get [[-a|--alias имя_псевдонима]|[-k|--key имя_ключа] [-f|--file имя_файла]]
   

Получает указанный ключ из хранилища.

-a имя_псевдонима
--alias=ladle|cluster |spec|stolonspec #

Указывает использование псевдонима вместо полного имени ключа. Нельзя использовать с параметром --key.

За подробностями обратитесь к Подразделу «Получение текущей конфигурации stolon».

-k имя_ключа
--key=имя_ключа #

Указывает ключ для извлечения из хранилища. Нельзя использовать с параметром --alias.

За подробностями обратитесь к Подразделу «Получение текущей конфигурации stolon».

-f имя_файла
--file=имя_файла #

Задаёт файл для вывода значения.

По умолчанию: - (стандартный вывод).

За подробностями обратитесь к Подразделу «Получение текущей конфигурации stolon».

store keys #

Синтаксис:

    shardmanctl [общие_параметры] store keys
   

Получает из хранилища все ключи с текущим префиксом кластера.

За подробностями обратитесь к Подразделу «Получение имён ключей кластера и ковша для текущего кластера».

store set #

Синтаксис:

    shardmanctl [общие_параметры] store set [[-a|--alias имя_псевдонима]|[-k|--key имя_ключа]] [-f|--file имя_файла]
   

Создаёт или перезаписывает ключ в хранилище.

-a ladle|cluster |spec|stolonspec
--alias=ladle|cluster |spec|stolonspec #

Указывает использование псевдонима вместо полного имени ключа. Нельзя использовать с параметром --key.

-k имя_ключа
--key=имя_ключа #

Указывает имя ключа для размещения в хранилище. Нельзя использовать с параметром --alias.

-f имя_файла
--file=имя_файла #

Задаёт файл с входными данными (- для стандартного ввода).

За подробностями обратитесь к Подразделу «Установка новой конфигурации для кластера».

tables sharded info #

Синтаксис:

    shardmanctl [общие_параметры] tables sharded info [-t|--table имя_таблицы]
   

Получает информацию о сегментированной таблице.

-t таблица
--table=таблица #

Указывает имя таблицы в формате schema.table

tables sharded list #

Синтаксис:

    shardmanctl [общие_параметры] tables sharded list
   

Получает список всех сегментированных таблиц.

tables sharded norebalance #

Синтаксис:

    shardmanctl [общие_параметры] tables sharded norebalance
   

Получает список сегментированных таблиц с отключённой автоматической перебалансировкой.

tables sharded partmove #

Синтаксис:

    shardmanctl [общие_параметры] tables sharded partmove [-t|--table имя_таблицы] [-s|--shard имя_сегмента] [-p|--partnum число]
   

Перемещает указанную секцию сегментированной таблицы в новый сегмент.

-t таблица
--table=таблица #

Указывает имя таблицы в формате schema.table.

-p число
--partnum=число #

Указывает номер секции для перемещения.

-s имя_сегмента
--shard=имя_сегмента #

Указывает имя нового сегмента для секции.

tables sharded rebalance #

Синтаксис:

    shardmanctl [общие_параметры] tables sharded rebalance [-t|--table имя_таблицы]
   

Включает и запускает автоматическую перебалансировку данных для выбранной сегментированной таблицы.

-t таблица
--table=таблица #

Указывает имя таблицы в формате schema.table.

config get #

Синтаксис:

shardmanctl [общие_параметры] config get [-c | --choose-revision] [-r | --revision ] [-f | --file]

Выгружает текущую полную конфигурацию кластера или конфигурацию указанной версии.

-c
--choose-revision #

Включает интерактивный режим выбора конфигурации указанной версии.

-r
--revision #

Идентификатор версии конфигурации.

-f имя_файла
--file=имя_файла #

Имя файла для записи конфигурации. Если не указано, то значение — stdout.

config revisions rm #

Синтаксис:

shardmanctl [общие_параметры] config revisions rm [-r | --revision ] [-y | --yes]

Удаляет указанную версию конфигурации из истории состояний.

-r
--revision #

Идентификатор версии конфигурации. Если не указан, включает интерактивный режим выбора конфигурации указанной версии. Это временная метка операции, которая привела к изменению конфигурации Shardman.

-y
--yes #

Выполнять автоматическое подтверждение.

config update #

Синтаксис:

shardmanctl [общие_параметры] config update [[-f|--file файл_конфигурации_stolon|файл_конфигурации_shardman]|текст_конфигурации [-p|--patch][-w|--wait]]] [--force][-y | --yes] [--from-primary-cluster]

Обновляет конфигурацию stolon или полную конфигурацию Shardman.

-f файл_конфигурации_stolon|файл_конфигурации_shardman
--specfile=файл_конфигурации_stolon|файл_конфигурации_shardman #

Указывает файл конфигурации stolon или полной конфигурации Shardman. Тип файла конфигурации определяется автоматически. Значение - означает стандартный ввод. По умолчанию конфигурация передаётся в тексте_конфигурации.

-w
--wait #

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

-p
--patch #

Объединяет новой конфигурации с существующей. По умолчанию новая конфигурация заменяет существующую.

--force #

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

-y
--yes #

Подтвердить перезапуск, необходимый для вступления в силу значений параметров. Если параметр не задан, а для изменения параметров требуется перезапуск, то будет запрошено подтверждение вручную. Если подтверждение не получено, кластер продолжит работу, но новые значения параметров вступят в силу только после перезапуска.

config rollback #

Синтаксис:

shardmanctl [общие_параметры] config rollback [-r | --revision] [-w|--wait длительность] [--force] [-y|--yes]

Выполняет откат конфигурации Shardman к одному из предыдущих состояний. При откате к версии конфигурации, имеющей параметры max_connections, max_prepared_transactions или max_worker_processes, реплики переинициализируются.

-r
--revision #

Идентификатор версии, до которой нужно откатить состояние конфигурации. Это временная метка операции, которая привела к изменению конфигурации Shardman.

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

-w
--wait #

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

По умолчанию: 1h.

-f
--force #

Выполнить принудительную настройку параметра, если выполняется операция на уровне кластера.

-y
--yes #

Выполнять автоматическое подтверждение.

config revisions #

Синтаксис:

shardmanctl [общие_параметры] config revisions [-f|--format text|json]

Выводит историю версий конфигурации кластера Shardman. Для каждой версии содержит следующую информацию:

  • revision_id — временная метка операции, вызвавшей изменение конфигурации Shardman

  • host — имя узла, на котором запустили операцию

  • user — пользователь, запустивший операцию

  • command — сама операция

-f=text|json
--format=text|json #

Указывает выходной формат.

По умолчанию: text.

config revisions set #

Синтаксис:

shardmanctl [общие_параметры] config revisions set [--keep-config-revisions]

Позволяет задать длину истории версий конфигурации. Не может быть меньше 5; это значение устанавливается автоматически, если указать длину меньше. Для кластеров Shardman, у которых ещё не была сформирована история версий конфигурации, автоматически выставляется значение 20.

--keep-config-revisions #

Лимит на количество версий одной конфигурации Shardman. Если лимит меньше текущей длины истории, наиболее старые версии за пределами этого лимита будут удалены. Если количество операций, приводящих к изменению конфигурации, превышает лимит, наиболее старая версия удаляется.

По умолчанию: 20.

config update ip #

Синтаксис:

shardmanctl [общие_параметры] config update ip [-u|ip_1=ip_2,hostname_1=hostname_2][-y|--yes]

Обновляет указанные IP-адреса узлов кластера.

-u
ip_1=ip_2,hostname_1=hostname_2 #

Указывает IP-адреса узлов кластера, которые необходимо обновить.

-y
--yes #

Выполнять автоматическое подтверждение.

set #

Синтаксис:

shardmanctl [общие_параметры] set pgParam1=value1 [pgParam2=value2 [...]] [-y|--yes] [-w|--wait длительность] [-f|--force]

Устанавливает значения указанных параметров базы данных кластера Shardman.

-w
--wait #

Указывает, что shardmanctl должен дождаться вступления в силу изменений конфигурации. Примеры значений: 2h45m, 1m30s, 5m, 10s.

По умолчанию: 1h.

-y
--yes #

Подтвердить перезапуск, необходимый для вступления в силу значений параметров. Если параметр не задан, а для изменения параметров требуется перезапуск, то будет запрошено подтверждение вручную. Если подтверждение не получено, кластер продолжит работу, но новые значения параметров вступят в силу только после перезапуска.

-f
--force #

Выполнить принудительную настройку параметра, если выполняется операция на уровне кластера.

upgrade #

Синтаксис:

shardmanctl [общие_параметры] upgrade

Обновляет расширение shardman базы данных и изменяет параметры pg_foreign_server.

bench init #

Синтаксис:

shardmanctl [общие_параметры] bench init [--schema-type single|simple|shardman|custom]
[--schema-file имя_файла] [-s|--scale значение_масштабирования]  [-n|--no-vacuum]
[-F|--fillfactor значение_коэффициента_заполнения]

Инициализирует схему тестирования через pgbench. Схема может быть пользовательской или предопределённой. Создаёт таблицы схемы tpc-b и заполняет их.

--schema-type=single|simple|shardman|custom #

Тип схемы, используемый при её инициализации. Возможные значения:

  • single — схема для одиночного теста производительности PostgreSQL

  • simple — простая сегментированная схема

  • shardman — сегментированная схема, оптимизированная для Shardman

  • custom — схема, инициализированная пользователем из файла --schema-file

По умолчанию: shardman.

--schema-file=имя_файла #

Файл с DDL-запросом для пользовательского типа схемы, который будет использоваться для создания таблиц tpc-b для pgbench: pgbench_accounts, pgbench_branches, pgbench_tellers, pgbench_history.

-s значение_масштабирования
--scale=значение_масштабирования #

Умножить количество сгенерированных строк на заданный коэффициент масштабирования.

-n
--no-vacuum #

Не выполнять очистку во время инициализации.

-F значение_коэффициента_заполнения
--fillfactor=значение_коэффициента_заполнения #

Заполнить таблицы pgbench заданным значением коэффициента заполнения.

bench run #

Синтаксис:

shardmanctl [общие_параметры] bench run [--schema-type single|simple|shardman|custom]
[-f|--file имя_файла] [-c|--client число_клиентов]  [-C|--connect] [--full-output]
[-j|--jobs число_процессов][-T|--time секунды][-t|--transactions число_транзакций]
[-s|--scale коэффициент_масштаба] ] [ -P | --progress секунды] [ -R | --rate скорость_передачи] [ -M | --protocol режим_запросов]

Запускает инициализированный тест производительности через pgbench. Можно использовать скрипт pgbench по умолчанию или пользовательский скрипт из файла.

--schema-type=single|simple|shardman|custom #

Тип схемы, используемый при её инициализации (bench init). Возможные значения:

  • single — схема для одиночного теста производительности PostgreSQL

  • simple — простая сегментированная схема

  • shardman — сегментированная схема, оптимизированная для Shardman

  • custom — схема, инициализированная пользователем из файла --schema-file.

По умолчанию: shardman.

-f имя_файла
--file=имя_файла #

Добавить в список выполняемых скриптов скрипт транзакции из файла имя_файла.

Дополнительно можно задать целочисленный вес после @, меняющий вероятность выбора этого скрипта относительно других. По умолчанию вес считается равным 1. (Если вам нужно передать имя скрипта, содержащее символ @, добавьте к такому имени вес, чтобы исключить неоднозначность прочтения, например filen@me@1).

-c число_клиентов
--client=число_клиентов #

Число имитируемых клиентов, то есть число одновременных сеансов базы данных.

-C
--connect #

Устанавливать новое подключение для каждой транзакции вместо одного для каждого клиента.

--full-output #

Вывести полный вывод pgbench.

-j число_процессов
--jobs=число_процессов #

Количество рабочих потоков в pgbench.

-s коэффициент_масштаба
--scale=коэффициент_масштаба #

Умножить число генерируемых строк на заданный коэффициент.

-T секунды
--time=секунды #

Выполнять тест с ограничением по времени в указанное количество секунд. Значение по умолчанию — 0, что означает отсутствие ограничения по времени. Обратите внимание, что флаги -T и -t являются взаимоисключающими, и флаг -T имеет приоритет. Если задан флаг -T, флаг -t игнорируется.

-t число_транзакций
--transactions=число_транзакций #

Выполнять тест с ограничением в указанное количество транзакций на каждом клиенте. Значение по умолчанию — 10. Обратите внимание, что флаги -T и -t являются взаимоисключающими, и флаг -T имеет приоритет. Если задан флаг -T, флаг -t игнорируется.

-P секунды
--progress=секунды #

Выводить отчёт о прогрессе через заданное число секунд (сек). Выдаваемый отчёт включает время, прошедшее с момента запуска, скорость (в TPS) с момента предыдущего отчёта, а также среднее время ожидания транзакций, стандартное отклонение и количество неуспешных транзакций с момента последнего отчёта. В режиме ограничения скорости (-R) время ожидания вычисляется относительно назначенного времени запуска транзакции, а не фактического времени её начала, так что оно включает и среднее время отставания от графика. Когда параметр --max-tries включает повторение транзакций после ошибок сериализации/взаимоблокировок, в отчёт добавляется количество повторявшихся транзакций и общее число повторов.

-R скорость_передачи
--rate=скорость_передачи #

Выполнять транзакции, ориентируясь на заданную скорость, а не максимально быстро (по умолчанию). Скорость задаётся в транзакциях в секунду. Если заданная скорость превышает максимально возможную, это ограничение скорости не повлияет на результаты.

-M режим_запросов
--protocol=режим_запросов #

Протокол, выбираемый для передачи запросов на сервер:

  • simple: использовать простой протокол запросов.

  • extended: использовать расширенный протокол запросов.

  • prepared: использовать расширенный протокол запросов с подготовленными операторами.

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

По умолчанию: simple.

bench cleanup #

Синтаксис:

shardmanctl [общие_параметры] bench cleanup

Очищает базу данных схемы после тестов производительности. Удаляет таблицы tpc-b.

bench generate #

Синтаксис:

shardmanctl [общие_параметры] bench generate [-c|--config имя_файла] [-o|--output-file имя_файла]

Получает конфигурацию теста производительности из файла и генерирует bash-скрипт для создания схемы, оптимизированной для Shardman, и запуска теста производительности с использованием pgbench. Файл конфигурации должен быть в формате yaml.

-f имя_файла
--file=имя_файла #

Путь к файлу конфигурации. Этот файл содержит последовательность конфигураций скрипта. Каждый скрипт должен иметь тип схемы (schema_type): single|simple|shardman|custom. Для пользовательской схемы необходимо указать schema_file с DDL-скриптом. Необязательные параметры: init_flags (набор по умолчанию: -s 1000), run_flags (набор по умолчанию: -n -P 10 -c 10 -j 4 -T 60), секции (значение по умолчанию: 50). Настоятельно рекомендуется использовать параметр -n (--no-vacuum) внутри run_flags. Пример файла конфигурации:

    benches:
    - schema_type: single
      init_flags: "-s 3"
      run_flags: "-n -P 10 -c 10 -j 4 -T 10"
    - schema_type: simple
      init_flags: "-s 4"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
      partitions: 100
    - schema_type: shardman
      init_flags: "-s 5"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
    - schema_type: custom
      init_flags: "-s 6"
      schema_file: "schema.psql"
                            
-o имя_файла
--output-file=имя_файла #

Файл вывода. По умолчанию: stdout.

script #

Синтаксис:

shardmanctl [общие_параметры] script -s|--shard имя_сегмента][[-f|--file имя_файла][--sql запрос]]

Выполняет нетранзакционные команды из файла или командной строки на указанных сегментах.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента.

-f имя_файла
--file=имя_файла #

Добавить в список выполняемых скриптов скрипт транзакции из файла имя_файла.

--sql query #

Указывает оператора для выполнения. Нельзя использовать с параметром -f.

psql #

Синтаксис:

shardmanctl [общие_параметры] psql -s |--shard имя_сегмента

Без заданных параметров подключается к первому доступному ведущему узлу.

-s имя_сегмента
--shard=имя_сегмента #

Имя сегмента. Если оно указано, подключение происходит к текущему ведущему узлу сегмента.

daemon set #

Синтаксис:

shardmanctl [общие_параметры] daemon set [--session-log-level debug | info | warn | error] [--session-log-format json|text] [--session-log-nodes]

Позволяет обновить параметры протоколирования «на лету».

--session-log-level debug | info | warn | error #

Указывает уровень детализации сообщений: debug, info, warn или error.

--session-log-format json|text #

Указывает выходной формат журнала: text или json.

--session-log-nodes #

Указывает узел, которые необходимо обновить. Если не задан, параметры обновляются на всех узлах.

По умолчанию: все узлы.

history #

Синтаксис:

shardmanctl [общие_параметры] ] history [--reverse | -r] [-f|--format json|text] [-l|--limit число_команд]

Выводит историю команд, которые привели к изменению кластера. По умолчанию отсортированы от самых недавних к самым старым.

-r
--reverse #

Переключает на сортировку по возрастанию.

-f json|text
--format=json|text #

Указывает выходной формат.

По умолчанию: text.

-l
--limit=число_команд #

Лимит числа выводимых последних команд. Максимальное число — 200.

По умолчанию: 20.

Общие параметры #

Общие параметры shardmanctl — это необязательные параметры, не являющиеся специфичными для данной утилиты. Они определяют параметры подключения etcd, имя кластера и некоторые другие параметры. По умолчанию shardmanctl пытается подключиться к хранилищу etcd 127.0.0.1:2379 и использовать имя кластера cluster0. Уровень журнала по умолчанию — info.

-h, --help #

Показывает краткую справочную информацию.

--cluster-name имя_кластера #

Указывает имя кластера, где будет работать. По умолчанию указывается имя кластера cluster0.

--log-level уровень #

Задаёт уровень детализации журнала. Возможные значения уровня (от минимального до максимального): error, warn, info и debug. По умолчанию используется info.

--retries число #

Указывает, сколько раз shardmanctl должен повторять прерванный запрос к etcd. Если запрос etcd прерывается, скорее всего, из-за проблем с подключением, shardmanctl повторяет его указанное количество раз, прежде чем сообщить об ошибке. Значение по умолчанию — 5.

--session-timeout секунды #

Указывает таймаут блокировок в сеансе shardmanctl. Если нет связи между shardmanctl и хранилищем etcd в течение указанного количества секунд, блокировка снимается. Значение по умолчанию — 30.

--store-endpoints строка #

Задаёт адрес/порт etcd в формате: http[s]://адрес[:порт](,http[s]://адрес[:порт])*. Значение по умолчанию — http://127.0.0.1:2379.

--store-ca-file строка #

Проверяет сертификат сервера хранилища etcd с поддержкой HTTPS, используя этот пакет CA.

--store-cert-file строка #

Указывает файл сертификата для идентификации клиента в хранилище etcd.

--store-key строка #

Указывает файл закрытого ключа для идентификации клиента в хранилище etcd.

--store-timeout длительность #

Задаёт тайм-аут для запроса etcd. Значение по умолчанию — 5 секунд.

--monitor-port число #

Указывает порт HTTP-сервера shardmand для метрик и точек трассировки. По умолчанию — 15432.

--api-port число #

Указывает порт для API HTTP-сервера shardmand. По умолчанию — 15432.

--version #

Показывает информацию о версии shardman-utils.

Переменные окружения #

SDM_BACKUP_MODE #

Аналог параметра --backup-mode.

SDM_BACKUP_PATH #

Аналог параметра --backup-path.

SDM_CLUSTER_NAME #

Аналог параметра --cluster-name.

SDM_ETCD_PATH #

Аналог параметра --etcd-path.

SDM_FILE #

Аналог параметра --file в команде config update.

SDM_LOG_LEVEL #

Аналог параметра --log-level.

SDM_NODES #

Аналог параметра --nodes в командах nodes add и nodes rm.

SDM_RETRIES #

Аналог параметра --retries.

SDM_SPEC_FILE #

Аналог параметра --spec-file в команде init.

SDM_STORE_ENDPOINTS #

Аналог параметра --store-endpoints.

SDM_STORE_CA_FILE #

Аналог параметра --store-ca-file.

SDM_STORE_CERT_FILE #

Аналог параметра --store-cert-file.

SDM_STORE_KEY #

Аналог параметра --store-key.

SDM_STORE_TIMEOUT #

Аналог параметра --store-timeout.

SDM_SESSION_TIMEOUT #

Аналог параметра --session-timeout.

Использование #

Добавление узлов в кластер Shardman #

Чтобы добавить узлы в кластер Shardman, выполните следующую команду:

shardmanctl [общие_параметры] nodes add -n|--nodes имена_узлов

Необходимо указать -n (--nodes) для передачи списка добавляемых узлов, разделённых запятыми. Ко всем узлам можно обращаться по их именам хостов или IP-адресам. Имена должны быть правильно разрешены на всех узлах.

Если во время выполнения команды nodes add произошёл сбой, используйте команду cleanup --after-node-operation, чтобы исправить возможные проблемы с конфигурацией кластера.

Выполнение очистки #

По умолчанию cleanup работает только в режиме отчёта, т. е. следующая команда покажет только действия, которые необходимо выполнить во время фактической очистки:

    shardmanctl [общие_параметры] cleanup --after-node-operation|--after-rebalance
   

Чтобы выполнить фактическую очистку, запустите следующую команду:

    shardmanctl [общие_параметры] cleanup -p|--processrepgroups --after-node-operation|--after-rebalance
   

Отображение топологии кластера #

Команда cluster topology отображает текущую топологию кластера, по умолчанию в виде таблицы. Все узлы кластера будут сгруппированы по группам репликации, к которым они принадлежат. Для каждого узла будет отображаться его статус.

    shardmanctl [общие_параметры] cluster topology -f|--format table|json|text
   

Проверка работы службы shardmand на узлах #

Команда daemon check не только проверяет, запущена ли служба shardmand на указанных узлах, но и гарантирует, что эти службы настроены для того же кластера, что и shardmanctl:

    shardmanctl [общие_параметры] daemon check -n|--nodes имена_узлов
   

Удаление узлов из кластера Shardman #

Чтобы удалить узлы из кластера Shardman, выполните следующую команду:

shardmanctl [общие_параметры] nodes rm -n|--nodes имена_узлов

Укажите параметр -n (--nodes) для передачи списка удаляемых узлов, перечисленных через запятую. Команда восстанавливает все секции сегментированных таблиц.

Примечание

Не используйте команду cleanup для устранения возможных проблем с конфигурацией кластера после сбоя команды nodes rm. Вместо этого ещё раз выполните nodes rm.

Чтобы удалить все узлы в кластере без сохранения данных, повторно инициализируйте кластер. Если удалённая группа репликации содержит локальные (несегментированные и неглобальные) таблицы, данные теряются после удаления группы репликации.

Получение статуса резервного кластера #

Ниже представлен пример вывода статуса из shardmanctl для статусов OK и Error и кластера в режиме резерва. Также показывает, до какой точки синхронизации была восстановлена каждая БД и нужно ли ждать восстановления до следующей точки синхронизации. Для резервного кластера вывод будет выглядеть так (в отличие от того, что будет получено командой --filter):

        $ shardmanctl status
        
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                                                        == STANDBY CLUSTER STATUS ==                                                                                                                                                                      │
├─────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┤─────────────────────────────────────────────────────┤
│            STATUS           │                                                      MESSAGE                                                     │                           NODE                          │                    REPLICATION GROUP                    │        LSN_DIFF          │        TIME_DIFF         │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/1189F0A0, last found │                          shrn1r                         │                         shard-1                         │          25.75MB         │           162            │
│                             │                                            syncpoint LSN is 0/11CA0588                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│              OK             │                          Instance recovered at a syncpoint with CSN 1754916734406196000                          │                          shrn2r                         │                         shard-2                         │          18.8MB          │           102            │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────│──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/157A3618, last found │                          shrn3r                         │                         shard-3                         │          277.1MB         │           162            │
│                             │                                            syncpoint LSN is 0/233CEB70                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/16C743C8, last found │                          shrn4r                         │                         shard-4                         │          277.1MB         │           162            │
│                             │                                            syncpoint LSN is 0/2616C078                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/1AB9A798, last found │                          shrn5r                         │                         shard-5                         │          277.1MB         │           162            │
│                             │                                            syncpoint LSN is 0/2DF8F348                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│              OK             │                          Instance recovered at a syncpoint with CSN 1754916734406196000                          │                          shrn6r                         │                         shard-6                         │          18.8MB          │           102            │
└─────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┘


          
        

Для формата json:

shardmanctl status --format json
[
 {
  "Title": "STANDBY CLUSTER STATUS",
  "Messages": [
   {
    "Status": "WARNING",
    "Message": "Instance recovered using catchup, need to wait for recovery to the next syncpoint",
    "Node": "shrn1r",
    "Shard": "shard-1"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn2r",
    "Shard": "shard-2"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn3r",
    "Shard": "shard-3"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn4r",
    "Shard": "shard-4"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn5r",
    "Shard": "shard-5"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn6r",
    "Shard": "shard-6"
   }
  ]
 }
]

LSN_DIFF показывает разницу между последним применённым LSN на основном экземпляре и на резервном. TIME_DIFF показывает, сколько времени в секундах прошло после создания текущей применённой на резервном кластере точки синхронизации.

Получение статуса подсистем кластера #

Чтобы получить отчёт о состоянии кластера Shardman в формате таблицы для подсистем metadata и store, отсортированных по группам репликации, выполните следующую команду:

    shardmanctl [общие_параметры] status --filter=metadata,store --sort=rg
   

Чтобы получить отчёт в формате JSON, используйте параметр -f|--format=json (не включён выше, так как формат table используется по умолчанию). О каждой обнаруженной проблеме сообщается со статусом «Unknown», «Warning», «Error» или «Fatal error». Инструмент также может сообщить об операционной ошибке, что означает, что во время проверки работоспособности кластера возникла проблема. Когда команда обнаруживает критическую или операционную ошибку, дальнейшая диагностика прекращается. Например, несогласованность метаданных хранилища не позволяет выполнять правильные операции с кластером и должна быть устранена в первую очередь.

Вывод списка неразобранных распределённых транзакций #

Чтобы просмотреть список распределённых транзакций, которые не удалось разобрать встроенными средствами мониторинга Shardman, выполните следующую команду:

    shardmanctl [общие_параметры] status transactions -r|--repgroup имя_группы_репликации

Информация о каждой транзакции состоит из tx_id (идентификатор транзакции), coordinator_id, creation_time и description (ошибка или статус транзакции). Чтобы отобразить список транзакций для определённой группы репликации, используйте параметр -r|--repgroup (по умолчанию для всех групп репликации). Если таких транзакций нет, команда возвращает значение null в формате JSON.

Выгрузка всех ключей из хранилища для отладки конфигурации ошибок #

Столкнувшись с ошибкой при использовании кластера Shardman, для получения исчерпывающего отчёта полезно выгрузить все конфигурации, которые могут привести к такой ошибке, используя следующую команду:

    shardmanctl [общие_параметры] store dump -f|--file имя_файла
   

Могут отображаться некоторые некритичные ошибки, но они не будут прерывать выгрузку. Если имя файла не указано, данные выводятся в stdout и могут замусорить терминал.

Получение текущей конфигурации stolon #

Чтобы получить текущую конфигурацию stolon, которая обычно является частью ключа кластера в хранилище, используйте следующую команду:

    shardmanctl [общие_параметры] store get -a|--alias stolonspec -f|--file имя_файла
   

Если сам ключ кластера повреждён, конфигурация stolon также не будет отображаться. Вместо использования псевдонима можно также узнать полное имя ключа данных кластера (выведя все ключи командой store keys) и использовать store get, чтобы получить его и найти в нём часть stolon. Учтите, что при использовании последнего варианта параметр shardman.config_uuid не будет удалён, что может привести к конфликту при последующем использовании этих данных. Для манипуляций с конфигурацией stolon рекомендуется использовать команду shardmanctl store get -a stolonspec.

Получение имён ключей кластера и ковша для текущего кластера #

Чтобы получить сразу все имена ключей в хранилище, выполните следующую команду:

    shardmanctl [общие_параметры] store keys
   

Они могут отображаться только в формате JSON. Также будут выведены псевдонимы для тех ключей, у которых они есть (за исключением stolonspec и spec, так как они являются частями других ключей)

Вывод информации о текущей блокировке метаданных кластера #

Можно просмотреть информацию о текущих блокировках метаданных кластера, полученных любой командой:

    shardmanctl [общие_параметры] store lock -f|--format json
   

Чтобы получить отчёт в формате JSON, используйте параметр -f|--format=json (не указан выше, поскольку формат text используется по умолчанию). Если блокировка не существует, возвращает Lock not found.

Установка новой конфигурации для кластера #

Чтобы установить новую часть конфигурации кластера, выполните следующую команду:

    shardmanctl [общие_параметры] store set --alias=spec --file=spec.json
   

Поскольку spec является частью ключа данных кластера, его нельзя задать в параметре --key. Если выбранный файл не формата JSON, новая часть конфигурации не будет установлена.

Регистрация кластера Shardman #

Чтобы зарегистрировать кластер Shardman в хранилище etcd, выполните следующую команду:

    shardmanctl [общие_параметры] init [-y|--yes] [-f|--spec-file имя_файла_конфигурации]|текст_конфигурации
   

В этой команде необходимо передать строку с конфигурацией кластера. Это можно сделать следующим образом:

  • В командной строке — не указывать параметр -f и передать строку в текст_конфигурации.

  • В стандартном вводе — указать параметр -f и передать - в имя_файла_конфигурации.

  • В файле — указать параметр -f и передать имя файла в имя_файла_конфигурации.

Резервное копирование кластера Shardman командой probackup #

Требования к резервному копированию и восстановлению кластера Shardman командой probackup перечислены в Подразделе 2.6.1.1.

Например, следуя этим требованиям, на узле резервного копирования:

  groupadd postgres
  useradd -m -N -g postgres -r -d /var/lib/postgresql -s /bin/bash
 

Затем добавьте ключи SSH, чтобы обеспечить SSH-соединение без пароля между узлом резервного копирования и узлами кластера Shardman. Затем на узле резервного копирования:

  apt-get install pg-probackup shardman-utils
  mkdir -p каталог
  chown postgres:postgres каталог -R
  shardmanctl [общие_параметры] probackup init --backup-path=каталог --etcd-path=каталог/etcd --remote-user=postgres --remote-port=22
  shardmanctl [общие_параметры] probackup archive-command --backup-path=каталог --remote-user=postgres --remote-port=22
  

Если вышеуказанные требования соблюдены, запустите подкоманду backup для резервного копирования кластера:

shardmanctl [общие_параметры] probackup backup --backup-path=каталог --etcd-path=каталог --backup-mode=РЕЖИМ
  

Следует указать каталоги в параметрах --backup-path и --etcd-path, а режим резервного копирования в --backup-mode. Доступны различные режимы копирования: FULL, DELTA, PTRACK и PAGE. Также можно указать параметры сжатия резервной копии в параметрах --compress, --compress-algorithm и --compress-level и указать параметры --remote-port и --remote-user. Можно ограничить количество одновременно выполняемых задач при резервном копировании, задав ограничение в параметре --maxtasks.

По умолчанию для создания резервной копии используется копирование данных по протоколу SSH. Чтобы изменить это поведение и скопировать данные в смонтированную секцию, используется параметр --storage-type со значением mount. Это значение будет автоматически использоваться в процессе восстановления.

Можно скопировать данные в S3-совместимое хранилище. Для этого используйте параметр --storage-type со значением S3. Это значение требует указания каталога для хранения журналов pg_probackup в команде --log-directory или в переменной окружения SDM_LOG_DIRECTORY, например:

export SDM_LOG_DIRECTORY=/backup/logs

Чтобы выполнить резервное копирование или восстановление только для S3-совместимого хранилища, вместо указания параметра --storage-type в каждой команде probackup можно установить переменную окружения:

export SDM_STORAGE_TYPE=S3
                

Восстановление кластера Shardman командой probackup #

Расширение shardmanctl в режиме probackup может выполнять полное восстановление, восстановление только метаданных или восстановление только схемы кластера Shardman из резервной копии, созданной командой probackup backup.

Чтобы выполнить полное или частичное восстановление, сначала необходимо выбрать желаемую резервную копию для восстановления. Чтобы отобразить список доступных резервных копий, выполните следующую команду:

shardmanctl [общие_параметры] probackup show --backup-path=путь --format=формат [--archive ] [-i|--backup-id ид_резервной_копии] [--instance экземпляр]

После этого должен отобразиться список резервных копий с их идентификаторами в формате таблицы или JSON. Затем выберите нужный идентификатор резервной копии и запустите команду восстановления probackup.

shardmanctl [общие_параметры] probackup restore --backup-path=путь --backup-id=идентификатор

Укажите путь к репозиторию в параметре --backup-path и идентификатор резервной копии во флаге --backup-id.

Если возникли проблемы с экземпляром etcd, лучше выполнить восстановление только метаданных. Для этого можно запустить следующую команду:

shardmanctl [общие_параметры] probackup restore --backup-path=путь --backup-id=идентификатор --metadata-only

Если нужно восстановить только информацию о схеме, например: таблицы, роли и т. д., следует указать параметр --schema-only.

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

Можно указать параметр --shard для восстановления только в одном сегменте.

Также можно указать параметр --recovery-target-time для выполнения восстановления на момент времени. В этом случае Shardman находит ближайшую точку синхронизации к указанной временной метке и предлагает выполнить восстановление по найденному значению LSN. Чтобы ограничить количество обрабатываемых сегментов WAL, можно указать параметр --wal-limit.

Важно

Перед восстановлением кластера Shardman необходимо убедиться, что кластер запущен, выполнив команду shardmanctl status. Если в выводе присутствуют ошибки, восстановление кластера может сделать его недоступным. Сначала необходимо исправить ошибки, повторно инициализировав кластер, и восстановить метаданные etcd. Только после этого можно проводить восстановление кластера из резервной копии.

Переинициализация реплик #

Если реплики находятся в неправильном состоянии, их можно сбросить с помощью команды shardmanctl:

shardmanctl [общие_параметры] shard --shard=имя_сегмента replicas reinit

Эта команда определяет узлы, на которых запущены реплики указанного сегмента, и отправляет запрос shardmand на этих узлах. После получения этого запроса shardmand очищает каталог данных postgres и перезапускает процесс keeper, отвечающий за управление репликой. После этого реплики перезапускаются и начинают получать данные от соответствующего ведущего сервера.

Примеры #

Инициализация кластера

Для инициализации кластера Shardman с именем cluster0, который использует кластер etcd, состоящий из прослушивающих порт 2379 узлов n1, n2 и n3, проверьте правильность параметров в файле конфигурации sdmspec.json и выполните:

$ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 init -f sdmspec.json

Получение строки подключения к кластеру

Чтобы получить строку подключения для кластера Shardman с именем cluster0, который использует кластер etcd, состоящий из узлов n1, n2 и n3, прослушивающих порт 2379, выполните:

  $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 getconnstr
  
  dbname=host postgres=n1,n4,n2,n1,n1,n2,n4,n3 password=yourpasswordhere port=5432,5433,5432,5433,5432,5433,5432,5433 user=postgres
  
  

Чтобы добавить информацию о репликах в результат команды getconnstr, используется параметр --all.

Получение статуса кластера

Ниже представлен пример вывода статуса из shardmanctl со статусами OK и Error:

        $ shardmanctl status --filter store,shardmand,rg --sort=node
        
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                            == STORE STATUS ==                                            │
├────────────┬─────────────────────────────────────────────┬───────────────────────┬───────────────────────┤
│   STATUS   │                   MESSAGE                   │   REPLICATION GROUP   │          NODE         │
├────────────┼─────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ etcd store is OK                            │                       │                       │
└────────────┴─────────────────────────────────────────────┴───────────────────────┴───────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                          == SHARDMAND STATUS ==                                           │
├────────────┬─────────────────────────────────────────────┬───────────────────────┬───────────────────────┤
│   STATUS   │                   MESSAGE                   │   REPLICATION GROUP   │          NODE         │
├────────────┼─────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ shardmand on node 56d819b4e9e4 is OK        │                       │      56d819b4e9e4     │
├────────────┼─────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ shardmand on node 6d0aabd50acc is OK        │                       │      6d0aabd50acc     │
└────────────┴─────────────────────────────────────────────┴───────────────────────┴───────────────────────┘
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                       == REPLICATION GROUP STATUS ==                                      │
├────────────┬──────────────────────────────────────────────┬───────────────────────┬───────────────────────┤
│   STATUS   │                    MESSAGE                   │   REPLICATION GROUP   │          NODE         │
├────────────┼──────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ Replication group clover-1-56d819b4e9e4 is   │ clover-1-56d819b4e9e4 │                       │
│            │ OK                                           │                       │                       │
├────────────┼──────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│            │ Replication connection is down for slave     │                       │                       │
│    Error   │ 6d0aabd50acc:5442 in replication group       │ clover-1-6d0aabd50acc │   6d0aabd50acc:5442   │
│            │ clover-1-6d0aabd50acc                        │                       │                       │
└────────────┴──────────────────────────────────────────────┴───────────────────────┴───────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────────────┐

│                           == RESTART REQUIRED PARAMS STATUS ==                          │

├──────────┬──────────────────────────────────────┬───────────────────┬───────────────────┤

│  STATUS  │                MESSAGE               │ REPLICATION GROUP │        NODE       │

├──────────┼──────────────────────────────────────┼───────────────────┼───────────────────┤

│    OK    │     No pending restart parameters    │      shard-1      │       shrn1       │

├──────────┼──────────────────────────────────────┼───────────────────┼───────────────────┤

│    OK    │     No pending restart parameters    │      shard-2      │       shrn4       │

└──────────┴──────────────────────────────────────┴───────────────────┴───────────────────┘
          
        

Изменение конфигурации stolon

Сначала получите список доступных ключей в хранилище, используя следующую команду:

      $ shardmanctl store keys
        
{
 "Key": "shardman/cluster0/data/cluster",
 "Alias": "cluster"
}{
 "Key": "shardman/cluster0/data/shardmand/56d819b4e9e4"
}{
...
 "Key": "shardman/cluster0/stolon/remoteLogs/6d0aabd50acc/clover-1-6d0aabd50acc/keeper_1/error"
}
        
      

Получите конфигурацию stolon из хранилища и сохраните её в файле stolonspec.json, используя команду

       $ shardmanctl store get -a stolonspec -f stolonspec.json
     

Примените необходимые изменения и загрузите новую конфигурацию командой shardmanctl config update. Учтите, что параметр shardman.config_uuid удаляется в команде shardmanctl store get -a stolonspec, а не в shardmanctl store get -k full/path/to/clusterspec; использование конфигурации с существующим shardman.config_uuid приведёт к конфликту.

Важно

Не используйте команду store set для обновления конфигураций кластера, поскольку она не применяет новую конфигурацию ко всем узлам, а только записывает её в хранилище. Для текущего примера с конфигурацией stolon допустимо выполнение shardmanctl config update.

Для перепроверки можно получить ключ кластера с новой StolonSpec по полному имени ключа (которое было показано ранее командой store keys):

      $ shardmanctl store get -k shardman/cluster0/data/cluster
        
{
  "FormatVersion": 1,
  "Spec": {
    "PgSuAuthMethod": "md5",
    "PgSuPassword": "12345",
    "PgSuUsername": "postgres",
    "PgReplAuthMethod": "md5",
    "PgReplPassword": "12345",
    "PgReplUsername": "repluser",
    "ShardSpec": {
      ...
}
        
      

Добавление узлов в кластер

Чтобы добавить узлы n1,n2, n3 и n4 в кластер, выполните:

$ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 nodes add -n n1,n2,n3,n4

Важно

Количество добавляемых узлов должно быть кратно Repfactor + 1, если используется политика размещения cross.

Удаление узлов из кластера

Чтобы удалить узлы n1 и n2 из кластера cluster0, выполните:

      $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 nodes rm -n n1,n2
    

Если используется политика размещения cross, вместе с узлами будут удалены звенья, содержащие эти узлы.

Выполнение запроса во всех группах репликации

Чтобы выполнить запрос select version() во всех группах репликации, используйте:

 $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 forall --sql 'select version()'
 
 Node 1 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 Node 4 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 Node 3 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 Node 2 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 
 

Выполнение перебалансировки

Чтобы выполнить перебалансировку сегментированных таблиц в кластере cluster0, выполните:

 $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 rebalance
 

Обновление параметров конфигурации PostgreSQL #

Чтобы установить для параметра max_connections значение 200 в кластере, создайте файл конфигурации (например, ~/stolon.json) со следующим содержимым:

 {
   "pgParameters": {
     "max_connections": "200"
   }
 }
 

Затем выполните:

  $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 config update -p -f ~/stolon.json
  

Поскольку для изменения max_connections требуется перезапуск, эта команда перезапускает экземпляры СУБД.

Выполнение резервного копирования и восстановления

Чтобы создать резервную копию кластера cluster0, используя etcd на etcdserver, прослушивающем порт 2379, и сохранить его в локальном каталоге /var/backup/shardman, выполните:

$ shardmanctl --store-endpoints http://etcdserver:2379 backup --datadir=/var/backup/shardman --use-ssh

Предположим, что вы выполняете восстановление из резервной копии в кластер cluster0, используя etcd на etcdserver, прослушивающем порт 2379, и берёте описание резервной копии из файла /var/backup/shardman/backup_info. Отредактируйте файл /var/backup/shardman/backup_info, если необходимо, задайте параметры DataRestoreCommand, RestoreCommand и запустите:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover --info /var/backup/shardman/backup_info

Чтобы восстановить только мета-данные:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover --metadata-only --dumpfile /var/backup/shardman/etcd_dump

Чтобы восстановить только схемы:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover --schema-only --dumpfile /var/backup/shardman/etcd_dump

Чтобы восстановить только один сегмент:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover  --info /var/backup/shardman/backup_info --shard shard_1

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

Чтобы создать резервную копию кластера cluster0, используя etcd на etcdserver, прослушивающем порт 2379, и сохранить её в локальном каталоге /var/backup/shardman, сначала инициализируйте репозиторий резервных копий подкомандой init:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup init --backup-path=/var/backup/shardman --etcd-path=/var/backup/etcd_dump

Затем добавьте и включите команду archive_command с подкомандой archive-command:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup archive-command add --backup-path=/var/backup/shardman

Если репозиторий успешно инициализирован и успешно добавлена archive-command, создайте резервную копию в режиме FULL, используя подкоманду probackup backup:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup backup --backup-path=/var/backup/shardman --etcd-path=/var/backup/etcd_dump --backup-mode=FULL --compress --compress-algorithm=zlib --compress-level=5

Чтобы создать резервную копию в режиме DELTA, PTRACK или PAGE, запустите подкоманду probackup backup со значением DELTA, PTRACK или PAGE параметра --backup-mode:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup backup --backup-path=/var/backup/shardman --etcd-path=/var/backup/etcd_dump --backup-mode=DELTA --compress --compress-algorithm=zlib --compress-level=5

Чтобы узнать идентификатор созданной резервной копии, запустите подкоманду show:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup show --backup-path=/var/backup/shardman --format=table

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                                      == BACKUP ID 'S88FRO'                                                                                                     │
│                                                                                                               ==                                                                                                               │
├───────────────────────────────────┬───────────────────────────────────┬───────────────────────────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┤
│              INSTANCE             │                HOST               │           RECOVERY TIME           │    MODE    │  WAL MODE  │     TLI    │    DATA    │     WAL    │   Z-RATIO  │  START LSN │  STOP LSN  │   STATUS   │
├───────────────────────────────────┼───────────────────────────────────┼───────────────────────────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│              shard-1              │               n1                  │       2024-02-02 14:19:05+00      │    FULL    │   ARCHIVE  │     1/0    │  42.37MiB  │    16MiB   │    1.00    │  0/C000028 │  0/D0018B0 │     OK     │
├───────────────────────────────────┼───────────────────────────────────┼───────────────────────────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│              shard-2              │               n2                  │       2024-02-02 14:19:05+00      │    FULL    │   ARCHIVE  │     1/0    │  42.38MiB  │    16MiB   │    1.00    │  0/C000028 │  0/D001E00 │     OK     │
└───────────────────────────────────┴───────────────────────────────────┴───────────────────────────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘


В режиме PTRACK Shardman отслеживает изменения страниц на лету. Чтобы он работал, не требуется производить непрерывное архивирование. При каждом изменении страницы отношения она помечается в специальной битовой карте PTRACK. Это отслеживание немного увеличивает издержки в работе сервера, но значительно ускоряет инкрементальное резервное копирование.

Если будут использоваться резервные копии PTRACK, выполните следующие дополнительные шаги:

  • Предварительно загрузите общую библиотеку ptrack на каждом узле. Добавьте значение ptrack к параметру shared_preload_libraries.

  • Создайте расширение PTRACK на каждом узле кластера:

                                $ shardmanctl --store-endpoints http://etcdserver:2379 forall --sql "create extension ptrack"
    
  • Для включения отслеживания изменений страницы, задайте параметр ptrack.map_size следующим образом:

                                $ shardmanctl --store-endpoints http://etcdserver:2379 update '{"pgParameters":{"ptrack.map_size":"64"}}'
    

    Для оптимальной производительности рекомендуется задавать ptrack.map_size равным N/1024, где N — максимальный размер узла кластера в мегабайтах. Если задать меньшее значение, увеличится вероятность наложения информации из разных блоков в карте PTRACK, что повлечёт ложные положительные результаты при определении изменённых блоков и, как следствие, увеличение размера инкрементальной копии, так как в копию будут попадать и фактически неизменённые блоки. Использовать значения ptrack.map_size, превышающие 1024, не рекомендуется, хотя PTRACK поддерживает большие карты.

Чтобы проверить созданную резервную копию, запустите подкоманду validate:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup validate --backup-path=/var/backup/shardman --backup-id=RFP1FI

Предположим, что выполняется восстановление из резервной копии в кластер cluster0, используя etcd на etcdserver, прослушивающем порт 2379, и берётся идентификатор резервной копии из команды show:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --backup-path=/var/backup/shardman --backup-id=RFP1FI
  

Наконец, нужно снова включить archive_command.

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup archive-command add --backup-path=/var/backup/shardman

Для восстановления только метаданных выполните:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --schema-only --backup-path=/var/backup/shardman --backup-id=RFP1FI

Для восстановления одного сегмента выполните:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --backup-path=/var/backup/shardman --backup-id=RFP1FI --shard shard_1

Для восстановления на определённый момент времени выполните:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --metadata-only --backup-path=/var/backup/shardman --backup-id=RFP1FI --recovery-target-time='2006-01-02 15:04:05' -s

Загрузка данных из текстового файла

Чтобы загрузить данные в кластер Shardman, выполните следующую команду:

$ shardmanctl --store-endpoints http://etcdserver:2379 load --file=/var/load/data.tsv --table=mytable --source file --format text -j 8
    

В этом примере данные загружаются из файла данных /var/load/data.tsv (с разделением табуляцией) в таблицу mytable в 8 параллельных потоков. Можно использовать schema.table в качестве имени таблицы.

Загрузка данных из таблицы PostgreSQL

Чтобы загрузить данные в кластер Shardman из таблицы PostgreSQL, выполните следующую команду:

$ shardmanctl --store-endpoints http://etcdserver:2379 load -t desttable --source postgres --source-connstr "dbname=db host=srchost port=srcport user=login password=passwd" --source-table sourcetable -j 8
     

В этом примере данные загружаются из таблицы sourcetable в таблицу desttable в 8 параллельных потоков. Можно использовать schema.table в качестве имён таблиц.

Загрузка данных из схемы PostgreSQL #

Чтобы загрузить данные из схемы PostgreSQL в кластер Shardman, выполните следующую команду:

$ shardmanctl --store-endpoints http://etcdserver:2379 load --schema load_schema.yaml
     

Файл load_schema.yaml имеет следующий формат:

version: "1.0"
migrate:
  connstr: "dbname=workdb host=workhost port=workport user=workuser password=workpassword"
  jobs: 8
  batch: 1000
  options:
    - create_schema
    - create_table
    - create_index
    - create_sequence
    - create_foreign_key
    - create_role
    - copy_ownership
    - copy_grants
    - truncate_table
    - skip_no_pkey_tables
    - skip_create_index_error
    - skip_create_extension_error
    - skip_load_errors
    - skip_create_foreign_key_error
    - skip_create_role_error
    - skip_copy_grants_error
    - skip_copy_ownership_error
  schemas:
    - name: public
      all: false
      tables:
        - name: tab1
          type: sharded
          partitions: 6
          distributedby: id
          priority: 3
        - name: tab2
          type: global
        - name: tab3
          type: sharded
          partitions: 6
          distributedby: field_id
          colocatewith: tab1
        - name: table4
            type: global
            source: schema.view
            source_pk: field_id
        - name: table5
            type: global
            source: schema.func(arg)
            source_pk: field_id
    - name: schema2
      all: false
      default_type: sharded
      default_partitions: 6
      tables:
        - name: table1
          distributedby: field_id
          priority: 2
        - name: table2
          type: global
        - name: table3
          source: schema.view
          distributedby: field_id
          priority: 3
        - name: table4
          distributedby: field_id
          source: schema.func(arg)
        - name: table5
          source: schema."complex.""table.name"
          distributedby: field_id
    - name: schema3
      all: true
      skip_tables: [table1, table2, table3]
  roles:
    - name: test_user1
      password: test_password
    - name: test_user2
    

Параметр migrate.jobs определяет количество параллельных процессов загрузки данных.

Параметр migrate.batch задаёт число строк в одной порции (рекомендуемое значение — 1000).

Параметр migrate.schema определяет массив желаемых схем исходной базы данных. Все остальные схемы будут пропущены.

Если для параметра all задано значение true, то будут перенесены все таблицы из текущей схемы (с типом global по умолчанию). Если таблица указана в массиве migrate.schemas.tables, то для неё необходимо явно указать тип целевой таблицы. В настоящее время поддерживаются два типа таблиц: global и sharded. Сначала загружаются глобальные (global) таблицы, затем сегментированные (sharded) таблицы и в конце сегментированные таблицы с параметром colocatedwith. Порядок загрузки таблиц одного типа можно изменить с помощью параметра priority.

Секция migrate.schemas.skip_tables определяет массив имён таблиц, которые будут пропущены при загрузке схемы, даже если для параметра all установлено значение true.

Для сегментированных таблиц должны быть установлены следующие атрибуты: distributedby (указывает имя столбца, используемого для секционирования таблицы) и partitions (количество секций, которые будут созданы для этой таблицы). Для сегментированных таблиц может быть дополнительно установлен атрибут colocatewith (имя таблицы, с которой выполняется совместное размещение). Shardman попытается разместить секции созданной таблицы с тем же ключом секции на тех же узлах, что и соответствующие секции таблицы, указанные в colocatewith.

Можно указать параметр таблицы default_type для схемы: global или sharded (по умолчанию: global). Для сегментированного типа также можно указать параметр default_partitions (по умолчанию: 20). Если установлен default_type sharded, необходимо указать параметр distributedby для каждой таблицы.

Параметр source для таблицы должен включать схему и исходную таблицу: schema.source. Исходной может быть таблица, представление или функция. Например: public.table, public.view, public.func(arg). Если устанавливается представление или функция source для глобальной таблицы, необходимо указать в параметре source_pk, какой первичный ключ установлен для этой таблицы. Если source не указан или содержит имя таблицы, также можно указать параметр source_pk, чтобы создать первичный ключ или переопределить существующий.

Параметр priority для таблицы определяет порядок загрузки таблиц одного типа. Таблицы с большим значением priority загружаются раньше. Значение priority по умолчанию — 0.

Раздел migrate.roles определяет массив имён таблиц и паролей, которые будут скопированы из исходной базы данных, если задан параметр create_role.

Схема поддерживает следующие параметры:

  • create_schema — создавать схемы баз данных, если они не существуют.

  • create_table — создавать таблицы, если они не существуют.

  • create_index — создавать индексы после создания таблиц.

  • create_sequence — создавать последовательности, если они не существуют.

  • create_index — создавать индексы после создания таблиц.

  • truncate_table — опустошать таблицы перед загрузкой данных.

  • create_role — создать глобальные роли, заданные в migrate.roles, и скопировать параметры ролей из исходной базы данных.

  • copy_grants — скопировать права доступа из исходной базы данных.

  • copy_ownership — сменить владельцев таблиц на владельца в исходной базе данных.

  • skip_no_pkey_tables — пропускать таблицы без первичных ключей.

  • skip_create_index_error — пропускать ошибки создания индекса.

  • skip_create_extension_error — пропускать ошибки создания расширений.

  • skip_load_errors — продолжать загрузку при возникновении ошибок.

  • skip_create_foreign_key_error — пропускать ошибки создания внешних ключей.

  • skip_create_role_error — пропускать ошибки создания ролей.

  • skip_copy_ownership_error — пропускать ошибки смены владельца таблицы.

  • skip_copy_grants_error — пропускать ошибки при копировании прав доступа из исходной базы данных.

Инициализация и тесты производительности #

Чтобы инициализировать тест производительности через shardmanctl, используя pgbench со схемой shardman, масштабирование=1000, разделы=40, запустите:

$ shardmanctlbench init --schema-type=shardman --scale=1000 --partitions=40

Чтобы запустить инициализированный тест производительности для той же схемы shardman, при количестве заданий=4, количестве клиентов=10, продолжительности в секундах=60 и с полным выводом pgbench, используйте:

$ shardmanctl bench run --schema-type=shardman --jobs=4 --client=10 --time=60 --full-output

Чтобы инициализировать тест производительности с использованием custom схемы из файла schema.psql с масштабированием=1000, выполните:

$ shardmanctlbench init --schema-type=custom --schema-file=schema.psql --scale=1000

Чтобы запустить инициализированный тест производительности с использованием custom схемы и пользовательского скрипта транзакции из script.psql с количеством заданий =4, числом клиентов=10, продолжительность в секундах=60, используйте:

$ shardmanctl bench run --schema-type=custom --file=script.psql --jobs=4 --client=10 --time=60

Чтобы очистить базу данных PostgreSQL от таблиц tpc-b, используйте:

$ shardmanctl bench cleanup

Скрипты генерации тестов производительности

Чтобы сгенерировать последовательность тестов производительности через shardmanctl из файла конфигурации=cfg.yaml и вывести результат в file=script.sh, запустите:

$ shardmanctlbenchgenerate --config=cfg.yaml --output-file=script.sh

Пример файла конфигурации:

    benches:
    - schema_type: single
      init_flags: "-s 3"
      run_flags: "-n -P 10 -c 10 -j 4 -T 10"
    - schema_type: simple
      init_flags: "-s 4"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
      partitions: 100
    - schema_type: shardman
      init_flags: "-s 5"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
    - schema_type: custom
      init_flags: "-s 6"
      schema_file: "schema.psql"
                            

См. также

sdmspec.json , shardmand

shardmanctl

shardmanctl — Shardman auxiliary command-line client and deployment tool

Synopsis

shardmanctl [common_options] daemon check -n | --nodes node_names:port

shardmanctl [common_options] cleanup [ -p | --processrepgroups ] --after-node-operation --after-rebalance

shardmanctl [common_options] config generate [ -f | --file filename]

shardmanctl [common_options] config verify [ -f | --file filename]

shardmanctl [common_options] config get [ -f | --file ] [ -c | --choose-revision ] [ -r | --revision ]

shardmanctl [common_options] config revisions rm [ -r | --revision ] [ -y | --yes ]

shardmanctl [common_options] config update [[ -f | --file stolon_spec_file|shardman_spec_file] | spec_text [ --force ] [ -p | --patch ] [ -w | --wait time_duration]]

shardmanctl [common_options] config rollback [ -r | --revision ] [ -w | --wait time_duration] [ --force ]

shardmanctl [common_options] config update credentials [ -u | --user ] [ -p | --password ] [ -k | --ssl-key ] [ -c | --ssl-cert ] [ -w | --wait time_duration] [ -f | --force ] [ -y | --yes ]

shardmanctl [common_options] config revisions [ -f | --format json|text ]

shardmanctl [common_options] config revisions set --keep-config-revisions

shardmanctl [common_options] config update ip [ -u | ip_1=ip_2,hostname_1=hostname_2 ] [ -y | --yes ]

shardmanctl [common_options] config update fdw [ -y | --yes ]

shardmanctl [common_options] cluster repfactor set --value value

shardmanctl [common_options] cluster start

shardmanctl [common_options] cluster stop [ -y | --yes ]

shardmanctl [common_options] cluster topology [ -f | --format table|json|text ]

shardmanctl [common_options] forall --sql query [ --twophase]

shardmanctl [common_options] getconnstr --all

shardmanctl [common_options] init [ -y | --yes ] [ -f | --spec-file spec_file_name] | spec_text

shardmanctl [common_options] intcheck [ -s | --system ] [ -c | --catalog ] [ -u | --user ] [ -o | --output ] [ -n | --node node]

shardmanctl [common_options] load [ -b | --batch-size lines_limit] [ --destination-fields fields_list] [ --distributed-keys key_type_list] [ -D | --delimiter character] [ --null_marker string] [ -e | --escape character] [ -f | --file input_file] [ -F | --format text | csv ] [ -j | --jobs task_total] [ -q | --quote character] [ --reject-file filename] [ --schema filename] [ --source file | postgres ] [ --source-connstr connect_string] [ --source-fields fields_list] [ --source-table table|view|func] [ -t | --table destination_table] [ -h | --help ]

shardmanctl [common_options] nodes add -n | --nodes node_names [ --no-rebalance]

shardmanctl [common_options] nodes start -n | --nodes node_names [ --no-wait]

shardmanctl [common_options] nodes restart -n | --nodes node_names [ --no-wait]

shardmanctl [common_options] nodes stop -n | --nodes node_names [ --no-wait]

shardmanctl [common_options] nodes replace --old old_node --new new_node

shardmanctl [common_options] nodes rm -n | --nodes node_names

shardmanctl [common_options] probackup [ init | archive-command | backup | checkdb | delete | merge | restore | set-config | show | validate | show-config ] [ subcommand_options]

shardmanctl [common_options] rebalance [ -f | --force ]

shardmanctl [common_options] restart [ -y | --yes ] [ --no-wait ]

shardmanctl [common_options] restart rolling [ -y | --yes ] [ --restore-masters ] [ --upgrade ]

shardmanctl [common_options] set pgParam1=value1 [pgParam2=value2 [...]] [ -y | --yes ] [ -w | --wait time_duration] [ -f | --force ]

shardmanctl [common_options] shard -s | --shard shard_name add -n | --node node_names

shardmanctl [common_options] shard -s | --shard shard_name master set [ -y | --yes ] -n | --node node_names

shardmanctl [common_options] shard -s | --shard shard_name master reset [ -y | --yes ]

shardmanctl [common_options] shard -s | --shard shard_name reset [ -y | --yes ] [ --new-primary | -p ]

shardmanctl [common_options] shard -s | --shard shard_name rm -n | --node node_names [ -f | --force ]

shardmanctl [common_options] shard -s | --shard shard_name switch [ --new-primary node_names]

shardmanctl [common_options] shard -s | --shard shard_name start [ --no-wait ] [ -n | --node node_name]

shardmanctl [common_options] shard -s | --shard shard_name stop [ -n | --node node_name]

shardmanctl [common_options] shard -s | --shard shard_name replicas reinit [ --no-wait ] [ -y | --yes ] [ -n | --node node_names]

shardmanctl [common_options] status [ --filter all | dictionary | primary | metadata | rg | shardmand | store | topology | restart_required_params ] [ -f | --format text | json ] [ -s | --sort node | rg | status ]

shardmanctl [common_options] status transactions [ -r | --repgroup replication_group_name]

shardmanctl [common_options] store dump [ -f | --file filename]

shardmanctl [common_options] store restore [ --delete-old-keys ] [ -f | --file filename] [ -y | --yes ]

shardmanctl [common_options] store get [ -a | --alias cluster | ladle | repgroups | stolonspec | spec ] [ -k | --key keyname] [ -f | --file filename]

shardmanctl [common_options] store keys

shardmanctl [common_options] store set [ -a | --alias cluster | ladle | repgroups | stolonspec | spec ] [ -k | --key keyname] [ -f | --file filename]

shardmanctl [common_options] store lock [ -f | --format text | json ]

shardmanctl [common_options] tables sharded info [ -t | --table table ]

shardmanctl [common_options] tables sharded list

shardmanctl [common_options] tables sharded norebalance

shardmanctl [common_options] tables sharded partmove [ -t | --table table ] [ -s | --shard shard_name ] [ -p | --partnum partition_number ]

shardmanctl [common_options] tables sharded rebalance [ -t | --table table ] [ --skip-run-rebalance ]

shardmanctl [common_options] upgrade

shardmanctl [common_options] bench init [ --schema-type single|simple|shardman|custom ] [ -S | --schema-file file_name] [ -s | --scale scale_value] [ --partitions partitions_value] [ -n | --no-vacuum ] [ -F | --fillfactor fillfactor_value]

shardmanctl [common_options] bench run [ --schema-type single|simple|shardman|custom ] [ -f | --file file_name] [ -c | --client client_value] [ -C | --connect ] [ --full-output ] [ -j | --jobs jobs_value] [ -s | --scale scale_factor] [ -T | --time seconds] [ -t | --transactions transactions_value] [ -P | --progress seconds] [ -R | --rate rate] [ -M | --protocol querymode]

shardmanctl [common_options] bench cleanup

shardmanctl [common_options] bench generate [ -c | --config config_file] [ -o | --output-file file_name]

shardmanctl [common_options] script [ -s | --shard shard_name] [[ -f | --file file_name | --sql query]]

shardmanctl [common_options] psql -s | --shard shard_name

shardmanctl [common_options] daemon set [ --session-log-level | debug | info | warn | error ] [ --session-log-format | text | json ] [ --session-log-nodes ]

shardmanctl [common_options] history [ -r | --reverse ] [ -f | --format text | json ] [ -l | --limit number_of_commands ]

Here common_options are:

[ --cluster-name cluster_name ] [ --log-level error | warn | info | debug ] [ --monitor-port port] [ --retries retries_number] [ --session-timeout seconds] [ --store-endpoints store_endpoints] [ --store-ca-file store_ca_file] [ --store-cert-file store_cert_file] [ --store-key client_private_key] [ --store-timeout duration] [ --version] [ -h | --help ]

Description #

shardmanctl is an utility for managing a Shardman cluster.

For any command that uses the node name as an argument, the node name can be specified either by its hostname or IP address.

The cleanup command is used for cleanup after failure of the nodes add command or of the shardmanctl rebalance command. Final changes to the etcd store are done at the end of the command execution. This simplifies the cleanup process. During cleanup, incomplete clover definitions and definitions of the corresponding replication groups are removed from the etcd metadata. Definitions of the corresponding foreign servers are removed from the DBMS metadata of the remaining replication groups. Since the cleanup process can be destructive, by default, the tool operates in the report-only mode: it only shows actions to be done during the actual cleanup. To perform the actual cleanup, add the -p flag. For usage details of the command, see the section called “Performing Cleanup”.

The daemon check command is used to verify that shardmand daemon is running on the nodes specified by --nodes option and is configured for the same cluster as shardmanctl . For usage details of the command, see the section called “Checking shardmand Service on Nodes”.

The init command is used to register a new Shardman cluster in the etcd store or to reinitialize the existing cluster defining a new cluster configuration and removing all data and nodes. In the init mode, shardmanctl reads the cluster specification, processes it and saves to the etcd store as parts of two JSON documents: ClusterSpec — as part of shardman/cluster0/data/cluster and LadleSpec — as part of shardman/cluster0/data/ladle ( cluster0 is the default cluster name used by Shardman utilities). Common options related to the etcd store, such as --store-endpoints, are also saved to the etcd store and pushed down to all Shardman services started by shardmand. For the description of the Shardman initialization file format, see sdmspec.json. For usage details of the command, see the section called “Registering a Shardman Cluster”.

The config generate command is used to create a default sdmspec.json template. By default, data is returned to the standard output. To write the result to a file, use flag -f filename. For the description of the Shardman initialization file format, see sdmspec.json.

The config verify command is used to check a correctness of the input Shardman initialization file. By default, the configuration is read from standard input. To read the configuration from a file, use flag -f filename. For the description of the Shardman initialization file format, see sdmspec.json.

The config get command is used to output the current full cluster specification or a configuration of the specified revision. The command takes the current cluster configuration from the cluster store. For the description of the Shardman initialization file format, see sdmspec.json.

The config update command is used to update the stolon or full Shardman configuration. The new configuration is applied to all replication groups and is saved in shardman/cluster0/data/cluster etcd key. Note that config update can cause a DBMS restart.

The forall command is used to execute an SQL statement on all replication groups in a Shardman cluster.

The getconnstr command is used to get the libpq connection string for connecting to a cluster as administrator.

The load command is used to upload data from a text file to a distributed table or to upload a database schema from a PostgreSQL database to Shardman. When loading data from a file, text and csv formats are supported. If a file is compressed with gzip, it will be automatically decoded while reading. To read data from stdin, specify --file=-. The data loading process can be optimized by specifying the number of parallel workers (key -j).

The nodes add command is used to add new nodes to a Shardman cluster. With the default cross placement policy, nodes are added to a cluster by clovers. Each node in a clover runs the primary DBMS instance and perhaps several replicas of other nodes in the clover. The number of replicas is determined by the Repfactor configuration parameter. So, each clover consists of Repfactor + 1 nodes and can stand loss of Repfactor nodes.

With manual placement policy, each new node is added as a replication group consisting of one primary server. After adding primary nodes, you can add replicas to the new replication group by calling the shard add command.

shardmanctl performs the nodes add operation in several steps:

  1. Acquires a global metadata lock.

  2. For each specified node, checks that shardmand is running on it and that it sees the current cluster configuration.

  3. Calculates the services to be present on each node and saves this information in etcd as part of the shardman/cluster0/data/ladle Layout object.

  4. Generates the configuration for new stolon clusters (also called replication groups) and initializes them.

  5. Registers the added replication groups in the shardman/cluster0/data/ladle etcd key.

  6. Waits for shardmand to start all the necessary services, checks that new replication groups are accessible and have correct configuration.

  7. Creates an auxiliary broadcaster that holds locks on each existing replication group in the cluster.

  8. For each new replication group, copies all schemas and shardman schema data from a randomly selected existing replication group to the new one, ensures that the Shardman extension is installed on the new replication group, and recalculates OIDs used in the extension configuration tables.

  9. On each existing replication group, defines foreign servers referencing the new replication group and recreates definitions of foreign servers on the new replication group.

  10. Recreates all partitions of sharded tables as foreign tables referencing data from old replication groups and has the changes registered in the etcd storage.

  11. For each new replication group, copies the global table data from existing replication groups to the new one.

  12. Rebalances partitions of sharded tables. The rebalancing process for each sharded table iteratively determines the replication group with the maximum and minimum number of partitions and creates a task to move one partition to the replication group with the minimum number of partitions. This process is repeated while max - min > 1. To move partitions, we use logical replication. Partitions of colocated tables are moved together with partitions of the distributed tables to which they refer. You can skip this step using the --no-rebalance.

For usage details of the command, see the section called “Adding Nodes to a Shardman Cluster”.

The nodes rm command is used to remove nodes from a Shardman cluster. In the manual-topology mode, this command only removes the specified nodes from the cluster and if a node is the last in the replication group, the entire group gets removed. In the cross-replication mode, this command removes clovers containing the specified nodes from the cluster. The last clover in the cluster cannot be removed. Any data (such as partitions of sharded relations) on removed replication groups is migrated to the remaining replication groups using logical replication, and all references to the removed replication groups (including definitions of foreign servers) are removed from the metadata of the remaining replication groups. Finally, the metadata in etcd is updated. For usage details of the command, see the section called “Removing Nodes from a Shardman cluster”.

The probackup command is used to backup and restore the Shardman cluster using pg_probackup backup utility. For details of the probackup command logic, see Backup anf Recovery Shardman Backups using pg_probackup. For usage details of the command, see the section called “ probackup.

The rebalance command is used to evenly rebalance sharded tables in a cluster. This can be useful, for example, if you did not perform rebalance when adding nodes to the cluster. If the --force option is not provided, then tables with manually moved partitions will be skipped.

The cleanup command with flag --after-rebalance is used to perform cleanup after failure of a rebalance command. On each node, it cleans up subscriptions and publications left from the rebalance command and drops tables that store data of partially-transferred partitions of sharded tables.

The cluster repfactor set command is used to set the value of the replication factor for the Shardman cluster. This command can only be used in manual topology cluster mode. The value of the new replication factor is passed through the command line flag --value repfactor.

The cluster start command is used to start all stopped PostgreSQL instances with the cluster stop command. For the command to work, shardmand must be running.

The cluster stop command is used to stop all PostgreSQL instances for the Shardman cluster. At the same time, the shardmand daemons continue to work.

The cluster topology command is used visualize the topology of a cluster. By default, the topology is returned in a table view. If you want to get a JSON or text representation, then use the flag --format json|text.

The restart command is used to restart a Shardman cluster, including all shardmand instances. If PostgreSQL instances were previously stopped using the cluster stop command, they will be started. The command returns control after all primary nodes in the cluster have been restarted.

The set command is used to set one or more parameters for DBMS instances of the Shardman cluster. Parameters are passed as arguments to the command line, each of them looks like param=value. The command is actually an alternative to shardmanctl config update -p to update database settings.

The status command is used to display health status of Shardman cluster subsystems. It can show status of several components: store, metadata, shardmand, replication groups, primary nodes, dictionary, and restart of the required parameters. If only some subsystems are of interest, option --filter may be used. Also status supports sorting its messages by status, node or replication group and printing the result to stdout as a table (table), text (text) or JSON (json) with table as the default. For usage details of the command, see the section called “Getting the Status of Cluster Subsystems”.

The store dump command gets all the keys and their values from the etcd store and outputs them into the --file, where - value is used for outputting to stdout (default). It is intended to be used for debugging, so some harmless errors may be produced during execution, yet all the available information will be dumped. Only keys for the current cluster (with current cluster prefix like shardman/cluster0/) will be dumped. For usage details of the command, see the section called “Dumping All Keys from the Store to Debug Error Configuration”.

The store get command gets a particular value from the store by its key name. It is expected to be a JSON value, so if it is not (which is not prohibited), some harmless errors may be produced. The key to retrieve from store can be specified with --key option; several keys have aliases — short names for easy use. To get a key by its alias, use --alias option with one of the available aliases (use --help or examples below for reference). Also aliases stolonspec and spec can be used to manipulate initial cluster and stolon configuration explicitly, without retrieving it from the full cluster specification. It is recommended to use existing aliases instead of full key names since there are some additional checks in alias processing, which help to achieve safer results. By default, a key is printed to stdout (explicitly — with --file=- option), but can be output to any desired file. For usage details of the command, see the section called “Getting the Current stolon Specification”.

The store keys command shows all the keys in the store for the current cluster (with cluster prefix) and its aliases. Aliases stolonspec and spec are not shown since they are parts of other keys. For usage details of the command, see the section called “Getting the Cluster and Ladle Key Names For the Current Cluster”.

The store set command creates or rewrites one particular key in the store. It is not expected to be a JSON value for a random key, but if it is one of the keys that have aliases with a known mapping (like ladle or cluster), the command will not accept incorrect JSON structures. Just like store get command, store set accepts a key name via --key or --alias option and the input source file as --file (stdin is specified with - value). For usage details of the command, see the section called “Setting a New Spec for the Cluster”.

The store lock command show the current cluster meta lock information. In case lock does not exist returns Lock not found. Displays cluster id, command that acquired locks, host name and lock time. You can specify --format to output in json format or in text format (by default). For usage details of the command, see the section called “Output Current Cluster Meta Lock Information”.

The upgrade command is used to update the version of Postgresql shardman extension on all cluster nodes. Before upgrading extensions, you need to install new packages and run the restart command. As a result of upgrade, utilities will upgrade shardman and all the other extensions on the server.

Sometimes after running the upgrade command or some user's manual manipulations, dictionary errors may appear in the output of the status command. One of the reasons for these errors is that the value of the srvoptions field of the pg_foreign_server table differs from what the system expects. To solve this specific issue, use the config update fdw command, which will return srvoptions to the expected state.

Note

Most of the described shardmanctl commands take a global metadata lock.

Command-line Reference

This section describes shardmanctl commands. For Shardman common options used by the commands, see the section called “Common Options”.

cleanup #

Syntax:

shardmanctl [common_options] cleanup [-p|--processrepgroups] --after-node-operation|--after-rebalance

Performs cleanup after the nodes add or rebalance command.

-p node_names
--processrepgroups=node_names #

Perform an actual cleanup. By default, the tool only shows actions to be done during the actual cleanup. For more details, see the section called “Performing Cleanup”.

--after-node-operation #

Perform cleanup after a failure of a nodes add command.

--after-rebalance #

Perform cleanup after a failure of a rebalance command.

config update credentials #

Syntax:

shardmanctl [common_options] config update credentials [-u | --user] [-p | --password] [-k | --ssl-key] [-c | --ssl-cert] [-w|--wait time_duration] [--force] [-y | --yes] [--from-primary-cluster]

Updates password or certificate/key of a user to connect to a Shardman cluster. It only updates the authentication type that was specified by the user (scram-sha-256, ssl) and not the type itself.

-u
--user #

User that requires an update of the authentication parameters.

-p
--password #

New password.

-k
--ssl-key #

New SSL key.

-c
--ssl-cert #

New SSL certificate.

-w
--wait #

Sets shardmanctl to wait for configuration changes to take effect. If a new configuration cannot be loaded by all replication groups, shardmanctl will wait forever.

--force #

Perform forced update if a cluster operation is in progress.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--from-primary-cluster #

Necessary for transferring of the primary cluster configuration to a stanby cluster. If present, the following configuration parameters are ignored: StandbyMode, StandbySettings, additionalReplicationSlots, createSlotsOnFollowers, additionalSlotsLagLimit.

cluster repfactor set #

Syntax:

shardmanctl [common_options] cluster repfactor set --value new_repfactor

Sets the replication factor for the manual-topology mode.

--value=new_repfactor #

New replication factor value

cluster start #

Syntax:

shardmanctl [common_options] cluster start

Starts all PostgreSQL server instances.

cluster stop #

Syntax:

shardmanctl [common_options] cluster stop [-y|--yes]

Stops all PostgreSQL server instances.

-y
--yes #

confirm the operation instead of asking approval from the standard input.

cluster standby enable #

Syntax:

shardmanctl [common_options cluster standby enable [-y | --yes][--no-wait]

Switches the cluster to the standby mode.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--no-wait #

Do not wait for the standby keeper to start.

cluster standby disable #

Syntax:

shardmanctl [common_options cluster standby disable [-y | --yes][--no-wait]

Checks that all cluster instances are restored to the same checkpoint and then switches the cluster from the standby mode back to the main. Once the standby mode is disabled, all cluster instances read the shardman/<cluster_name>/data/last-replay-lsn/<shard_name>/<node_address> etcd key, that checks whether all instances are restored to the same syncpoint.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--no-wait #

Do not wait for the cluster to start.

Note that if there are dictionary errors after the cluster is up, you can fix it with the shardmanctl config update fdw command.

cluster standby catchup #

Syntax:

shardmanctl [common_options] cluster standby catchup
[-s|--shard shard_name]
[-n|--node node_names --soutce-datadir directory]
[--remote-port port]
[--remote-user username]
[-j|--jobs count]
[--log-directory path]
[--log-to-console]

Copies data from the primary cluster instance to the standby cluster instance if one of the standby cluster instances lags behind. It is run on the standby cluster node and uses StandbySettings from sdmspec.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

-s shard_name
--shard=shard_name #

Standby cluster shard name.

-n node_names
--node=node_names #

Specifies the comma-separated list of standby cluster nodes. Must be executed on a lagging node.

--source-datadir directory #

Specifies the absolute path to the directory with the primary cluster data.

--remote-port port #

Specifies the remote ssh port to receive data.

Default: 22.

--remote-user username #

Specifies the remote ssh user to receive data.

Default: postgres.

--jobs count
-j count #

The number of parallel threads that pg_probackup uses when creating a backup.

Default: 1.

--log-directory path #

Specifies the directory for pg_probackup catchup logs.

--log-to-console #

Enables output of pg_probackup catchup logs to the console.

cluster topology #

Syntax:

shardmanctl [common_options] cluster topology -f|--format table|json|text

Displays the cluster topology.

-f table|json|text
--format=table|json|text #

Output format. For more details, see the section called “Displaying the Cluster Topology”.

daemon check #

Syntax:

shardmanctl [common_options] daemon check -n|--nodes node_name:port

Checks shardmand on nodes.

-n node_name:port
--nodes=node_name:port #

List of nodes to check shardmand on. For more details, see the section called “Checking shardmand Service on Nodes”.

forall #

Syntax:

shardmanctl [common_options] forall --sql query[ --sql query[ --sql query ...]] [--twophase]

Executes an SQL statement on all replication groups in a Shardman cluster.

--sql query #

Specifies the statement to be executed.

--twophase #

Use the two-phase-commit protocol to execute the statement.

getconnstr #

Syntax:

shardmanctl [common_options] getconnstr --all

Gets the libpq connection string for connecting to a cluster as administrator.

--all #

Adds replicas to getconnstr.

init #

Syntax:

    shardmanctl [common_options] init [-y|--yes] [-f|--spec-file spec_file_name]|spec_text
   

Registers a new Shardman cluster in the etcd store or reinitializes the existing cluster defining a new cluster configuration and removing all data and nodes.

-f spec_file_name
--specfile=spec_file_name #

Specifies the file with the cluster specification string. The value of - means the standard input. By default, the string is passed in spec_text. For usage details, see the section called “Registering a Shardman Cluster”.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

intcheck #

Syntax:

    shardmanctl [common_options] intcheck [-s|--system] [-u|--user] [-c|--catalog] [-o|--output]  [-n|--node node]
   

Runs pg_integrity_check on all nodes of a Shardman cluster or on a selected one node.

-s
--system #

Validate checksums for read-only files. Checksums for read-only files control both file contents and file attributes.

-u
--user #

Validate checksums for additional files. Checksums for additional files control both file contents and file attributes.

-c
--catalog #

Validate checksums for system catalog tables. For the -c option to work correctly, the database server must be started and accept connections.

-o
--output #

Recalculate checksums and write them into a file

-n node_names
--node=node_names #

Only execute the pg_integrity_check command on the selected node

load #

Syntax:

     shardmanctl [common_options] load [ -b | --batch-size lines_limit] [ --destination-fields fields_list]
     [ --distributed-keys key_type_list] [ -D | --delimiter character]
     [--null_marker string] [ -e | --escape character] [ -f | --file input_file]
     [ -F | --format text|csv ] [ -j | --jobs task_total] [ -q | --quote character]
     [ --reject-file filename] [ --schema filename] [ --source file|postgres]
     [ --source-connstr connect_string] [ --source-fields fields_list] [ --source-table source_table]
     [ -t | --table destination_table]
   

Loads data to a Shardman cluster.

-b lines_limit
--batch-size=lines_limit #

Number of rows per batch to write to the Shardman cluster.

Default: 1000.

--destination-fields=fields_list #

Comma-separated list of target table fields. If the value is not set, then all fields of the table are used in the order they are declared.

--distributed-keys=key_type_list #

Comma-separated list of pairs. Each pair consists of a field number (starting with zero) and a type, which are separated by a colon. The following types are supported: bool, char, float4, float8, int2, int4, int8, name, text, varchar and uuid.

-D character
--delimiter=character #

Specifies the character that separates columns within each row (line) of the file. This must be a single one-byte character.

Default: tab for text format, comma for CSV format

--null_marker=string #

Specifies the string that represents a null value.

Default: \N for text format, unquoted empty string for CSV format.

-e character
--escape=character #

Specifies the character that should appear before a data character that matches the QUOTE value. The default is the same as the QUOTE value (so that the quoting character is doubled if it appears in the data). This must be a single one-byte character. This option is allowed only when using CSV format.

-f filename
--file=filename #

Input data filename (or - for stdin)

-F text|csv
--format=text|csv #

Input data format. Possible values are text and csv.

Default: text.

-j number
--jobs=number #

Number of parallel processes to load data.

Default: number of replication groups.

-q character
--quote=character #

Specifies the quoting character to be used when a data value is quoted. The default is double-quote. This must be a single one-byte character. This option is allowed only when using CSV format.

--reject-file=filename #

All data batches with errors during upload will be written to this file. If the value is not set, then such batches will be skipped.

--schema=filename #

The schema that defines the rules for transferring data from PostgreSQL to Shardman. If this option is set, then all other options are not used.

--source=file|postgres #

Data source type — file or postgres.

Default: file.

--source-connstr=string #

Data source database connection string

--source-fields=fields_list #

Comma-separated list of source table fields. If the value is not set, then all fields of the table are used in the order they are declared.

--source-table=table #

Source table, view or function (funcname(param1,...,paramN)).

-t table
--table=table #

Destination table.

nodes add #

Syntax:

shardmanctl [common_options] nodes add -n|--nodes node_names [--no-rebalance]

Adds nodes to a Shardman cluster.

-n node_names
--nodes=node_names #

Required.

Specifies the comma-separated list of nodes to be added.

--no-rebalance #

Skip the step of rebalancing partitions of sharded tables. For more details, see the section called “Adding Nodes to a Shardman Cluster”.

nodes rm #

Syntax:

shardmanctl [common_options] nodes rm -n|--nodes node_names

Removes nodes from a Shardman cluster.

-n node_names
--nodes=node_names #

Specifies the comma-separated list of nodes to be removed. For usage details, see the section called “Removing Nodes from a Shardman cluster”.

probackup #

Syntax:

shardmanctl [common_options] probackup
       [init|archive-command|backup|checkdb|delete|merge|restore|set-config|show|validate|show-config]
       [--log-to-console][--help]
       [subcommand_options]

Creates a backup of a Shardman cluster and restores the Shardman cluster from a backup using pg_probackup.

List of subcommands: #

init #

Initializes a new repository folder for the Shardman cluster backup and creates a configuration file on all nodes for connection to the backup storage if --storage-type is S3.

archive-command #

Adds archive_command to each replication group (or to a single one if the --shard option is specified) and enables or disables it in the Shardman cluster.

backup #

Creates a backup of the Shardman cluster.

checkdb #

Verifies the Shardman cluster correctness by detecting physical and logical corruption.

delete #

Deletes a backup of the Shardman cluster with the specified backup_id.

merge #

Merges the backups that belong to a common incremental backup chain. The full backup merges the backups with their first incremental backup. The incremental backup merges the backups with their parent full backup, along with all the incremental backups between them. Once the merge is complete, the full backup covers all the merged data, and the incremental backups are removed as redundant. In this version, you cannot run the merge command using the S3 interface.

restore #

Restores the Shardman cluster from the selected backup.

show #

Shows the list of backups of the Shardman cluster.

validate #

Checks the selected Shardman cluster backup for integrity.

show-config #

Displays all the current pg_probackup configuration settings, including those that are specified in the pg_probackup.conf configuration file located in the backup_dir/backups/shard_name directory and those that were provided on a command line.

set-config #

Adds the specified settings to the pg_probackup.conf or modifies those previously added.

The following options can be used with all probackup subcommands:

--log-to-console #

Outputs a full probackup log to the console. By default, for each replication group the probackup log file is written to the backup directory (see --backup-path below) as the <backup-directory>/backup/log/pg_probackup-<repgroup-name>.log file. The log rotation file size is 20MB. If this value is reached, the log file is rotated once a shardmanctl probackup validate or shardmanctl probackup backup command is launched.

--help #

Shows subcommand help.

init #

Syntax:

shardmanctl [common_options] probackup init
-B|--backup-path path
-E|--etcd-path path
[--remote-port port]
[--remote-user username]
[--ssh-key path]
[-t|--timeout seconds]
[-m|--maxtasks number_of_tasks]
[--storage-type mount|remote|S3]
[--s3-config-only]
[--s3-config-path path]
[--s3-host S3_host]
[--s3-port S3_port]
[--s3-access-key S3_access_key]
[--s3-secret-key S3_secret_key]
[--s3-bucket S3_bucket]
[--s3-region S3_region]
[--s3-buffer-size size]
[--s3-retries number_of_retries]
[--s3-timeout time]
[--s3-https]
[-y|--yes]

Initializes a new repository folder for the Shardman cluster backup.

-B path
--backup-path path #

Required if --s3-config-only is not used. Specifies the path to the backup catalog where Shardman cluster backups should be stored.

-E path
--etcd-path path #

Required if --s3-config-only is not used. Specifies the path to the catalog where the etcd dumps should be stored.

--remote-port port #

Specifies the remote ssh port for replication group instances.

Default: 22.

--remote-user username #

Specifies the remote ssh user for replication group instances.

Default: postgres.

--ssh-key path #

Specifies the ssh private key for execution of remote ssh commands.

Default: $HOME/.ssh/id_rsa.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively.

Default: remote.

--s3-config-path path #

Specifies the path where the S3 configuration file will be created on all Shardman nodes.

Default: <shardman-data-dir>/s3.config.

--s3-config-only #

Create only S3 configuration files on all nodes and skip backup repository initialization. This flag is useful if the value of --storage-type is S3.

--s3-host host #

Specifies the S3 host to connect to S3-compatible storage.

--s3-port port #

Specifies the S3 port to connect to S3-compatible storage.

--s3-access-key access-key #

Specifies the S3 access key to connect to S3-compatible storage.

--s3-secret-key access-key #

Specifies the S3 secret key to connect to the S3-compatible storage.

--s3-bucket bucket #

Specifies the bucket in the S3-compatible object storage for storing backups.

--s3-region bucket #

Specifies the region in the S3-compatible object storage.

--s3-buffer-size size #

Size of the read/write buffer for pg_probackup to communicate with the S3-compatible object storage, in MiB.

Default: 16.

--s3-retries number_of_retries #

Maximum number of attempts for pg_probackup to execute an S3 request in case of failures.

Default: 5.

--s3-timeout time #

Maximum allowable amount of time for pg_probackup to transfer data of size --s3-buffer-size to/from the S3-compatible object storage, in seconds.

Default: 300.

--s3-https #

Specifies the HTTPS URL to connect to the S3-compatible object storage.

-y|--yes #

Approve the operation regardless of whether the file specified in --s3-config-path exists.

archive-command #

Syntax:

shardmanctl [common_options] probackup archive-command [add|rm]
        -B|--backup-path path
        [-j|--jobs count]
        [--compress]
        [--compress-algorithm algorithm]
        [--compress-level level]
        [--batch-size batch_size]
        [--storage-type mount|remote|S3]
        [--remote-port port]
        [--remote-user username]
        [-s|--shard shard-name]
        [--s3-config-path path]
        [-y|--yes]
    

Adds/removes and enables/disables the archive command for every replication group in the Shardman cluster to put WAL logs into the initialized backup repository.

add #

Adds and enables the archive command for every replication group in the Shardman cluster.

rm #

Disables the archive command in every replication group in the Shardman cluster. No additional options are required.

-B path
--backup-path path #

Required when adding archive_command. Specifies the path to the backup catalog where the Shardman cluster backups should be stored.

--batch-size batch_size #

To speed up the archiving, specify the --batch-size option to copy the WAL segments in batches of a specified size. If the --batch-size option is used, it is also possible to specify the -j option to copy a batch of the WAL segments on multiple threads.

--jobs count
-j count #

The number of parallel threads that pg_probackup uses when creating a backup. Default: 1.

--compress #

If this flag is not specified, compression will be disabled. If the flag is specified, the default zstd algorithm is used with the compression level set to 1, while other compression options are ignored even if they are specified.

--compress-algorithm algorithm #

Defines the compression algorithm: zlib, lz4, zstd, pglz, or none. Once defined, it checks if the values are valid within the scale of the defined algorithm.

The supported compression algorithms depend on the version of Postgres Pro Enterprise that includes the pg_probackup used, as explained in Compression Options.

Default: none.

--compress-level level #

Defines the compression level — 0-9 for zlib, 1 for pglz, 0-22 for zstd, and 0-12 for lz4.

Default: 1.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively.

Default: remote.

--remote-port port #

Specifies the remote ssh port for replication group instances.

Default: 22.

--remote-user username #

Specifies the remote ssh user for replication group instances.

Default: postgres.

-s|--shard shard-name #

Specifies the name of the shard where the archive command must be added, enabled or disabled. If not specified, the archive command is enabled or disabled for every shard.

--s3-config-path path #

Specifies the path to the S3 configuration file.

Default: <shardman-data-dir>/s3.config.

-y
--yes #

Confirm the restart instead of asking approval from the standard input. Only applies for the add command.

backup #

Syntax:

shardmanctl [common_options] probackup backup -B|--backup-path path
        -E|--etcd-path path
        -b|--backup-mode MODE
        [-j|--jobs count]
        [--compress-algorithm algorithm]
        [--compress-level level]
        [--batch-size batch_size]
        [--storage-type mount|remote|S3]
        [--remote-port port]
        [--remote-user username]
        [--ssh-key path]
        [-t|--timeout seconds]
        [-m|--maxtasks number_of_tasks]
        [--log-directory path]
        [--s3-config-path path]
        [--no-validate]
        [--skip-block-validation]
        [--log-to-console]
        [--retention-redundancy]
        [--retention-window]
        [--wal-depth]
        [--delete-wal]
        [--delete-expired]
        [--merge-expired]
        [-y | --yes]
        [--lock-lifetime]
    

Creates a backup of the Shardman cluster.

-B path
--backup-path path #

Required. Specifies the path to the backup catalog where Shardman cluster backups should be stored.

-E path
--etcd-path path #

Required. Specifies the path to the catalog where the etcd dumps should be stored.

-b MODE
--backup-mode MODE #

Required. Defines the backup mode: FULL, PAGE, DELTA, PTRACK.

--batch-size batch_size #

To speed up the archiving, specify the --batch-size option to copy the WAL segments in batches of a specified size. If the --batch-size option is used, it is also possible to specify the -j option to copy a batch of the WAL segments on multiple threads.

--jobs count
-j count #

The number of parallel threads that pg_probackup uses when creating a backup. Default: 1.

--compress-algorithm algorithm #

Defines the compression algorithm: zlib, lz4, zstd, pglz, or none.

The supported compression algorithms depend on the version of Postgres Pro Enterprise that includes the pg_probackup used, as explained in Compression Options.

Default: none.

--compress-level level #

Defines the compression level — 0-9 for zlib, 1 for pglz, 0-22 for zstd, and 0-12 for lz4.

Default: 1.

--remote-port port #

Specifies the remote ssh port for replication group instances.

Default: 22.

--remote-user username #

Specifies the remote ssh user for replication group instances.

Default: postgres.

--ssh-key path #

Specifies the ssh private key for execution of remote ssh commands.

Default: $HOME/.ssh/id_rsa.

-t seconds
--timeout seconds #

Exit with error after waiting until the cluster is ready for the specified number of seconds.

-m number_of_tasks
--maxtasks number_of_tasks #

Specifies the maximum number of concurrent tasks (pg_probackup commands) to run.

Default: number of logical CPUs of the system.

--no-validate #

Skip automatic validation after the backup is taken. You can use this flag if you validate backups regularly and would like to save time when running backup operations.

Default: false.

--skip-block-validation #

Disables block-level checksum verification to speed up the backup process.

Default: false.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively.

Default: remote.

--log-to-console #

Enables output of the pg_probackup logs to the console.

Default: false.

--log-directory path #

Specifies the directory for pg_probackup logs. Required if --storage-type is set to S3 unless the SDM_LOG_DIRECTORY environment variable is set.

Default: <backup-directory>/backup/log.

--s3-config-path path #

Specifies the path to the S3 configuration file.

Default: <shardman-data-dir>/s3.config.

--retention-redundancy=redundancy
#

Specifies the number of full backup copies to keep in the data directory. Must be a non-negative integer. The zero value disables this setting.

Default: current value of the pg_probackup.conf file, 0 if not specified.

--retention-window=window
#

Number of days of recoverability. Must be a non-negative integer. The zero value disables this setting.

Default: current value of the pg_probackup.conf file, 0 if not specified.

--wal-depth=wal_depth #

Number of latest valid backups on every timeline that must retain the ability to perform PITR. Must be a non-negative integer. The zero value disables this setting.

Default: current value of the pg_probackup.conf file, 0 if not specified.

--delete-wal #

Deletes WAL files that are no longer required to restore the cluster from any of the existing backups.

Default: false.

--delete-expired #

Deletes backups that do not conform to the retention policy.

Default: false.

--merge-expired
#

Merges the oldest incremental backup that satisfies the requirements of retention policy with its parent backups that have already expired.

Default: false.

-y
--yes #

Confirm the restart instead of asking approval from the standard input.

--lock-lifetime #

Allows setting the maximum time that probackup can hold the lock, in seconds.

Default: 1800.

checkdb #

Syntax:

shardmanctl [common_options] probackup checkdb
[--amcheck [--skip-block-validation] [--heapallindexed]] [--shard shard]
[-m|--maxtasks number_of_tasks]

Verifies the Shardman cluster correctness by detecting physical and logical corruption.

--amcheck #

Performs logical verification of indexes if no corruption was found while checking data files. You must have the amcheck extension or the amcheck_next extension installed in the database to check its indexes. For databases without amcheck, index verification will be skipped. The amcheck extension is included with the Shardman package.

--heapallindexed #

Checks that all heap tuples that should be indexed are actually indexed. You can use this flag only together with the --amcheck flag. This option is effective depending on the version of amcheck/amcheck_next installed. The amcheck extension included in the Shardman package supports this verification.

--skip-block-validation #

Skip validation of data files. You can use this flag only together with the --amcheck flag, so that only logical verification of indexes is performed.

--shard shard #

Perform the verification only on the specified shard. By default, the verification is performed on all shards.

-m number_of_tasks
--maxtasks number_of_tasks #

Specifies the maximum number of concurrent tasks (pg_probackup commands) to run.

Default: number of logical CPUs of the system.

delete #

Syntax:

shardmanctl [common_options] probackup delete -B|--backup-path path
        [-i|--backup-id backup_id]
        [-j|--jobs count]
        [-m|--maxtasks number_of_tasks]
        [--storage-type mount|remote|S3]
        [--s3-config-path path]
        [--delete-wal]
        [-y|--yes]
        [--retention-redundancy]
        [--retention-window]
        [--wal-depth]
        [--delete-expired]
        [--merge-expired]

Deletes a backup of the Shardman cluster with specified backup_id or launches the retention purge of backups and archived WAL that do not satisfy the current retention policies.

Note that backup_id cannot be used with merge-expired or delete-expired.

-B path
--backup-path path #

Required. Specifies the path to the backup catalog (or key in the bucket of the S3-compatible storage) where Shardman cluster backups should be stored.

-i backup_id
--backup-id backup_id #

Specifies the unique identifier of the backup.

--jobs count
-j count #

The number of parallel threads that pg_probackup uses when creating a backup. Default: 1.

-m number_of_tasks
--maxtasks number_of_tasks #

Specifies the maximum number of concurrent tasks (pg_probackup commands) to run.

Default: number of logical CPUs of the system.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively.

Default: remote.

To delete the backup that was created with a --storage-type option with a S3 value, set a --storage-type option to a S3 value in the delete command.

--s3-config-path path #

Specifies the path to the S3 configuration file.

Default: <shardman-data-dir>/s3.config.

--delete-wal #

Deletes WAL files that are no longer required to restore the cluster from any of the existing backups.

Default: false.

-y
--yes #

Approve operation.

Default: false.

--retention-redundancy=redundancy
#

Specifies the number of full backup copies to keep in the data directory. Must be a non-negative integer. The zero value disables this setting.

Default: current value of the pg_probackup.conf file, 0 if not specified.

--retention-window=window
#

Number of days of recoverability. Must be a non-negative integer. The zero value disables this setting.

Default: current value of the pg_probackup.conf file, 0 if not specified.

--wal-depth=wal_depth #

Number of latest valid backups on every timeline that must retain the ability to perform PITR. Must be a non-negative integer. The zero value disables this setting.

Default: current value of the pg_probackup.conf file, 0 if not specified.

--delete-expired #

Deletes backups that do not conform to the retention policy.

Default: false.

--merge-expired
#

Merges the oldest incremental backup that satisfies the requirements of retention policy with its parent backups that have already expired.

Default: false.

merge #

Syntax:

shardmanctl [common_options] probackup merge -B|--backup-path path
        -i|--backup-id backup_id
        [-j|--jobs count]
        [-m|--maxtasks number_of_tasks]
        [--no-validate]
        [--no-sync]
        [-y|--yes]

Merges the backups that belong to a common incremental backup chain. The full backup merges the backups with their first incremental backup. The incremental backup merges the backups with their parent full backup, along with all the incremental backups between them. Once the merge is complete, the full backup covers all the merged data, and the incremental backups are removed as redundant.

-B path
--backup-path path #

Required. Specifies the path to the backup catalog where Shardman cluster backups should be stored.

-i backup_id
--backup-id backup_id #

Required. Specifies the unique identifier of the backup.

--jobs count
-j count #

The number of parallel threads that pg_probackup uses when creating a backup. Default: 1.

-m number_of_tasks
--maxtasks number_of_tasks #

Specifies the maximum number of concurrent tasks (pg_probackup commands) to run.

Default: number of logical CPUs of the system.

--no-sync #

Do not sync merged files to disk. You can use this flag to speed up the merge process. Using this flag can result in data corruption in case of operating system or hardware crash.

Default: false.

--no-validate #

Skip automatic validation before and after merge.

Default: false.

-y
--yes #

Approve the operation.

Default: false.

restore #

Syntax:

shardmanctl [common_options] probackup restore
        -B|--backup-path path
        -i|--backup-id id
        -j|--jobs count
        [--recovery-target-time timestamp]
        [-I|--recovery-mode incremental_mode]
        [-t|--timeout seconds]
        [-m|--maxtasks number_of_tasks]
        [--metadata-only] [--schema-only] [--shard shard]
        [--no-validate]
        [--skip-block-validation]
        [--s3-config-path path]
        [--storage-type mount|remote|S3]
        [--wal-limit number_of_wal_segments]
        [--log-directory path]
        [--data-validate]
    

Restores a Shardman cluster from the selected backup.

-B path
--backup-path path #

Required. Specifies the path to the backup catalog where Shardman cluster backups should be stored. Can be used to deploy a stanby cluster from the primary cluster backup by specifying the cluster backup path from the data center.

-i id
--backup-id id #

Required. Specifies backup ID for restore.

--jobs count
-j count #

The number of parallel threads that pg_probackup uses when restoring from a backup. Default: 1.

--recovery-target-time timestamp #

Point-in-Time Recovery (PITR) option. Specifies the timestamp for restore. Example: '2024-01-25 15:30:36' in UTC.

-I incremental_mode
--recovery-mode incremental_mode #

Specifies the incremental restore mode to be used. Possible values are:

  • checksum — replace only pages with mismatched checksum and LSN.

  • lsn — replace only pages with LSN greater than point of divergence.

  • none — regular restore, default.

-t seconds
--timeout seconds #

Exit with error after waiting until the cluster is ready or the recovery is complete for the specified number of seconds.

--metadata-only #

Perform metadata-only restore. By default, full restore is performed.

--schema-only #

Perform schema-only restore. By default, full restore is performed.

--shard shard #

Perform restoring only on the specified shard. By default, restoring is performed on all shards.

--no-validate #

Skip backup validation. You can use this flag if you validate backups regularly and would like to save time when running restore operations.

Default: false.

--skip-block-validation #

Disable block-level checksum verification to speed up validation. During automatic validation before the restore only file-level checksums will be verified.

Default: false.

--s3-config-path path #

Specifies the path to the S3 configuration file.

Default: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively. When creating backup with a --storage-type option with a S3 value, set --storage-type option to a S3 value in the restore command.

Default: remote.

--wal-limit number_of_wal_segments #

Specifies the number of WAL segments in which the closest synchronization points will be searched in the case of PITR.

Default: 0 — no limit.

--log-directory path #

Specifies the directory for pg_probackup logs. Required if --storage-type is set to S3 unless the SDM_LOG_DIRECTORY environment variable is set.

Default: <backup-directory>/backup/log.

--data-validate #

If enabled, verifies data with probackup validate before restoring.

Default: false.

show #

Syntax:

shardmanctl [common_options] probackup show
        -B|--backup-path path
        [-f|--format table|json]
        [--archive ]
        [-i|--backup-id backup-id]
        [--instance instance]
        [--storage-type mount|remote|S3]
        [--s3-config-path path]
    

Shows the list of backups of the Shardman cluster.

-B path
--backup-path path #

Required. Specifies the path to the backup catalog where Shardman cluster backups should be stored.

-f table|json
--format table|json #

Specifies the output format.

Default: table.

--archive #

Shows the WAL archive information.

-i backup-id
--backup-idbackup-id #

Shows information about the specific backups.

--instanceinstance #

Shows information about the specific instance.

--s3-config-path path #

Specifies the path to the S3 configuration file.

Default: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively. To show a backup that was created with the S3 value of --storage-type, set --storage-type to S3 in the show command.

Default: remote.

show-config #

Syntax:

shardmanctl [common_options] probackup show-config
    -B backup_path
    [--format=text|json]
    [--no-scale-units]
    -s|--shard shard_name
    [--s3-config-path path]
    [--storage-type mount|remote|S3]

Displays all the current pg_probackup configuration settings, including those that are specified in the pg_probackup.conf configuration file located in the backup_dir/backups/shard_name directory and those that were provided on a command line.

-B string
--backup-path=string #

Required. Specifies the absolute path to the backup catalog.

--format text|json #

Specifies the output format.

Default: text.

--no-scale-units #

Output the configuration parameter values for the time and the amount of memory in the default units.

Default: false.

-s string
--shard=string #

A name of the shard to execute the show-config command for.

--s3-config-path path #

Specifies the path where the S3 configuration file will be created on all Shardman nodes.

Default: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively.

Default: remote.

validate #

Syntax:

shardmanctl [common_options] probackup validate
        -B|--backup-path path
        -i|--backup-id id
        [-t|--timeout seconds]
        [-m|--maxtasks number_of_tasks]
        [--log-to-console]
        [--storage-type mount|remote|S3]
        [--s3-config-path path]
        [--log-directory path]
        [--remote-port port]
        [--remote-user username]
    

Checks the selected Shardman cluster backup for integrity.

-B path
--backup-path path #

Required. Specifies the path to the backup catalog where Shardman cluster backups should be stored.

-i id
--backup-id id #

Required. Specifies backup ID for validation.

--log-to-console #

Enables output of pg_probackup logs to the console.

Default: false.

-t seconds
--timeout seconds #

Exit with error after waiting until the cluster is ready for the specified number of seconds.

-m number_of_tasks
--maxtasks number_of_tasks #

Specifies the maximum number of concurrent tasks (pg_probackup commands) to run.

Default: number of logical CPUs of the system.

--s3-config-path path #

Specifies the path to the S3 configuration file.

Default: <shardman-data-dir>/s3.config.

--storage-type mount|remote|S3 #

Type of the backup storage. If the value is remote, SSH is used to copy data files to the remote backup directory. But this behavior is different if a directory mounted to all nodes or an S3-compatible object storage is used to store backups. To specify these kinds of storage, the value of the --storage-type option is set to mount or S3, respectively. To validate a backup that was created with the S3 value of --storage-type, set --storage-type to S3 in the validate command.

Default: remote.

--log-directory path #

Specifies the directory for pg_probackup logs. Required if --storage-type is set to S3 unless the SDM_LOG_DIRECTORY environment variable is set.

Default: <backup-directory>/backup/log.

--remote-port port #

Specifies the remote ssh port for replication group instances.

Default: 22.

--remote-user username #

Specifies the remote ssh user for replication group instances.

Default: postgres.

--ssh-key path #

Specifies the ssh private key for execution of remote ssh commands.

Default: $HOME/.ssh/id_rsa.

set-config #

Syntax:

shardmanctl [common_options] probackup set-config
        [--archive-timeout int]
        [-B | --backup-path string]
        [-m |--maxtasks int]
        [--remote-port int]
        [--remote-user string]
        [--retention-redundancy int]
        [--retention-window int]
        [--wal-depth int]
        [--s3-config-path string]
        [-s |--shard string]
        [--storage-type string]

Adds the specified settings to the pg_probackup.conf or modifies those previously added.

--archive-timeout int #

Sets a timeout for the WAL segment archiving and streaming, in seconds.

Default: pg_probackup waits for 300 seconds.

-B string
--backup-path=string #

Specifies the absolute path to the backup catalog.

-m int
--maxtasks=int #

Specifies the maximum number of concurrent tasks (pg_probackup commands) to run.

Default: number of logical CPUs of the system.

--remote-port int #

An SSH remote backup port.

Default: 22.

--remote-user string #

An SSH remote backup user.

--retention-redundancy int #

Specifies the number of the full backup copies to store in the data directory. It must be set to a non-negative integer. The zero value disables this setting.

Default: 0.

--retention-window int #

A number of days of recoverability. It must be set to a non-negative integer. The zero value disables this setting.

Default: 0.

--wal-depth int #

A number of the latest valid backups on every timeline that must retain the ability to perform PITR. Must be set to a non-negative integer. The zero value disables this setting.

--s3-config-path string #

A path to the S3 configuration file.

Default: /var/lib/pgpro/sdm-14/data/s3.config

-s string
--shard=string #

A name of the shard to make the set-config command for. If not specified, the command is run for all the shards.

Default: current value of the pg_probackup.conf file.

--storage-type string #

A backup storage type, the possible values are remote, mount, S3.

Default: remote.

rebalance

Syntax:

shardmanctl [common_options] rebalance [-f|--force]

Rebalances sharded tables.

-f
--force #

Perform forced rebalance of sharded tables whose partitions were manually moved.

restart #

Syntax:

     shardmanctl [common_options] restart [-y|--yes] [--no-wait]
   

Restarts a Shardman cluster.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--no-wait #

Do not wait for the replicas to start.

restart rolling #

Syntax:

     shardmanctl [common_options] restart rolling [-y|--yes] [--restore-masters] [--upgrade]
   

Consecutively restarts a Shardman cluster with minimum downtime. It restarts shardmand, consecutively restarts all standbys, switches the primary to one of the standbys, and restarts the former primary instance.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--restore-masters #

Return the primary roles to the instances that were primaries before the command.

--upgrade #

Run shardmanctl upgrade once all instances restarted.

shard add #

Syntax:

shardmanctl [common_options] shard -s|--shard shard_name add -n|--nodes node_names [--no-wait]

Adds a replica to a shard.

-s shard_name
--shard=shard_name #

Shard name.

-n node_names
--nodes=node_names #

Specifies the comma-separated list of replica nodes to be added.

--no-wait #

Do not wait for the shard to start.

shard master set #

Syntax:

shardmanctl [common_options] shard -s|--shard shard_name master set [--yes | -y] [-n| node node_names]

Sets the precedence for a certain primary server for a specified shard.

-s shard_name
--shard=shard_name #

Shard name.

master set #

Primary server with precedence.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

-n node_names
--nodes=node_names #

Specifies the comma-separated list of replica nodes.

shard master reset #

Syntax:

shardmanctl [common_options] shard -s|--shard shard_name master reset [--yes | -y] -n| node node_names

Resets the parameters of the master with precedence for the shard.

-s shard_name
--shard=shard_name #

Shard name.

master reset #

Resets the parameters of the master with precedence for the shard.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

-n node_names
--nodes=node_names #

Specifies the comma-separated list of replica nodes.

shard add #

Syntax:

shardmanctl [common_options] shard -s|--shard shard_name reset [--yes | -y][--new-primary | -p]

Resets nodes of a replication group if they are in a state of hanging.

-s shard_name
--shard=shard_name #

Shard name.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--new-primary
-p #

New primary node host.

shard rm #

Syntax:

     shardmanctl [common_options] shard -s|--shard shard_name rm -n|--nodes node_names [-f|--force]
   

Removes a replica from a shard.

-s shard_name
--shard=shard_name #

Shard name

-n node_names
--nodes=node_names #

Specifies the comma-separated list of replica nodes to be removed.

-f
--force #

Perform forced removal of the node, even if it is dead.

shard switch #

Syntax:

     shardmanctl [common_options] shard -s|--shard shard_name switch [--new-primary node_names]
   

Switches the primary node. When this command is running, the user is prompted to set the current node as primary to avoid switching back.

-s shard_name
--shard=shard_name #

Shard name.

--new-primary=node_names #

New primary node host.

shard start #

Syntax:

     shardmanctl [common_options] shard -s |--shard shard_name start [--no-wait] [-n|--node node_name]
   

Starts the shard.

-s shard_name
--shard=shard_name #

Shard name.

--no-wait #

Do not wait for the shard to start.

-n node_name
--node=node_name #

Specifies the node to start.

shard stop #

Syntax:

     shardmanctl [common_options] shard -s |--shard shard_name stop [-n|--node node_name]
   

Stops the shard.

-s shard_name
--shard=shard_name #

Shard name.

-n node_name
--node=node_name #

Specifies the node to stop.

shard replicas reinit #

Syntax:

     shardmanctl [common_options] shard -s|--shard shard_name replicas reinit [-n|--node node_names] [-y|--yes] [--no-wait]

Resets replicas of a specific shard.

-s shard_name
--shard=shard_name #

Shard name.

-n node_names
--node=node_names #

Specifies the node on which to reset replicas. If not specified, checks shard replicas on all nodes.

-y
--yes #

Confirm the operation instead of asking approval from the standard input.

--no-wait #

Do not wait wait for replicas to become ready.

For more details, see the section called “Reinitializing Replicas”

nodes start #

Syntax:

     shardmanctl [common_options] nodes start -n|--nodes node_names [--no-wait]
   

Starts the nodes.

-n node_names
--nodes=node_names

Node names.

--no-wait

Sets shardmanctl not to wait for the nodes to start.

nodes restart #

Syntax:

     shardmanctl [common_options] nodes restart -n|--nodes node_names [--no-wait]
   

Restarts the nodes.

-n node_names
--nodes=node_names

Node names.

--no-wait

Do not wait for the nodes to restart.

nodes stop #

Syntax:

     shardmanctl [common_options] nodes stop -n|--nodes node_names [--no-wait]
   

Stops the nodes.

-n node_names
--nodes=node_names

Node names.

--no-wait

Do not wait for the nodes to stop.

status #

Syntax:

     shardmanctl [common_options] status [-f|--format table|json] [--filter store|metadata|shardmand|rg|master|dictionary|all|restart_required_params] [-s|--sort node|rg|status]
   

Reports on the health status of Shardman cluster subsystems.

-f table|json
--format=table|json #

Specifies the report format.

Default: table.

For more details, see the section called “Getting the Status of Cluster Subsystems”.

--filter store|metadata|shardmand|rg|master|dictionary|allrestart_required_params #

Specifies subsystems whose status information should be included in the output.

Default: all.

For more details, see the section called “Getting the Status of Cluster Subsystems”.

-s node|rg|status
--sort node|rg|status #

Sort messages inside one group (table) as specified.

Default: node.

For more details, see the section called “Getting the Status of Cluster Subsystems”.

status transactions #

Syntax:

     shardmanctl [common_options] status transactions [-r|--repgroup replication_group_name
     

Shows distributed transactions that Shardman built-in monitoring tools failed to resolve.

-r replication_group_name
--repgroup=replication_group_name #

Specifies the replication group for which to output transactions.

Default: all replication groups.

For more details, see the section called “Outputting the List of Unresolved Distributed Transactions”.

store dump #

Syntax:

     shardmanctl [common_options] store dump [-f|--file filename]
   

Dumps current cluster specifications from the store.

-f filename
--file=filename #

Specifies the output file (- for stdout).

Default: -.

For more details, see the section called “Dumping All Keys from the Store to Debug Error Configuration”.

store restore #

Syntax:

     shardmanctl [common_options] store restore [--delete-old-keys][-f|--file filename][-y|--yes]
   

Allows to safely restore the etcd cluster from the dump. To do this, shardmand must be disabled on every shard. Also, it only works for the cold backup.

--delete-old-keys #

Clean all the etcd keys before restoring.

-f filename
--file=filename #

Specifies the name of the etcd keys dump.

-y
--yes #

Perform automatic confirmation.

store lock #

Syntax:

     shardmanctl [common_options] store lock [-f|--format text|json]
   

Shows the current cluster meta lock information.

-f=text|json
--format=text|json #

Specifies the output format.

Default: text.

For more details, see the section called “Output Current Cluster Meta Lock Information”.

store get #

Syntax:

    shardmanctl [common_options] store get [[-a|--alias aliasname]|[-k|--key keyname] [-f|--file filename]]
   

Gets the specified key from the store.

-a aliasname
--alias=ladle|cluster |spec|stolonspec #

Specifies the use of alias instead of the full key name. Cannot be used with --key.

For more details, see the section called “Getting the Current stolon Specification”.

-k keyname
--key=keyname #

Specifies the key to retrieve from the store. Cannot be used with --alias.

For more details, see the section called “Getting the Current stolon Specification”.

-f filename
--file=filename #

Specifies the file to print the value to.

Default: - (stdout).

For more details, see the section called “Getting the Current stolon Specification”.

store keys #

Syntax:

    shardmanctl [common_options] store keys
   

Gets all keys with the current cluster prefix from the store.

For more details, see the section called “Getting the Cluster and Ladle Key Names For the Current Cluster”.

store set #

Syntax:

    shardmanctl [common_options] store set [[-a|--alias aliasname]|[-k|--key keyname]] [-f|--file filename]
   

Creates or rewrites a key in the store.

-a ladle|cluster |spec|stolonspec
--alias=ladle|cluster |spec|stolonspec #

Specifies the use of alias instead of the full key name. Cannot be used with --key.

-k keyname
--key=keyname #

Specifies the key name to set in the store. Cannot be used with --alias.

-f filename
--file=filename #

Specifies the file with input data (- for stdin).

For more details, see the section called “Setting a New Spec for the Cluster”.

tables sharded info #

Syntax:

    shardmanctl [common_options] tables sharded info [-t|--table table_name]
   

Gets information about a sharded table.

-t table
--table=table #

Specifies the name of the table in the format schema.table

tables sharded list #

Syntax:

    shardmanctl [common_options] tables sharded list
   

Gets the list of all sharded tables.

tables sharded norebalance #

Syntax:

    shardmanctl [common_options] tables sharded norebalance
   

Gets the list of sharded tables with automatic rebalancing disabled.

tables sharded partmove #

Syntax:

    shardmanctl [common_options] tables sharded partmove [-t|--table table_name] [-s|--shard shard_name] [-p|--partnum number]
   

Moves the specified partition of a sharded table to a new shard.

-t table
--table=table #

Specifies the name of the table in the format schema.table.

-p number
--partnum=number #

Specifies the number of the partition to move.

-s shard_name
--shard=shard_name #

Specifies the name of the new shard for the partition.

tables sharded rebalance #

Syntax:

    shardmanctl [common_options] tables sharded rebalance [-t|--table table_name]
   

Enables and runs automatic data rebalancing for the selected sharded table.

-t table
--table=table #

Specifies the name of the table in the format schema.table.

config get #

Syntax:

shardmanctl [common_options] config get [-c | --choose-revision] [-r | --revision ] [-f | --file]

Outputs the current full cluster specification or a configuration of the specified revision.

-c
--choose-revision #

Enables an interactive mode of choosing a configuration of the specified revision.

-r
--revision #

ID of a configuration revision.

-f file_name
--file=file_name #

Name of a file for writing the configuration. If not specified, the value is stdout.

config revisions rm #

Syntax:

shardmanctl [common_options] config revisions rm [-r | --revision ] [-y | --yes]

Deletes a specified configuration revision from history.

-r
--revision #

ID of a configuration revision. If not specified, enables an interactive mode of choosing a configuration of the specified revision. This is a timestamp of an operation that resulted in Shardman configuration change.

-y
--yes #

Perform automatic confirmation.

config update #

Syntax:

shardmanctl [common_options] config update [[-f|--file stolon_spec_file|shardman_spec_file]|spec_text [-p|--patch][-w|--wait]] [--force] [-y | --yes] [--from-primary-cluster]

Updates the stolon or full Shardman configuration.

-f stolon_spec_file|shardman_spec_file
--specfile=stolon_spec_file|shardman_spec_file #

Specifies the file with the stolon or full Shardman configuration. The configuration file type is determined automatically. The value of - means the standard input. By default, the configuration is passed in spec_text.

-w
--wait #

Sets shardmanctl to wait for configuration changes to take effect. If a new configuration cannot be loaded by all replication groups, shardmanctl will wait forever.

-p
--patch #

Merge the new configuration into the existing one. By default, the new configuration replaces the existing one.

--force #

Perform forced update if a cluster operation is in progress.

-y
--yes #

Confirm the restart necessary for the parameters to take effect. If this option is not specified, and the parameters update requires a restart, the manual confirmation will be requested. If not confirmed, the cluster will continue to work, yet the new parameter values will only take effect after the restart.

config rollback #

Syntax:

shardmanctl [common_options] config rollback [-r | --revision] [-w|--wait time_duration] [--force] [-y|--yes]

Makes a rollback of Shardman to one of the previous states. When rolling back to the config revision that has max_connections, max_prepared_transactions, or max_worker_processes parameters, the replicas are reinitialized.

-r
--revision #

ID of a revision the rollback must be made to. It is a timestamp of an operation that resulted in Shardman configuration change.

If not specified, a user is presented with a list of revisions that he can choose from.

-w
--wait #

Sets shardmanctl to wait for configuration changes to take effect. If a new configuration cannot be loaded by all replication groups, shardmanctl will wait forever.

Default: 1h.

-f
--force #

Perform forced setting of a parameter if a cluster operation is in progress.

-y
--yes #

Perform automatic confirmation.

config revisions #

Syntax:

shardmanctl [common_options] config revisions [-f|--format text|json]

Outputs the revision history of the Shardman cluster configuration. It has the following information for each revision:

  • revision_id — timestamp of the command that resulted in the Shardman cluster configuration change

  • host — name of the host from which this command was executed

  • user — user who executed this command

  • command — the command itself

-f=text|json
--format=text|json #

Specifies the output format.

Default: text.

config revisions set #

Syntax:

shardmanctl [common_options] config revisions set [--keep-config-revisions]

Allows setting the length of the configuration revision history. This length cannot be lower than 5, in which case it is automatically set to 5. For Shardman clusters where the configuration revision history was not collected yet, the length is automatically set to 20.

--keep-config-revisions #

A limit on the number of revisions for one Shardman configuration. If the limit is lower than the current history length, the older versions out of this limit will be deleted. Also, if the number of operations resulting in configuration changes exceeds the limit, the oldest revision is deleted.

Default: 20.

config update ip #

Syntax:

shardmanctl [common_options] config update ip [-u|ip_1=ip_2,hostname_1=hostname_2][-y|--yes]

Updates the specified node IPs in the cluster.

-u
ip_1=ip_2,hostname_1=hostname_2 #

Specifies the node IPs to be updated.

-y
--yes #

Perform automatic confirmation.

set #

Syntax:

shardmanctl [common_options] set pgParam1=value1 [pgParam2=value2 [...]] [-y|--yes] [-w|--wait time_duration] [-f|--force]

Sets the values of the specified Shardman cluster database parameters.

-w
--wait #

Sets shardmanctl to wait for configuration changes to take effect. Value examples: 2h45m, 1m30s, 5m, 10s.

Default: 1h.

-y
--yes #

Confirm the restart necessary for the parameters to take effect. If this option is not specified, and the parameters update requires a restart, the manual confirmation will be requested. If not confirmed, the cluster will continue to work, yet the new parameter values will only take effect after the restart.

-f
--force #

Perform forced setting of a parameter if a cluster operation is in progress.

upgrade #

Syntax:

shardmanctl [common_options] upgrade

Upgrades the shardman database extension and updates pg_foreign_server options.

bench init #

Syntax:

shardmanctl [common_options] bench init [--schema-type single|simple|shardman|custom]
[--schema-file file_name] [-s|--scale scale_value]  [-n|--no-vacuum]
[-F|--fillfactor fillfactor_value]

Initializes the benchmark schema via pgbench. Schema can be custom or predefined. Creates tpc-b schema tables and fills them.

--schema-type=single|simple|shardman|custom #

Type of schema used by schema initialization. Possible values:

  • single — schema for a single PostgreSQL benchmark test

  • simple — simple sharded schema

  • shardman — sharded schema optimized for Shardman

  • custom — schema initialized by the user from the --schema-file file

Default schema: shardman.

--schema-file=file_name #

File with DDL query for the custom schema type, to be used to create tpc-b tables for pgbench: pgbench_accounts, pgbench_branches, pgbench_tellers, pgbench_history.

-s scale_value
--scale=scale_value #

Multiply the number of generated rows by the given scale factor.

-n
--no-vacuum #

Perform no vacuuming during initialization.

-F fillfactor_value
--fillfactor=fillfactor_value #

Fill pgbench tables with the given fillfactor value.

bench run #

Syntax:

shardmanctl [common_options] bench run [--schema-type single|simple|shardman|custom]
[-f|--file file_name] [-c|--client client_value]  [-C|--connect] [--full-output]
[-j|--jobs jobs_value][-T|--time seconds][-t|--transactions transactions_value]
[-s|--scale scale_factor] [ -P | --progress seconds] [ -R | --rate rate] [ -M | --protocol querymode]

Runs the initialized benchmark via pgbench. Can use the default pgbench script or a custom script from a file.

--schema-type=single|simple|shardman|custom #

Type of schema used by schema initialization (bench init). Possible values:

  • single — schema for single PostgreSQL benchmark

  • simple — simple sharded schema

  • shardman — sharded schema optimized for Shardman

  • custom — schema initialized by the user from the --schema-file file.

Default schema: shardman.

-f file_name
--file=file_name #

Add a transaction script read from filename to the list of scripts to be executed.

Optionally, write an integer weight after @ to adjust the probability of selecting this script versus other ones. The default weight is 1. (To use a script file name that includes an @ character, append a weight so that there is no ambiguity, for example filen@me@1).

-c client_value
--client=client_value #

Number of clients simulated, that is, number of concurrent database sessions.

-C
--connect #

Establish a new connection for each transaction rather than doing it just once per client session.

--full-output #

Print all pgbench output.

-j jobs_value
--jobs=jobs_value #

Number of worker threads within pgbench.

-s scale_factor
--scale=scale_factor #

Multiply the number of generated rows by + the given scale factor.

-T seconds
--time=seconds #

Run the test with a time limit of the specified number of seconds. The default value is 0, which means that there is no time limit. Note that the -T and -t flags are mutually exclusive, and the -T flag takes precedence. If the -T flag is specified, the -t flag is ignored.

-t transactions_value
--transactions=transactions_value #

Run the test with a limit of the specified number of transactions on each client. The default value is 10. Note that the -T and -t flags are mutually exclusive, and the -T flag takes precedence. If the -T flag is specified, the -t flag is ignored.

-P seconds
--progress=seconds #

Show progress report every sec seconds. The report includes the time since the beginning of the run, the TPS since the last report, and the transaction latency average, standard deviation, and the number of failed transactions since the last report. Under throttling (-R), the latency is computed with respect to the transaction scheduled start time, not the actual transaction beginning time, thus it also includes the average schedule lag time. When --max-tries is used to enable transaction retries after serialization/deadlock errors, the report includes the number of retried transactions and the sum of all retries.

-R rate
--rate=rate #

Execute transactions targeting the specified rate instead of running as fast as possible (the default). The rate is given in transactions per second. If the targeted rate is above the maximum possible rate, the rate limit won't impact the results.

-M querymode
--protocol=querymode #

Protocol to use for submitting queries to the server:

  • simple: use simple query protocol.

  • extended: use extended query protocol.

  • prepared: use extended query protocol with prepared statements.

In the prepared mode, pgbench reuses the parse analysis result starting from the second query iteration, so pgbench runs faster than in other modes.

Default: simple.

bench cleanup #

Syntax:

shardmanctl [common_options] bench cleanup

Cleans up schema database after benchmarks. Drops tpc-b tables.

bench generate #

Syntax:

shardmanctl [common_options] bench generate [-c|--config file_name] [-o|--output-file file_name]

Gets the benchmark configuration from a file and generates a bash script to create a schema optimized for Shardman and run the benchmark using pgbench. The configuration file must be in yaml format.

-f file_name
--file=file_name #

The configuration file path. The file contains a sequence of script confugurations. Each script must have a schema_type: single|simple|shardman|custom. For a custom schema it is necessary to specify the schema_file with the DDL script. Optional parameters: init_flags (default set: -s 1000), run_flags (default set: -n -P 10 -c 10 -j 4 -T 60), partitions (default value: 50). It is highly recomended to use -n (--no-vacuum) parameter inside run_flags. Configuration file example:

    benches:
    - schema_type: single
      init_flags: "-s 3"
      run_flags: "-n -P 10 -c 10 -j 4 -T 10"
    - schema_type: simple
      init_flags: "-s 4"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
      partitions: 100
    - schema_type: shardman
      init_flags: "-s 5"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
    - schema_type: custom
      init_flags: "-s 6"
      schema_file: "schema.psql"
                            

-o file_name
--output-file=file_name #

Output file. Default: stdout.

script #

Syntax:

shardmanctl [common_options] script -s|--shard shard_name][[-f|--file file_name][--sql query]]

Executes non-transactional commands from a file or from the command-line on the specified shards.

-s shard_name
--shard=shard_name #

Shard name.

-f file_name
--file=file_name #

Add a transaction script from the file_name file to the list of scripts to be executed.

--sql query #

Specifies the statement to be executed and can only be used separately from -f.

psql #

Syntax:

shardmanctl [common_options] psql -s|--shard shard_name

Connects to the first available primary node if no options are specified.

-s shard_name
--shard=shard_name #

Name of the shard. If specified, the connection is installed with this shard current primary.

daemon set #

Syntax:

shardmanctl [common_options] daemon set [--session-log-level debug | info | warn | error] [--session-log-format json|text] [--session-log-nodes]

Allows updating the log parameters on the fly.

--session-log-level debug | info | warn | error #

Updates the log level to debug, info, warn, or error.

--session-log-format json|text #

Updates the log output format to text or json.

--session-log-nodes #

Specifies which cluster nodes must be updated. If not specified, the parameters are updated on every node.

Default: all nodes.

history #

Syntax:

shardmanctl [common_options] history [--reverse | -r] [-f|--format json|text] [-l|--limit number_of_commands]

Shows history of the commands that updated the cluster. By default, they are sorted from the most recent to the oldest ones.

-r
--reverse #

Switches to the ascending sorting order.

-f json|text
--format=json|text #

Output format.

Default: text.

-l
--limit=number_of_commands #

Limit for the number of the most recent commands in the output. The maximum value is 200.

Default: 20.

Common Options #

shardmanctl common options are optional parameters that are not specific to the utility. They specify etcd connection settings, cluster name and a few more settings. By default shardmanctl tries to connect to the etcd store 127.0.0.1:2379 and use the cluster0 cluster name. The default log level is info.

-h, --help #

Show brief usage information.

--cluster-name cluster_name #

Specifies the name for a cluster to operate on. The default is cluster0.

--log-level level #

Specifies the log verbosity. Possible values of level are (from minimum to maximum): error, warn, info and debug. The default is info.

--retries number #

Specifies how many times shardmanctl retries a failing etcd request. If an etcd request fails, most likely, due to a connectivity issue, shardmanctl retries it the specified number of times before reporting an error. The default is 5.

--session-timeout seconds #

Specifies the session timeout for shardmanctl locks. If there is no connectivity between shardmanctl and the etcd store for the specified number of seconds, the lock is released. The default is 30.

--store-endpoints string #

Specifies the etcd address in the format: http[s]://address[:port](,http[s]://address[:port])*. The default is http://127.0.0.1:2379.

--store-ca-file string #

Verify the certificate of the HTTPS-enabled etcd store server using this CA bundle.

--store-cert-file string #

Specifies the certificate file for client identification by the etcd store.

--store-key string #

Specifies the private key file for client identification by the etcd store.

--store-timeout duration #

Specifies the timeout for a etcd request. The default is 5 seconds.

--monitor-port number #

Specifies the port for the shardmand http server for metrics and probes. The default is 15432.

--api-port number #

Specifies the port for the shardmand http api server. The default is 15432.

--version #

Show shardman-utils version information.

Environment #

SDM_BACKUP_MODE #

An alternative to setting the --backup-mode option.

SDM_BACKUP_PATH #

An alternative to setting the --backup-path option.

SDM_CLUSTER_NAME #

An alternative to setting the --cluster-name option.

SDM_ETCD_PATH #

An alternative to setting the --etcd-path option.

SDM_FILE #

An alternative to setting the --file option for config update.

SDM_LOG_LEVEL #

An alternative to setting the --log-level option.

SDM_NODES #

An alternative to setting the --nodes option for nodes add and nodes rm.

SDM_RETRIES #

An alternative to setting the --retries option.

SDM_SPEC_FILE #

An alternative to setting the --spec-file option for init.

SDM_STORE_ENDPOINTS #

An alternative to setting the --store-endpoints option.

SDM_STORE_CA_FILE #

An alternative to setting the --store-ca-file option.

SDM_STORE_CERT_FILE #

An alternative to setting the --store-cert-file option.

SDM_STORE_KEY #

An alternative to setting the --store-key option.

SDM_STORE_TIMEOUT #

An alternative to setting the --store-timeout option.

SDM_SESSION_TIMEOUT #

An alternative to setting the --session-timeout option.

Usage #

Adding Nodes to a Shardman Cluster #

To add nodes to a Shardman cluster, run the following command:

shardmanctl [common_options] nodes add -n|--nodes node_names

You must specify the -n (--nodes) option to pass the comma-separated list of nodes to be added. Nodes can be referred by their hostname or IP address. Hostnames must be correctly resolved on all nodes.

If nodes add command fails during execution, use the cleanup --after-node-operation command to fix possible cluster configuration issues.

Performing Cleanup #

By default, cleanup operates in the report-only mode, that is, the following command will only show actions to be done during actual cleanup:

    shardmanctl [common_options] cleanup --after-node-operation|--after-rebalance
   

To perform the actual cleanup, run the following command:

    shardmanctl [common_options] cleanup -p|--processrepgroups --after-node-operation|--after-rebalance
   

Displaying the Cluster Topology #

cluster topology displays the current cluster topology. The default is the table mode. All cluster nodes will be grouped by the replication groups they belong to. For each node, its status will be displayed.

    shardmanctl [common_options] cluster topology -f|--format table|json|text
   

Checking shardmand Service on Nodes #

daemon check not only checks that shardmand service is running on specified nodes, but also assures those services are configured for the same cluster as shardmanctl:

    shardmanctl [common_options] daemon check -n|--nodes node_names
   

Removing Nodes from a Shardman cluster #

To remove nodes from a Shardman cluster, run the following command:

shardmanctl [common_options] nodes rm -n|--nodes node_names

Specify the -n (--nodes) option to pass the comma-separated list of nodes to be removed.Recreates all partitions of sharded tables

Note

Do not use the cleanup command to fix possible cluster configuration issues after a failure of nodes rm. Redo the nodes rm command instead.

To remove all nodes in a cluster and not care about the data, just reinitialize the cluster. If a removed replication group contains local (non-sharded and non-global) tables, the data is silently lost after the replication group removal.

Getting the Standby Cluster Status #

Here is a sample status output from shardmanctl with OK and Error statuses for the cluster in the standby mode. It also shows what syncpoint each DB instance was restored to, and whether it is required to wait for recovery to the next syncpoint. For the standby mode, this is what the output looks like (and not what was filtered with --filter option):

        $ shardmanctl status
        
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                                                        == STANDBY CLUSTER STATUS ==                                                                                                                                                                      │
├─────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────┤─────────────────────────────────────────────────────┤
│            STATUS           │                                                      MESSAGE                                                     │                           NODE                          │                    REPLICATION GROUP                    │        LSN_DIFF          │        TIME_DIFF         │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/1189F0A0, last found │                          shrn1r                         │                         shard-1                         │          25.75MB         │           162            │
│                             │                                            syncpoint LSN is 0/11CA0588                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│              OK             │                          Instance recovered at a syncpoint with CSN 1754916734406196000                          │                          shrn2r                         │                         shard-2                         │          18.8MB          │           102            │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────│──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/157A3618, last found │                          shrn3r                         │                         shard-3                         │          277.1MB         │           162            │
│                             │                                            syncpoint LSN is 0/233CEB70                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/16C743C8, last found │                          shrn4r                         │                         shard-4                         │          277.1MB         │           162            │
│                             │                                            syncpoint LSN is 0/2616C078                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│           WARNING           │ Instance recovered at an older syncpoint with CSN 1754916674425273000; last replay LSN is 0/1AB9A798, last found │                          shrn5r                         │                         shard-5                         │          277.1MB         │           162            │
│                             │                                            syncpoint LSN is 0/2DF8F348                                           │                                                         │                                                         │                          │                          │
├─────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────┤──────────────────────────┤──────────────────────────┤
│              OK             │                          Instance recovered at a syncpoint with CSN 1754916734406196000                          │                          shrn6r                         │                         shard-6                         │          18.8MB          │           102            │
└─────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────┘


          
        

For json format:

shardmanctl status --format json
[
 {
  "Title": "STANDBY CLUSTER STATUS",
  "Messages": [
   {
    "Status": "WARNING",
    "Message": "Instance recovered using catchup, need to wait for recovery to the next syncpoint",
    "Node": "shrn1r",
    "Shard": "shard-1"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn2r",
    "Shard": "shard-2"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn3r",
    "Shard": "shard-3"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn4r",
    "Shard": "shard-4"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn5r",
    "Shard": "shard-5"
   },
   {
    "Status": "OK",
    "Message": "Instance recovered at a syncpoint with CSN 1754917034419818000",
    "Node": "shrn6r",
    "Shard": "shard-6"
   }
  ]
 }
]

LSN_DIFF shows the difference between the last LSN being applied on the primary instance and on the standby. TIME_DIFF shows how many seconds passed since the current applied syncpoint on the standby cluster was created.

Getting the Status of Cluster Subsystems #

To get a report on the health status of Shardman cluster in a table format for metadata and store subsystems sorted by replication group, run the following command:

    shardmanctl [common_options] status --filter=metadata,store --sort=rg
   

To get the report in JSON format, use -f|--format=json option (omitted above since table format is used by default). Each detected issue is reported as an Unknown, Warning, Error or Fatal error status. The tool can also report an Operational error, which means there was an issue during the cluster health check. When the command encounters a Fatal or Operational error, it stops further diagnostics. For example, an inconsistency in the store metadata does not allow correct cluster operations and must be handled first.

Outputting the List of Unresolved Distributed Transactions #

To view the list of distributed transactions that Shardman built-in monitoring tools failed to resolve, run the following command:

    shardmanctl [common_options] status transactions -r|--repgroup replication_group_name

Each output transaction consists of tx_id (transaction ID), coordinator_id, creation_time and description (error or transaction status). To display the list of transactions for a specific replication group, use the -r|--repgroup option (for all replication groups by default). In case there are no such transactions, returns null value in JSON.

Dumping All Keys from the Store to Debug Error Configuration #

After facing an error while using Shardman cluster, to fill in an exhaustive report, it is convinient to dump all specifications that could produce such an error with the following command:

    shardmanctl [common_options] store dump -f|--file filename
   

Some harmless errors may be shown, but they will not interrupt dumping. If you do not specify the filename, dump will be sent to stdout and may pollute your terminal.

Getting the Current stolon Specification #

To get the current stolon specification, which is normally a part of cluster key in the store, use the following command:

    shardmanctl [common_options] store get -a|--alias stolonspec -f|--file filename
   

If the cluster key is corrupted itself, stolon specification will not be shown either. Instead of using the alias, you may also find out the full cluster data key name (by listing all keys with store keys command), use store get to retrieve it and find the stolon part there. Mind that while using the last option, shardman.config_uuid parameter will not be deleted, which may result in a conflict in later use of this data; for manipulation with stolon specification, it is recommended to use shardmanctl store get -a stolonspec command.

Getting the Cluster and Ladle Key Names For the Current Cluster #

To get all key names in the store at once, run the following command:

    shardmanctl [common_options] store keys
   

It can only be shown in JSON format. It will also print alias names for keys that have them (excluding stolonspec and spec, since they are parts of other keys)

Output Current Cluster Meta Lock Information #

You can view information about current cluster meta locks that acquired by any command:

    shardmanctl [common_options] store lock -f|--format json
   

To get the report in JSON format, use -f|--format=json option (omitted above since text format is used by default). In case the lock does not exists returns Lock not found

Setting a New Spec for the Cluster #

To set a new spec part of the cluster specification, run the following command:

    shardmanctl [common_options] store set --alias=spec --file=spec.json
   

Since spec is a part of cluster data key, it cannot be set with --key. If the provided file is not a valid JSON, the new spec part will not be set.

Registering a Shardman Cluster #

To register a Shardman cluster in the etcd store, run the following command:

    shardmanctl [common_options] init [-y|--yes] [-f|--spec-file spec_file_name]|spec_text
   

You must provide the string with the cluster specification. You can do it as follows:

  • On the command line — do not specify the -f option and pass the string in spec_text.

  • On the standard input — specify the -f option and pass - in spec_file_name.

  • In a file — specify the -f option and pass the filename in spec_file_name.

Backing up a Shardman Cluster Using probackup Command #

Requirements for backing up and restoring a Shardman cluster using the probackup command are listed in Section 2.6.1.1.

For example, following these requirements, on the backup host:

  groupadd postgres
  useradd -m -N -g postgres -r -d /var/lib/postgresql -s /bin/bash
 

Then add SSH keys to provide passwordless SSH connection between the backup host and Shardman cluster hosts. Then on the backup host:

  apt-get install pg-probackup shardman-utils
  mkdir -p directory
  chown postgres:postgres directory -R
  shardmanctl [common_options] probackup init --backup-path=directory --etcd-path=directory/etcd --remote-user=postgres --remote-port=22
  shardmanctl [common_options] probackup archive-command --backup-path=directory --remote-user=postgres --remote-port=22
  

If all the requirements are met, then run the probackup backup subcommand for the cluster backup:

shardmanctl [common_options] probackup backup --backup-path=directory --etcd-path=directory --backup-mode=MODE
  

You must pass the directories through the --backup-path and --etcd-path options and backup mode through --backup-mode. Full and delta backups are available with FULL, DELTA, PTRACK and PAGE values. Also it is possible to specify backup compression options --compress-level, as well as specify --remote-port and --remote-user. You can limit the number of running concurrent tasks when doing backup by passing the limit through the --maxtasks option.

By default, copying data via SSH is used to create a backup. To copy data to a mounted partition instead, use the --storage-type option with the mount value. This value will be automatically used in the restore process.

You can also copy data to an S3-compatible object storage. To do this, use the --storage-type option with the S3 value. When this value is used, it is required to specify the directory for pg_probackup logs. You can do it either by specifying --log-directory for each command or set the environment variable SDM_LOG_DIRECTORY, for example:

export SDM_LOG_DIRECTORY=/backup/logs

If you are going to perform backup/restore only for an S3-compatible object storage, you can also set an environment variable instead of specifying --storage-type in each probackup command:

export SDM_STORAGE_TYPE=S3
                

Restoring a Shardman Cluster using probackup command #

shardmanctl in probackup mode can perform either full restore, metadata-only or schema-only restore of a Shardman cluster from a backup created by the probackup backup command.

To perform full or partial restore, firstly you must select needed backup to restore from. To show list of available backups run the following command:

shardmanctl [common_options] probackup show --backup-path=path --format=format [--archive ] [-i|--backup-id backup-id] [--instance instance]

The output should be a list of backups with their IDs in a table or JSON format. Then pick the needed backup ID and run the probackup restore command.

shardmanctl [common_options] probackup restore --backup-path=path --backup-id=id

Pass the path to the repo through the --backup-path option and backup ID througt --backup-id flag.

If you encounter issues with an etcd instance, it makes sense to perform metadata-only restore. To do this, you can run the following command:

shardmanctl [common_options] probackup restore --backup-path=path --backup-id=id --metadata-only

If you need to restore only schema information, like: tables, roles and etc. you should specify --schema-only option.

For both kinds of restore, you can specify --timeout for the tool to exit with error after waiting until the cluster is ready or the recovery is complete for the specified number of seconds.

You can specify --shard parameter for restoring only on the single shard.

Also you can specify --recovery-target-time option for Point-in-Time Recovery. In this case Shardman finds the closest syncpoint to specified timestamp and suggests restoring on the found LSN. You can also specify --wal-limit to limit the number of WAL segments to be processed.

Important

Before restoring a Shardman cluster, make sure that the cluster is up by executing the shardmanctl status command. If the output shows errors, performing the restore can result in the cluster becoming unavailable. First, fix the errors by reinitializing the cluster and restoring the etcd metadata. Then you can proceed to restoring the cluster from backup.

Reinitializing Replicas #

If replicas are in an incorrect state, you can reset them using the shardmanctl command:

shardmanctl [common_options] shard --shard=shard_name replicas reinit

This command determines the nodes on which replicas of the specified shard are running and sends a request to shardmand on these nodes. After receiving this request, shardmand clears the postgres data directory and restarts the keeper thread that is responsible for managing the replica. After that, the replicas are restarted and begin to receive data from the corresponding primary.

Examples #

Initializing the Cluster

To initialize a Shardman cluster that has the cluster0 name, uses an etcd cluster consisting of n1,n2 and n3 nodes listening on port 2379, ensure proper settings in the spec file sdmspec.json and run:

$ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 init -f sdmspec.json

Getting the Cluster Connection String

To get the connection string for a Shardman cluster that has the cluster0 name, uses an etcd cluster consisting of n1,n2 and n3 nodes listening on port 2379, run:

 $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 getconnstr
 
 dbname=postgres host=n1,n4,n2,n1,n1,n2,n4,n3 password=yourpasswordhere port=5432,5433,5432,5433,5432,5433,5432,5433 user=postgres
 
 

To add replicas to getconnstr, use --all.

Getting the Cluster Status

Here is a sample status output from shardmanctl with OK and Error statuses:

        $ shardmanctl status --filter store,shardmand,rg --sort=node
        
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                            == STORE STATUS ==                                            │
├────────────┬─────────────────────────────────────────────┬───────────────────────┬───────────────────────┤
│   STATUS   │                   MESSAGE                   │   REPLICATION GROUP   │          NODE         │
├────────────┼─────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ etcd store is OK                            │                       │                       │
└────────────┴─────────────────────────────────────────────┴───────────────────────┴───────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                          == SHARDMAND STATUS ==                                           │
├────────────┬─────────────────────────────────────────────┬───────────────────────┬───────────────────────┤
│   STATUS   │                   MESSAGE                   │   REPLICATION GROUP   │          NODE         │
├────────────┼─────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ shardmand on node 56d819b4e9e4 is OK        │                       │      56d819b4e9e4     │
├────────────┼─────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ shardmand on node 6d0aabd50acc is OK        │                       │      6d0aabd50acc     │
└────────────┴─────────────────────────────────────────────┴───────────────────────┴───────────────────────┘
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                       == REPLICATION GROUP STATUS ==                                      │
├────────────┬──────────────────────────────────────────────┬───────────────────────┬───────────────────────┤
│   STATUS   │                    MESSAGE                   │   REPLICATION GROUP   │          NODE         │
├────────────┼──────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│     OK     │ Replication group clover-1-56d819b4e9e4 is   │ clover-1-56d819b4e9e4 │                       │
│            │ OK                                           │                       │                       │
├────────────┼──────────────────────────────────────────────┼───────────────────────┼───────────────────────┤
│            │ Replication connection is down for slave     │                       │                       │
│    Error   │ 6d0aabd50acc:5442 in replication group       │ clover-1-6d0aabd50acc │   6d0aabd50acc:5442   │
│            │ clover-1-6d0aabd50acc                        │                       │                       │
└────────────┴──────────────────────────────────────────────┴───────────────────────┴───────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────────────┐

│                           == RESTART REQUIRED PARAMS STATUS ==                          │

├──────────┬──────────────────────────────────────┬───────────────────┬───────────────────┤

│  STATUS  │                MESSAGE               │ REPLICATION GROUP │        NODE       │

├──────────┼──────────────────────────────────────┼───────────────────┼───────────────────┤

│    OK    │     No pending restart parameters    │      shard-1      │       shrn1       │

├──────────┼──────────────────────────────────────┼───────────────────┼───────────────────┤

│    OK    │     No pending restart parameters    │      shard-2      │       shrn4       │

└──────────┴──────────────────────────────────────┴───────────────────┴───────────────────┘
          
        

Rewriting stolon Specification

First, get the list of available keys in the store using the following command:

      $ shardmanctl store keys
        
{
 "Key": "shardman/cluster0/data/cluster",
 "Alias": "cluster"
}{
 "Key": "shardman/cluster0/data/shardmand/56d819b4e9e4"
}{
...
 "Key": "shardman/cluster0/stolon/remoteLogs/6d0aabd50acc/clover-1-6d0aabd50acc/keeper_1/error"
}
        
      

Get stolon configuration from the store and save it in the stolonspec.json file with the command

      $ shardmanctl store get -a stolonspec -f stolonspec.json
    

Apply the necessary changes to the file and upload the new specification using shardmanctl config update. Mind that shardman.config_uuid parameter is deleted with shardmanctl store get -a stolonspec and not with shardmanctl store get -k full/path/to/clusterspec; using spec with existing shardman.config_uuid will result in a conflict.

Important

Do not use store set command to update cluster configurations because it does not apply a new specification on all nodes, it only writes it to the store. For the above example with stolon specification, shardmanctl config update is acceptable.

To double-check, you can get the cluster key with new StolonSpec by the full key name (which was shown earlier with store keys command):

      $ shardmanctl store get -k shardman/cluster0/data/cluster
        
{
  "FormatVersion": 1,
  "Spec": {
    "PgSuAuthMethod": "md5",
    "PgSuPassword": "12345",
    "PgSuUsername": "postgres",
    "PgReplAuthMethod": "md5",
    "PgReplPassword": "12345",
    "PgReplUsername": "repluser",
    "ShardSpec": {
      ...
}
        
      

Adding Nodes to the Cluster

To add n1,n2, n3 and n4 nodes to the cluster, run:

$ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 nodes add -n n1,n2,n3,n4

Important

The number of nodes being added must be a multiple of Repfactor + 1 if cross placement policy is used.

Removing Nodes from the Cluster

To remove n1 and n2 nodes from the cluster0 cluster, run:

      $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 nodes rm -n n1,n2
    

If cross placement policy is used, then the clovers that contain them will be deleted along with the nodes.

Executing a Query on All Replication Groups

To execute the select version() query on all replication groups, run:

 $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 forall --sql 'select version()'
 
 Node 1 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 Node 4 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 Node 3 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 Node 2 says:
 [PostgreSQL 13.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit]
 
 

Performing Rebalance

To rebalance sharded tables in the cluster0 cluster, run:

 $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 rebalance
 

Updating PostgreSQL Configuration Settings #

To set the max_connections parameter to 200 in the cluster, create the spec file (for instance, ~/stolon.json) with the following contents:

 {
   "pgParameters": {
     "max_connections": "200"
   }
 }
 

Then run:

 $ shardmanctl --store-endpoints http://n1:2379,http://n2:2379,http://n3:2379 config update -p -f ~/stolon.json
 

Since changing max_connections requires a restart, DBMS instances are restarted by this command.

Performing Backup and Recovery

To create a backup of the cluster0 cluster using etcd at etcdserver listening on port 2379 and store it in the local directory /var/backup/shardman, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 backup --datadir=/var/backup/shardman --use-ssh

Assume that you are performing a recovery from a backup to the cluster0 cluster using etcd at etcdserver listening on port 2379 and you take the backup description from the /var/backup/shardman/backup_info file. Edit the /var/backup/shardman/backup_info file, set DataRestoreCommand , RestoreCommand as necessary and run:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover --info /var/backup/shardman/backup_info

For metadata-only restore, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover --metadata-only --dumpfile /var/backup/shardman/etcd_dump

For schema-only restore, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover --schema-only --dumpfile /var/backup/shardman/etcd_dump

For single shard restore, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 recover  --info /var/backup/shardman/backup_info --shard shard_1

Performing Backup and Recovery with probackup Command

To create a backup of the cluster0 cluster using etcd at etcdserver listening on port 2379 and store it in the local directory /var/backup/shardman, first initialize the backups repository with the init subcommand:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup init --backup-path=/var/backup/shardman --etcd-path=/var/backup/etcd_dump

Then add and enable archive_command with the archive-command subcommand:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup archive-command add --backup-path=/var/backup/shardman

If the repository is successfully initialized and archive-command successfully added, create a FULL backup with the probackup backup subcommand:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup backup --backup-path=/var/backup/shardman --etcd-path=/var/backup/etcd_dump --backup-mode=FULL --compress --compress-algorithm=zlib --compress-level=5

To create DELTA, PTRACK or PAGE backup, run the probackup backup subcommand with DELTA, PTRACK or PAGE value of the --backup-mode option:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup backup --backup-path=/var/backup/shardman --etcd-path=/var/backup/etcd_dump --backup-mode=DELTA  --compress --compress-algorithm=zlib --compress-level=5

To show the created backup ID, run show subcommand:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup show --backup-path=/var/backup/shardman --format=table

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                                      == BACKUP ID 'S88FRO'                                                                                                     │
│                                                                                                               ==                                                                                                               │
├───────────────────────────────────┬───────────────────────────────────┬───────────────────────────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┤
│              INSTANCE             │                HOST               │           RECOVERY TIME           │    MODE    │  WAL MODE  │     TLI    │    DATA    │     WAL    │   Z-RATIO  │  START LSN │  STOP LSN  │   STATUS   │
├───────────────────────────────────┼───────────────────────────────────┼───────────────────────────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│              shard-1              │               n1                  │       2024-02-02 14:19:05+00      │    FULL    │   ARCHIVE  │     1/0    │  42.37MiB  │    16MiB   │    1.00    │  0/C000028 │  0/D0018B0 │     OK     │
├───────────────────────────────────┼───────────────────────────────────┼───────────────────────────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│              shard-2              │               n2                  │       2024-02-02 14:19:05+00      │    FULL    │   ARCHIVE  │     1/0    │  42.38MiB  │    16MiB   │    1.00    │  0/C000028 │  0/D001E00 │     OK     │
└───────────────────────────────────┴───────────────────────────────────┴───────────────────────────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘


In PTRACK backup mode, Shardman tracks page changes on the fly. Continuous archiving is not necessary for it to operate. Each time a relation page is updated, this page is marked in a special PTRACK bitmap. Tracking implies some minor overhead on the database server operation, but speeds up incremental backups significantly.

If you are going to use PTRACK backups, complete the following additional steps:

  • Preload the ptrack shared library on each node. This can be done by adding the ptrack value to the shared_preload_libraries parameter.

  • Сreate the PTRACK extension on each cluster node:

                                $ shardmanctl --store-endpoints http://etcdserver:2379 forall --sql "create extension ptrack"
    

  • To enable tracking page updates, set the ptrack.map_size parameter as follows:

                                $ shardmanctl --store-endpoints http://etcdserver:2379 update '{"pgParameters":{"ptrack.map_size":"64"}}'
    

    For optimal performance, it is recommended to set ptrack.map_size to N/1024, where N is the maximum size of the cluster node, in MB. If you set this parameter to a lower value, PTRACK is more likely to map several blocks together, which leads to false-positive results when tracking changed blocks and increases the incremental backup size as unchanged blocks can also be copied into the incremental backup. Setting ptrack.map_size to a higher value does not affect PTRACK operation, but it is not recommended to set this parameter to a value higher than 1024.

To validate the created backup, run validate subcommand:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup validate --backup-path=/var/backup/shardman --backup-id=RFP1FI

Assume that you are performing a recovery from a backup to the cluster0 cluster using etcd at etcdserver listening on port 2379 and you take the backup ID from the show command:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --backup-path=/var/backup/shardman --backup-id=RFP1FI
  

Finally we need to enable archive_command back.

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup archive-command add --backup-path=/var/backup/shardman

For metadata-only restore, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --metadata-only --backup-path=/var/backup/shardman --backup-id=RFP1FI

For metadata-only restore, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --schema-only --backup-path=/var/backup/shardman --backup-id=RFP1FI

For single shard restore, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --backup-path=/var/backup/shardman --backup-id=RFP1FI --shard shard_1

For Point-in-Time Recovery, run:

$ shardmanctl --store-endpoints http://etcdserver:2379 probackup restore --metadata-only --backup-path=/var/backup/shardman --backup-id=RFP1FI --recovery-target-time='2006-01-02 15:04:05' -s

Loading Data from a Text File

To load data into a Shardman cluster, run the following command:

$ shardmanctl --store-endpoints http://etcdserver:2379 load --file=/var/load/data.tsv --table=mytable --source file --format text -j 8
    

In this example, data is loaded from the /var/load/data.tsv data file (tab-delimited) into the table mytable in 8 parallel threads. You can use schema.table as the table name.

Loading data from PostgreSQL table

To load data into a Shardman cluster from a PostgreSQL table, run the following command:

$ shardmanctl --store-endpoints http://etcdserver:2379 load -t desttable --source postgres --source-connstr "dbname=db host=srchost port=srcport user=login password=passwd" --source-table sourcetable -j 8
    

In this example, data is loaded from the table sourcetable into the desttable table in 8 parallel threads. You can use schema.table as table names.

Loading Data with a Schema from PostgreSQL #

To load data with a schema into Shardman cluster from PostgreSQL, run the following command:

$ shardmanctl --store-endpoints http://etcdserver:2379 load --schema load_schema.yaml
    

The file load_schema.yaml has the folowing format:

version: "1.0"
migrate:
  connstr: "dbname=workdb host=workhost port=workport user=workuser password=workpassword"
  jobs: 8
  batch: 1000
  options:
    - create_schema
    - create_table
    - create_index
    - create_sequence
    - create_foreign_key
    - create_role
    - copy_ownership
    - copy_grants
    - truncate_table
    - skip_no_pkey_tables
    - skip_create_index_error
    - skip_create_extension_error
    - skip_load_errors
    - skip_create_foreign_key_error
    - skip_create_role_error
    - skip_copy_grants_error
    - skip_copy_ownership_error
  schemas:
    - name: public
      all: false
      tables:
        - name: tab1
          type: sharded
          partitions: 6
          distributedby: id
          priority: 3
        - name: tab2
          type: global
        - name: tab3
          type: sharded
          partitions: 6
          distributedby: field_id
          colocatewith: tab1
        - name: table4
            type: global
            source: schema.view
            source_pk: field_id
        - name: table5
            type: global
            source: schema.func(arg)
            source_pk: field_id
    - name: schema2
      all: false
      default_type: sharded
      default_partitions: 6
      tables:
        - name: table1
          distributedby: field_id
          priority: 2
        - name: table2
          type: global
        - name: table3
          source: schema.view
          distributedby: field_id
          priority: 3
        - name: table4
          distributedby: field_id
          source: schema.func(arg)
        - name: table5
          source: schema."complex.""table.name"
          distributedby: field_id
    - name: schema3
      all: true
      skip_tables: [table1, table2, table3]
  roles:
    - name: test_user1
      password: test_password
    - name: test_user2
    

The migrate.jobs value defines the number of parallel data loader processes.

The migrate.batch value is the number of rows in one batch (recommended value is 1000).

The migrate.schemas section defines an array of source database schemas that you are working with. All other schemas will be skipped.

If the all value is set to true, then all tables from the current schema will be migrated (with global type by default). If a table is listed in the migrate.schemas.tables array, then the target table type must be explicitly specified for it. Two types of tables are currently supported: global and sharded. Global tables are loaded first, then sharded tables and at the end sharded tables with the colocatedwith parameter. The order of loading tables of the same type can be changed using priority option.

The migrate.schemas.skip_tables section defines an array of table names that will be skipped when the schema is loaded even if the all parameter is set to true.

For sharded tables, the following attributes must be set: distributedby (specifies the name of the column to use for the table partitioning) and partitions (number of partitions that will be created for this table). Optionally, for sharded tables colocatewith attribute can be set (name of the table to colocate with). Shardman will try to place partitions of the created table with the same partition key on the same nodes as the corresponding partitions of the table specified by colocatewith.

You can specify the table default_type option for a schema: global or sharded (default: global). For the sharded type you can also specify the default_partitions option (default: 20). If you set default_type to sharded, you need to specify the distributedby option for each table.

The source option for a table should include the schema and table source: schema.source. The source can be a table, view or function. For example: public.table, public.view, public.func(arg). If you set the source view or function for a global table, you should specify source_pk to set the primary key for this table. If source is not specified or contains the name of a table, you can also specify source_pk to create a primary key or override the existing one.

The priority option for table determines the order in which the tables of the same type are loaded. Tables with higher priority are loaded earlier. Default priority value is 0.

The migrate.roles section defines an array of role names and passwords that will be copied from the source database if create_role is specified.

The schema supports the following options:

  • create_schema — create database schemas if they do not exist.

  • create_table — create tables if they do not exist.

  • create_index — create indexes after creating tables.

  • create_sequence — create sequences if they do not exist.

  • create_foreign_key — create foreign keys after creating tables.

  • truncate_table — truncate tables before data load.

  • create_role — create global roles defined in migrate.roles and copy role parameters from the source database.

  • copy_grants — copy access privileges from the source database.

  • copy_ownership — change of table owners to the owner in the source database.

  • skip_no_pkey_tables — skip tables without primary keys.

  • skip_create_index_error — skip index creation errors.

  • skip_create_extension_error — skip extension creation errors.

  • skip_load_errors — continue loading if errors occur.

  • skip_create_foreign_key_error — skip foreign key creation errors.

  • skip_create_role_error — skip role creation errors.

  • skip_copy_ownership_error — skip table owner changing errors.

  • skip_copy_grants_error — skip errors when copying access privuleges from the source database.

Initialization and Running Benchmarks #

To initialize a benchmark via shardmanctl using pgbench with the shardman schema, scale=1000, partitions=40, run:

$ shardmanctl bench init --schema-type=shardman --scale=1000 --partitions=40

To run an initialized benchmark for the same shardman schema, number of jobs=4, number of clients=10, duration in seconds=60 and full pgbench output, use:

$ shardmanctl bench run --schema-type=shardman --jobs=4 --client=10 --time=60 --full-output 

To initialize a benchmark with the custom schema from file schema.psql with scale=1000 run:

$ shardmanctl bench init --schema-type=custom --schema-file=schema.psql --scale=1000

To run an initialized benchmark with the custom schema and custom transaction script from script.psql with the number of jobs=4, number of clients=10, duration in seconds=60, use:

$ shardmanctl bench run --schema-type=custom --file=script.psql --jobs=4 --client=10 --time=60 

To clean up a PostgreSQL database of tpc-b tables, use:

$ shardmanctl bench cleanup

Benchmark Generation Scripts

To generate a benchmark sequence via shardmanctl from the config file=cfg.yaml and output the result to file=script.sh, run:

$ shardmanctl bench generate --config=cfg.yaml --output-file=script.sh

Configuration file example:

    benches:
    - schema_type: single
      init_flags: "-s 3"
      run_flags: "-n -P 10 -c 10 -j 4 -T 10"
    - schema_type: simple
      init_flags: "-s 4"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
      partitions: 100
    - schema_type: shardman
      init_flags: "-s 5"
      run_flags: "-n -P 10 -c 20 -j 4 -T 10"
    - schema_type: custom
      init_flags: "-s 6"
      schema_file: "schema.psql"
                            

FAQ