1.1. Быстрый запуск #

Если ваш администратор выполнил установку не с параметрами по умолчанию, вам может потребоваться проделать дополнительную работу. Например, если сервер баз данных установлен на удалённом компьютере, вам нужно будет указать в переменной окружения PGHOST имя этого компьютера. Вероятно, также придётся установить переменную окружения PGPORT. То есть, если вы пытаетесь запустить клиентское приложение и оно сообщает, что не может подключиться к базе данных, вы должны обратиться к вашему администратору. Если это вы сами, вам следует обратиться к документации и убедиться в правильности настройки окружения. Если вы не поняли, о чём здесь идёт речь, перейдите к следующему разделу.

Postgres Pro Shardman состоит из следующих программных компонентов:

  • СУБД PostgreSQL 18 с набором изменений.

  • Расширение Postgres Pro Shardman.

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

  • Расширение BiHA.

Конфигурация Postgres Pro Shardman хранится в распределённом хранилище.

Демон shardmand контролирует конфигурацию кластера и управляет BiHA-кластерами, которые обеспечивают отказоустойчивость сегментов. Общая конфигурация Postgres Pro Shardman (shardmand) хранится в распределённом хранилище.

В настоящее время пакеты Postgres Pro Shardman доступны для следующих ОС:

  • Ubuntu 22.04/24.04 (не сертифицированная редакция)

  • Debian 12/13 (не сертифицированная редакция)

  • РОСА «ХРОМ» 12.7 (не сертифицированная редакция)

  • РЕД ОС 7.3 (не сертифицированная редакция) и РЕД ОС 8 (как не сертифицированная, так и сертифицированная редакция)

  • Альт 10/11 (не сертифицированная редакция) и Альт СП релиз 10

  • Astra Linux 1.7/1.8 и s390x (не сертифицированная редакция)

1.1.1. Выбор устанавливаемых пакетов #

В следующей таблице перечислены все имеющиеся пакеты Postgres Pro Shardman.

Таблица 1.1. Пакеты Postgres Pro Shardman

Пакет

Описание

postgrespro-sdm-18

Пакет верхнего уровня, устанавливающий и настраивающий Postgres Pro Shardman для серверных и клиентских систем. Не используйте этот пакет при обновлении или миграции.

Важно

При установке пакета postgrespro-sdm-18 могут быть удалены существующие инсталляции продуктов на базе Postgres Pro Shardman и PostgreSQL. И напротив, установленный пакет Postgres Pro Shardman может быть автоматически удалён, если вы впоследствии развернёте другой продукт на базе PostgreSQL.

postgrespro-sdm-18-debuginfo

Пакет верхнего уровня, устанавливающий символы отладки для других пакетов.

postgrespro-sdm-18-client

Стандартные клиентские приложения, такие как psql и pg_dump.

postgrespro-sdm-18-client-debuginfo

Пакет для отладки.

sdm-18-services

Демон shardmand для управления службами Postgres Pro Shardman.

sdm-18-tools

Утилита командной строки для управления демоном или утилитами, например, shardmanctl.

postgrespro-sdm-18-libs

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

postgrespro-sdm-18-libs-debuginfo

Пакет для отладки.

postgrespro-sdm-18-server

Сервер Postgres Pro Shardman и серверный язык программирования PL/pgSQL.

postgrespro-sdm-18-server-debuginfo

Пакет для отладки.

postgrespro-sdm-18-contrib

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

postgrespro-sdm-18-contrib-debuginfo

Пакет для отладки.

postgrespro-sdm-18-devel

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

В системах на базе Debian этот пакет называется postgrespro-sdm-18-dev.

postgrespro-sdm-18-devel-debuginfo

Пакет для отладки для заголовочных файлов.

postgrespro-sdm-18-plperl

Реализация языка Perl для программирования на стороне сервера (см. Главу 46).

postgrespro-sdm-18-plperl-debuginfo

Пакет для отладки.

postgrespro-sdm-18-plpython3

Реализация языка Python 3 для программирования на стороне сервера (см. PL/Python).

postgrespro-sdm-18-plpython3-debuginfo

Пакет для отладки.

postgrespro-sdm-18-pltcl

Реализация языка Tcl для программирования на стороне сервера (см. Главу 45).

postgrespro-sdm-18-ptcl-debuginfo

Пакет для отладки.

postgrespro-sdm-18-docs

Документация на английском языке.

postgrespro-sdm-18-docs-ru

Документация на русском языке.

biha-utils-sdm-18

Версия bihactl для Golang, которой через BiHA могут управлять shardmanctl и другие утилиты.

postgrespro-sdm-18-jit

Этот пакет обеспечивает поддержку JIT-компиляции.

Этот пакет предоставляется только для архитектуры x86_64 и только для поддерживаемых систем Debian и Ubuntu, Astra Linux 1.7/1.8 и поддерживаемых систем Альт.

Чтобы узнать об использовании JIT больше, обратитесь к Главе 30.

postgrespro-sdm-18-jit-debuginfo

Пакет для отладки.

pg-probackup3

Утилита pg_probackup3. Категорически запрещается использовать версии pg_probackup3, отличные от поставляемых в репозитории Postgres Pro Shardman.

pg-probackup3-debuginfo

Пакет для отладки.

pgpro-controldata

Утилита pgpro_controldata, показывающая управляющую информацию кластера БД PostgreSQL/Postgres Pro Shardman и параметры совместимости кластера и/или сервера.

pgpro-pwr-sdm-18

Расширение pgpro_pwr, позволяющее получать отчёты по нагрузке, полезные для выявления наиболее ресурсоёмких операций в базе данных.

ppgpro-logical-slot-sdm-18

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


Кроме того, Postgres Pro Shardman предоставляет отдельные пакеты с отладочной информацией для некоторых операционных систем:

  • В системах на базе Debian это пакет postgrespro-sdm-18-dbg.

  • В ОС Альт Линукс для всех пакетов с двоичными файлами имеются соответствующие пакеты -debuginfo.

1.1.2. Конфигурирование кластера #

Минимальная конфигурация состоит из двух узлов Postgres Pro Shardman.

Допустим, у нас есть следующие имена узлов и IP-адреса:

 192.0.1.20 sdm01 - первый узел Shardman
 192.0.1.21 sdm02 - второй узел Shardman
192.0.1.100 ntp  - сервер синхронизации по местному времени (необязательно)

Характеристики каждого узла: 4Gb RAM, 20GB HDD, 2CPU и ОС Ubuntu 22.04.

1.1.3. Подготовка #

1.1.3.1. Добавление имён узлов в /etc/hosts #

Этот шаг следует выполнить на всех узлах.

sudo /bin/sh -c 'cat << EOF >> /etc/hosts
192.0.1.20 sdm01
192.0.1.21 sdm02
EOF'

1.1.3.2. Синхронизация по времени #

Этот шаг следует выполнить на всех узлах.

Установите и запустите демон chrony на всех узлах.

sudo apt install -y chrony

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

chronyc sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^? 192.0.1.100                   1   6     7     1    -98us[  -98us] +/-   11ms
^* time.cloudflare.com           3   6     7     1   +139us[ +163us] +/-   11ms
^+ tms04.deltatelesystems.ru     1   6     7     1   -381us[ -357us] +/-   17ms

Желательно синхронизировать время с вашим сервером или локальным сервером для кластера. В данном случае — сервер ntp. Для этого внесите в конфигурацию chrony следующие изменения:

sudo tee "/etc/chrony/chrony.conf" > /dev/null << 'EOF'
server 192.0.1.100 iburst
keyfile /etc/chrony.keys
driftfile /var/lib/chrony/chrony.drift
log tracking measurements statistics
logdir /var/log/chrony
EOF
systemctl restart chrony

Проверьте, что демон chrony подключён к нужному серверу.

chronyc sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^? 192.0.1.100                   8   6    17    37    +14us[  +70us] +/-  161us
chronyc tracking
Reference ID    : 0A80000C (ntp.local)
Stratum         : 9
Ref time (UTC)  : Wed Nov 15 11:58:52 2023
System time     : 0.000000004 seconds slow of NTP time
Last offset     : -0.000056968 seconds
RMS offset      : 0.000056968 seconds
Frequency       : 10.252 ppm fast
Residual freq   : -2.401 ppm
Skew            : 364.419 ppm
Root delay      : 0.000455358 seconds
Root dispersion : 0.010503666 seconds
Update interval : 2.1 seconds
Leap status     : Normal

1.1.4. Развёртывание узлов Postgres Pro Shardman #

Добавьте репозиторий Postgres Pro Shardman на каждом узле Postgres Pro Shardman:

  • Установите следующие пакеты:

    sudo apt install -y vim curl jq
  • Запустите указанные скрипты:

    curl -fsSL -u "<пользователь>:<пароль>" https://repo.postgrespro.ru/sdm/sdm-18/keys/pgpro-repo-add.sh > pgpro-repo-add.sh
    chmod +x pgpro-repo-add.sh

  • Задайте свой логин и пароль для репозитория pgpro-repo-add.sh:

    ex -s -c "%s/^REPOUSER=.*/REPOUSER=<пользователь>/" -c "wq" "pgpro-repo-add.sh"
    ex -s -c "%s/^PASSWORD=.*/PASSWORD=<пароль>/" -c "wq" "pgpro-repo-add.sh"

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

  • Запустите sudo pgpro-repo-add.sh:

    sudo ./pgpro-repo-add.sh

Установите пакеты (на каждом узле):

sudo apt update
sudo apt install -y postgrespro-sdm-18-server postgrespro-sdm-18-client postgrespro-sdm-18-contrib postgrespro-sdm-18-libs pg-probackup3 sdm-18-services sdm-18-tools biha-utils-sdm-18

Предположим, выбранное имя кластера — cluster0. Следующий шаг — поместить переменные окружения Postgres Pro Shardman в каталог /etc/shardman (на каждом узле):

sudo sh -c 'cat << EOF > /etc/shardman/shardmand18-cluster0.env
SDM_CLUSTER_NAME=cluster0
SDM_LOG_LEVEL=info
EOF'

Файл и каталог создаются с помощью команды sudo, однако в дальнейшем shardmanctl её не использует, поэтому доступ к файлу с переменными окружения отсутствует. Для получения доступа необходимо добавить переменные в систему через export или дать пользователю права доступа к файлу и каталогу.

Для локального пользователя (не root) добавьте путь /opt/pgpro/sdm-18/bin в переменную окружения PATH:

echo 'export PATH=$PATH:/opt/pgpro/sdm-18/bin' >> ~/.bashrc
source ~/.bashrc

1.1.5. Инициализация кластера Postgres Pro Shardman #

Осталось несколько последних шагов. Сначала включите и запустите службу shardmand (на каждом узле Postgres Pro Shardman):

  sudo systemctl start shardmand18@cluster0
  sudo systemctl status shardmand18@cluster0
  sudo systemctl enable --now shardmand18@cluster0

  ● shardmand18@cluster0.service - deployment daemon for shardman
       Loaded: loaded (/lib/systemd/system/shardmand18@.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2023-04-18 12:28:18 UTC; 2min 13s ago
     Docs: https://github.com/postgrespro/shardman
  Main PID: 618 (shardmand)
     Tasks: 10 (limit: 4571)
    Memory: 32.0M
       CPU: 422ms
   CGroup: /system.slice/system-shardmand.slice/shardmand@cluster0.service
           └─618 /opt/pgpro/sdm-18/bin/shardmand --cluster-name cluster0 --system-bus --user postgres

Сгенерируйте пример конфигурации с помощью утилит Postgres Pro Shardman (только на одном узле Postgres Pro Shardman).

  sudo -u postgres /opt/pgpro/sdm-18/bin/shardmanctl config generate > /tmp/spec.json

На этом шаге можно внести некоторые изменения в спецификацию (конфигурацию) кластера, например изменить пароль или параметр PostgreSQL shared_buffers и так далее.

Инициализируйте конфигурацию кластера в распределённом хранилище (только на одном [любом] узле Postgres Pro Shardman).

  sudo -u postgres /opt/pgpro/sdm-18/bin/shardmanctl init -f /tmp/spec.json

Ожидается такой результат:

2023-04-18T12:30:03.043Z    DEBUG   cmd/common.go:100   Waiting for metadata lock...
2023-04-18T12:30:03.048Z    DEBUG   cluster/cluster.go:365  DataDir is not specified, setting to default /var/lib/pgpro/sdm-18/data

1.1.6. Добавление узлов в кластер Postgres Pro Shardman #

Следующую команду необходимо выполнить только на одном узле Postgres Pro Shardman.

На этом шаге предполагается, что все предыдущие шаги выполнены успешно: время на всех узлах синхронизировано и демон запущен на sdm01 и sdm02. На последнем шаге выполняется команда shardmanctl:

  sudo -u postgres /opt/pgpro/sdm-18/bin/shardmanctl nodes add -n sdm01,sdm02 \
             --cluster-name cluster0 \
             --log-level debug

Ожидается такой результат:

  2023-04-18T12:43:11.300Z    DEBUG   cmd/common.go:100   Waiting for metadata lock...
2023-04-18T12:43:11.306Z    INFO    cluster/store.go:277    Checking if shardmand on all nodes have applied current cluster configuration
✓ Waiting for shardmand on node sdm01 to apply current configuration: success 0.000s
✓ Waiting for shardmand on node sdm02 to apply current configuration: success 0.000s
2023-04-18T12:43:42.336Z    INFO    add/case.go:187 Adding repgroups...
✓ waiting rg 1 config apply: done 7.014s
2023-04-18T12:43:49.444Z    DEBUG   broadcaster/worker.go:33    start broadcaster worker for repgroup id=1
2023-04-18T12:43:49.453Z    DEBUG   broadcaster/worker.go:51    repgroup 1 connect established
2023-04-18T12:43:49.453Z    DEBUG   commands/addrepgroup.go:575 waiting for extension lock...
2023-04-18T12:43:49.453Z    DEBUG   commands/addrepgroup.go:137 Loading schema into replication group rg 1
...
2023-04-18T12:44:25.665Z    DEBUG   rebalance/service.go:528    wait all tasks finish
2023-04-18T12:44:25.666Z    DEBUG   broadcaster/worker.go:75    finish broadcaster worker for repgroup id=1
2023-04-18T12:44:25.666Z    DEBUG   broadcaster/worker.go:75    finish broadcaster worker for repgroup id=2
2023-04-18T12:44:25.666Z    INFO    add/case.go:221 Successfully added nodes sdm01, sdm02 to the cluster

Сообщение «Successfully added nodes sdm01, sdm02 to the cluster» (Узлы sdm01, sdm02 успешно добавлены в кластер) означает, что всё в порядке и узлы sdm01 и sdm02 работают нормально.

1.1.7. Проверка состояния кластера Postgres Pro Shardman #

Проверьте состояние узлов кластера.

  /opt/pgpro/sdm-18/bin/shardmanctl cluster status
postgres@shrn1:/$ /opt/pgpro/sdm-18/bin/shardmanctl cluster status
RESTART REQUIRED PARAMS STATUS OK
BIHA STATUS OK
METADATA STATUS OK
SHARDMAND STATUS OK
REPLICATION GROUP STATUS OK
DICTIONARY STATUS OK
KEEPER STATUS OK
STORE STATUS OK
MASTER STATUS OK

1.1.8. Подключение к кластеру Postgres Pro Shardman #

Для подключения к кластеру получите строку подключения на любом узле кластера (sdm01 или sdm02):

  /opt/pgpro/sdm-18/bin/shardmanctl getconnstr

Пример вывода:

  dbname=postgres host=sdm01,sdm02 password=!!!CHANGE_ME!!! port=5432,5432 user=postgres

Затем попробуйте подключиться:

  psql -d 'dbname=postgres host=sdm01,sdm02 password=!!!CHANGE_ME!!! port=5432,5432 user=postgres'

Пример вывода:

  psql (18.1)
  Type "help" for help.

1.1. Quickstart Guide #

If your site administrator has not set things up in the default way, you might have some more work to do. For example, if the database server machine is a remote machine, you will need to set the PGHOST environment variable to the name of the database server machine. The environment variable PGPORT might also have to be set. The bottom line is this: if you try to start an application program and it complains that it cannot connect to the database, you should consult your site administrator or, if that is you, the documentation to make sure that your environment is properly set up. If you did not understand the preceding paragraph then read the next section.

Postgres Pro Shardman is composed of several software components:

  • PostgreSQL 18 DBMS with a set of patches.

  • Postgres Pro Shardman extension.

  • Management tools and services, including built-in shard manager to provide high availability.

  • BiHA extension.

Postgres Pro Shardman stores its configuration in the distributed storage.

The shardmand daemon monitors the cluster configuration and manages BiHA clusters, which are used to guarantee high availability of all shards. The common Postgres Pro Shardman configuration (shardmand) is stored in the distributed storage.

Currently Postgres Pro Shardman packages are available for

  • Ubuntu 22.04/24.04 (no certified edition)

  • Debian 12/13 (no certified edition)

  • ROSA Chrome 12.7 (no certified edition)

  • Red OS 7.3 (no certified edition) and Red OS 8 (both certified and no certified editions)

  • Alt 10/11 (no certified edition) and ALT SP Release 10

  • Astra Linux 1.7/1.8 and s390x (no certified edition)

1.1.1. Choosing the Packages to Install #

The table below lists all the available Postgres Pro Shardman packages.

Table 1.1. Postgres Pro Shardman Packages

Package

Description

postgrespro-sdm-18

Top-level package that installs and configures Postgres Pro Shardman for server and client systems. Do not use this package for upgrades or migrations.

Important

Installing the postgrespro-sdm-18 package can delete existing installations of Postgres Pro Shardman and PostgreSQL-based products. Similarly, this Postgres Pro Shardman installation may be automatically removed if you later install another PostgreSQL-based product.

postgrespro-sdm-18-debuginfo

Top-level package that installs debug symbols for other packages.

postgrespro-sdm-18-client

Standard client applications, such as psql or pg_dump.

postgrespro-sdm-18-client-debuginfo

Debug package.

sdm-18-services

shardmand daemon to manage Postgres Pro Shardman services.

sdm-18-tools

Command line utility to manage daemon or tools like shardmanctl.

postgrespro-sdm-18-libs

Shared libraries required to deploy client applications, including libpq; runtime libraries for ECPG processor.

postgrespro-sdm-18-libs-debuginfo

Debug package

postgrespro-sdm-18-server

Postgres Pro Shardman server and PL/pgSQL server-side programming language.

postgrespro-sdm-18-server-debuginfo

Debug package

postgrespro-sdm-18-contrib

Additional extensions and programs deployable on database servers.

postgrespro-sdm-18-contrib-debuginfo

Debug package.

postgrespro-sdm-18-devel

Header files and libraries for developing client applications and server extensions.

On Debian-based systems, this package is called postgrespro-sdm-18-dev.

postgrespro-sdm-18-devel-debuginfo

Debug package for header files.

postgrespro-sdm-18-plperl

Server-side programming language based on Perl (see Chapter 46).

postgrespro-sdm-18-plperl-debuginfo

Debug package.

postgrespro-sdm-18-plpython3

Server-side programming language based on Python 3 (see PL/Python).

postgrespro-sdm-18-plpython3-debuginfo

Debug package.

postgrespro-sdm-18-pltcl

Server-side programming language based on Tcl (see Chapter 45).

postgrespro-sdm-18-ptcl-debuginfo

Debug package.

postgrespro-sdm-18-docs

Documentation (English).

postgrespro-sdm-18-docs-ru

Documentation (Russian).

biha-utils-sdm-18

bihactl version for Golang that shardmanctl and other tools use to manage BiHA.

postgrespro-sdm-18-jit

This package provides support for Just-in-Time (JIT) compilation.

This package is available only for x86_64 architecture and only for the supported Debian and Ubuntu systems, Astra Linux 1.7/1.8, supported ALT systems.

To learn more about enabling and using JIT, see Chapter 30.

postgrespro-sdm-18-jit-debuginfo

Debug package.

pg-probackup3

pg_probackup3 utility. It is strictly prohibited to use any pg_probackup3 versions except for the one included in the Postgres Pro Shardman repository.

pg-probackup3-debuginfo

Debug package.

pgpro-controldata

pgpro_controldata application to display control information of a PostgreSQL/Postgres Pro Shardman database cluster and compatibility information for a cluster and/or server.

pgpro-pwr-sdm-18

pgpro_pwr extension that enables you to generate workload reports, which help to discover most resource-intensive activities in your database.

ppgpro-logical-slot-sdm-18

pgpro_logical_slot extension that provides the ability to continue logical replication in case a logical slot was invalidated or incorrectly deleted.


Additionally, Postgres Pro Shardman provides separate packages with debug information for some operating systems:

  • On Debian-based systems, see the postgrespro-sdm-18-dbg package.

  • On ALT Linux systems, all packages containing binary files have the corresponding -debuginfo packages.

1.1.2. Cluster Configuration #

The minimal configuration consists of two Postgres Pro Shardman nodes.

Let’s suppose that we have the following node names and IP addresses:

 192.0.1.20 sdm01 - Shardman node1
 192.0.1.21 sdm02 - Shardman node2
192.0.1.100 ntp  - local time sync server (optional)

Each node has 4Gb RAM, 20GB HDD, 2CPU and Ubuntu 22.04 installed.

1.1.3. Preparation #

1.1.3.1. Add host names to /etc/hosts #

This step must be performed on all nodes.

sudo /bin/sh -c 'cat << EOF >> /etc/hosts
192.0.1.20 sdm01
192.0.1.21 sdm02
EOF'

1.1.3.2. Time Synchronization #

This step must be performed on all nodes.

Deploy and start chrony daemon on all hosts.

sudo apt install -y chrony

By default, chrony gets the time from available servers on internet or the local time server. You can check available time servers as follows:

chronyc sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^? 192.0.1.100                   1   6     7     1    -98us[  -98us] +/-   11ms
^* time.cloudflare.com           3   6     7     1   +139us[ +163us] +/-   11ms
^+ tms04.deltatelesystems.ru     1   6     7     1   -381us[ -357us] +/-   17ms

It is desirable to synchronize time with your server or the local server for the cluster. In this case, it is the ntp server. To do this, make changes similar to the following to chrony configuration:

sudo tee "/etc/chrony/chrony.conf" > /dev/null << 'EOF'
server 192.0.1.100 iburst
keyfile /etc/chrony.keys
driftfile /var/lib/chrony/chrony.drift
log tracking measurements statistics
logdir /var/log/chrony
EOF
systemctl restart chrony

Check that chrony is connected to the appropriate server.

chronyc sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^? 192.0.1.100                   8   6    17    37    +14us[  +70us] +/-  161us
chronyc tracking
Reference ID    : 0A80000C (ntp.local)
Stratum         : 9
Ref time (UTC)  : Wed Nov 15 11:58:52 2023
System time     : 0.000000004 seconds slow of NTP time
Last offset     : -0.000056968 seconds
RMS offset      : 0.000056968 seconds
Frequency       : 10.252 ppm fast
Residual freq   : -2.401 ppm
Skew            : 364.419 ppm
Root delay      : 0.000455358 seconds
Root dispersion : 0.010503666 seconds
Update interval : 2.1 seconds
Leap status     : Normal

1.1.4. Deploy Postgres Pro Shardman Nodes #

Let’s add a Postgres Pro Shardman repository on each Postgres Pro Shardman node:

  • Install the following packages:

    sudo apt install -y vim curl jq
    

  • Run

    curl -fsSL -u "<user>:<password>" https://repo.postgrespro.ru/sdm/sdm-18/keys/pgpro-repo-add.sh > pgpro-repo-add.sh
    chmod +x pgpro-repo-add.sh
    

  • Specify your login and password for the pgpro-repo-add.sh repository.

    ex -s -c "%s/^REPOUSER=.*/REPOUSER=<user>/" -c "wq" "pgpro-repo-add.sh"
    ex -s -c "%s/^PASSWORD=.*/PASSWORD=<password>/" -c "wq" "pgpro-repo-add.sh"
    

    To include a double quote in a password, escape it with a backslash.

  • Run sudo pgpro-repo-add.sh.

    sudo ./pgpro-repo-add.sh
    

Next step is installation of packages (on each node):

sudo apt update
sudo apt install -y postgrespro-sdm-18-server postgrespro-sdm-18-client postgrespro-sdm-18-contrib postgrespro-sdm-18-libs pg-probackup3 sdm-18-services sdm-18-tools biha-utils-sdm-18

Suppose we have chosen a default cluster name of cluster0. The next step is to put Postgres Pro Shardman environment vars into the /etc/shardman directory (on each node):

sudo sh -c 'cat << EOF > /etc/shardman/shardmand18-cluster0.env
SDM_CLUSTER_NAME=cluster0
SDM_LOG_LEVEL=info
EOF'

The file and directory are created with sudo, but later shardmanctl does not use sudo, thus cannot access the file with the environment variables. To access it, either add the variables to the system with export, or grant user with access rights to the file and the directory.

For your non-root user, add /opt/pgpro/sdm-18/bin to the PATH environment variable:

echo 'export PATH=$PATH:/opt/pgpro/sdm-18/bin' >> ~/.bashrc
source ~/.bashrc

1.1.5. Initialize the Postgres Pro Shardman Cluster #

Now we have some final steps. First, enable and start the shardmand service (on each Postgres Pro Shardman node):

  sudo systemctl start shardmand18@cluster0
  sudo systemctl status shardmand18@cluster0
  sudo systemctl enable --now shardmand18@cluster0

  ● shardmand18@cluster0.service - deployment daemon for shardman
       Loaded: loaded (/lib/systemd/system/shardmand18@.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2023-04-18 12:28:18 UTC; 2min 13s ago
     Docs: https://github.com/postgrespro/shardman
  Main PID: 618 (shardmand)
     Tasks: 10 (limit: 4571)
    Memory: 32.0M
       CPU: 422ms
   CGroup: /system.slice/system-shardmand.slice/shardmand@cluster0.service
           └─618 /opt/pgpro/sdm-18/bin/shardmand --cluster-name cluster0 --system-bus --user postgres

Let’s generate a sample configuration with the Postgres Pro Shardman utilities (only on one Postgres Pro Shardman node).

  sudo -u postgres /opt/pgpro/sdm-18/bin/shardmanctl config generate > /tmp/spec.json

In this step, you can make some changes to the cluster specification (configuration), i.e., change the password or PostgreSQL shared_buffers parameter and so on.

Let's initialize the cluster configuration in the distributed storage (only on one [any] Postgres Pro Shardman node).

  sudo -u postgres /opt/pgpro/sdm-18/bin/shardmanctl init -f /tmp/spec.json

The expected output is:

2023-04-18T12:30:03.043Z    DEBUG   cmd/common.go:100   Waiting for metadata lock...
2023-04-18T12:30:03.048Z    DEBUG   cluster/cluster.go:365  DataDir is not specified, setting to default /var/lib/pgpro/sdm-18/data

1.1.6. Add Nodes to the Postgres Pro Shardman Cluster #

The following command must be executed only on one Postgres Pro Shardman node.

This step assumes that all previous steps were executed successfully: the time on all hosts is synchronized and the daemon is launched on sdm01 and sdm02. The final step should be executed with shardmanctl command as follows:

  sudo -u postgres /opt/pgpro/sdm-18/bin/shardmanctl nodes add -n sdm01,sdm02 \
             --cluster-name cluster0 \
             --log-level debug

The expected output should be:

  2023-04-18T12:43:11.300Z    DEBUG   cmd/common.go:100   Waiting for metadata lock...
2023-04-18T12:43:11.306Z    INFO    cluster/store.go:277    Checking if shardmand on all nodes have applied current cluster configuration
✓ Waiting for shardmand on node sdm01 to apply current configuration: success 0.000s
✓ Waiting for shardmand on node sdm02 to apply current configuration: success 0.000s
2023-04-18T12:43:42.336Z    INFO    add/case.go:187 Adding repgroups...
✓ waiting rg 1 config apply: done 7.014s
2023-04-18T12:43:49.444Z    DEBUG   broadcaster/worker.go:33    start broadcaster worker for repgroup id=1
2023-04-18T12:43:49.453Z    DEBUG   broadcaster/worker.go:51    repgroup 1 connect established
2023-04-18T12:43:49.453Z    DEBUG   commands/addrepgroup.go:575 waiting for extension lock...
2023-04-18T12:43:49.453Z    DEBUG   commands/addrepgroup.go:137 Loading schema into replication group rg 1
...
2023-04-18T12:44:25.665Z    DEBUG   rebalance/service.go:528    wait all tasks finish
2023-04-18T12:44:25.666Z    DEBUG   broadcaster/worker.go:75    finish broadcaster worker for repgroup id=1
2023-04-18T12:44:25.666Z    DEBUG   broadcaster/worker.go:75    finish broadcaster worker for repgroup id=2
2023-04-18T12:44:25.666Z    INFO    add/case.go:221 Successfully added nodes sdm01, sdm02 to the cluster

The “Successfully added nodes sdm01, sdm02 to the cluster” message means that everything is fine and nodes sdm01 and sdm02 are working properly.

1.1.7. Check the Postgres Pro Shardman Cluster Status #

Let's check the status of the cluster nodes.

  /opt/pgpro/sdm-18/bin/shardmanctl cluster status
postgres@shrn1:/$ /opt/pgpro/sdm-18/bin/shardmanctl cluster status
RESTART REQUIRED PARAMS STATUS OK
BIHA STATUS OK
METADATA STATUS OK
SHARDMAND STATUS OK
REPLICATION GROUP STATUS OK
DICTIONARY STATUS OK
KEEPER STATUS OK
STORE STATUS OK
MASTER STATUS OK

1.1.8. Connect to the Postgres Pro Shardman Cluster #

To connect to the cluster we should get the cluster connection string on any cluster node (sdm01 or sdm02):

  /opt/pgpro/sdm-18/bin/shardmanctl getconnstr

Output example:

  dbname=postgres host=sdm01,sdm02 password=!!!CHANGE_ME!!! port=5432,5432 user=postgres

And then let’s try to connect:

  psql -d 'dbname=postgres host=sdm01,sdm02 password=!!!CHANGE_ME!!! port=5432,5432 user=postgres'

Output example:

  psql (18.1)
  Type "help" for help.

FAQ