Перейти к основному содержимому

Уровень 3.0

Практика. Конфигурация сервера​

  1. Очистите предыдущие настройки в postgresql.auto.conf и перезапустите сервер:

    [postgres@ServerName ~]$ psql -U postgres -h localhost
    psql (15.5)
    Type "help" for help.
    postgres@postgres=# ALTER SYSTEM RESET ALL;
    ALTER SYSTEM
    postgres@postgres=# \q
    [postgres@ServerName ~] exit
    [student@ServerName ~]$ sudo systemctl restart postgresql
    Примечание

    Перезапуск сервера потребовался для применения значений сброшенных параметров. Перезапуск выполнен командой systemctl restart, поскольку ранее был создан и запущен сервис systemd для экземпляра СУБД Pangolin.

    Если экземпляр был запущен командой pg_ctl start, его перезапуск необходимо выполнить командой pg_ctl restart от имени пользователя postgres.

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

    [postgres@ServerName ~]$ psql -U postgres -h localhost
    psql (15.5)
    Type "help" for help.
    postgres@postgres=# SELECT context, count(*) FROM pg_settings GROUP BY context ORDER BY 2;
    context | count
    -------------------+-------
    backend | 2
    superuser-backend | 4
    internal | 22
    superuser | 65
    user | 160
    postmaster | 164
    sighup | 170
    (7 rows)

Представление pg_file_settings​

  1. Получите список всех параметров, имеющих контекст superuser (из может изменять только суперпользователь) и значения которых установлены в конфигурационных файлах:

    postgres@postgres=# SELECT fs.sourcefile, fs.sourceline, fs.name FROM pg_file_settings fs, pg_settings st
    WHERE fs.name = st.name AND st.context = 'superuser';
    sourcefile | sourceline | name
    ---------------------------------+------------+-------------
    /pgdata/06/data/postgresql.conf | 741 | lc_messages
    (1 row)
  2. Запустите оболочку Bash от имени postgres. Скопируйте конфигурационный файл postgresql.conf:

    [postgres@ServerName ~]$ cd $PGDATA
    [postgres@ServerName data]$ cp -v postgresql.conf{,.orig}
    'postgresql.conf' -> 'postgresql.conf.orig'
  3. Закомментируйте все строки, начинающиеся с include в postgresql.conf. Проверьте с помощью grep:

    [postgres@ServerName ~]$ sed -i 's/^include/#include/' postgresql.conf
    [postgres@ServerName ~]$ grep include postgresql.conf
    # can include strftime() escapes
    #include_dir = '...' # include files ending in '.conf' from
    #include_if_exists = '...' # include file only if it exists
    #include = '...' # include file
    # Can include strftime() escapes.
  4. Добавьте в конец файла postgresql.conf директиву include_dir и выйдите из сеанса пользователя postgres:

    [postgres@ServerName ~]$ echo "include_dir '/etc/pangolin/lab_conf'" >> postgresql.conf
    [postgres@ServerName ~]$ tail -1 postgresql.conf
    include_dir '/etc/pangolin/lab_conf'
    [postgres@ServerName ~]$ exit
    logout
  5. Создайте каталог /etc/pangolin/lab_conf и назначьте его владельцем пользователя ОС postgres:

    [student@ServerName ~]$ sudo mkdir -p /etc/pangolin/lab_conf
    [student@ServerName ~]$ sudo chown postgres:postgres /etc/pangolin/lab_conf
    [student@ServerName ~]$ ls -ld /etc/pangolin/lab_conf
    drwxr-xr-x 2 postgres postgres 4096 Nov 8 20:42 /etc/pangolin/lab_conf
  6. Запишите в файл /etc/pangolin/lab_conf/lab.conf настройки для размера кеша буферов 512MB и рабочей памяти для обслуживания 128MB:

    [student@ServerName ~]$ sudo vi /etc/pangolin/lab_conf/lab.conf
    shared_buffers = 512MB
    maintenance_work_mem = 128MB
  7. Зайдите в сеанс psql пользователем postgres. Проверьте, что показывает pg_file_settings для настройки shared_buffers и maintenance_work_mem:

    [postgres@ServerName ~]$ psql -U postgres -h localhost
    postgres@postgres=# SELECT * FROM pg_file_settings WHERE name ~ 'shared_buffers|work_mem';
    sourcefile | sourceline | seqno | name | setting | applied | error
    ---------------------------------+------------+-------+----------------------+---------+---------+------------------------------
    /pgdata/06/data/postgresql.conf | 136 | 2 | shared_buffers | 128MB | f |
    /etc/pangolin/lab_conf/lab.conf | 1 | 22 | shared_buffers | 512MB | f | setting could not be applied
    /etc/pangolin/lab_conf/lab.conf | 2 | 23 | maintenance_work_mem | 128MB | t |
    (3 rows)

    Для параметра shared_buffers из файла lab.conf в поле error выводится сообщение setting could not be applied, а в поле applied — false. Причина в контексте этой настройки — postmaster. Необходимо перезапустить сервер.

    Для параметра maintenance_work_mem в поле applied — true, что значит, что он может быть применен.

  8. Получите текущие значения параметров shared_buffers и maintenance_work_mem. Затем перечитайте их и проверьте снова:

    postgres@postgres=# \dconfig shared_buffers|m*work_mem
    List of configuration parameters
    Parameter | Value
    ----------------------+-------
    maintenance_work_mem | 64MB
    shared_buffers | 128MB
    (2 rows)
    postgres=# SELECT pg_reload_conf();
    pg_reload_conf
    ----------------
    t
    (1 row)
    postgres@postgres=# \dconfig shared_buffers|m*work_mem
    List of configuration parameters
    Parameter | Value
    ----------------------+-------
    maintenance_work_mem | 128MB
    shared_buffers | 128MB
    (2 rows)

    Параметр maintenance_work_mem применился сразу после перечитывания конфигурации, так как он имеет контекст user, а изменение параметра shared_buffers требует перезапуск сервера (контекст — postmaster).

  9. Перезапустите экземпляр и проверьте параметр shared_buffers снова:

    postgres=# \q
    [student@ServerName ~]$ sudo systemctl restart postgresql
    [postgres@ServerName ~]$ psql -U postgres -h localhost
    psql (15.5)
    Type "help" for help.
    postgres@postgres=# SELECT * FROM pg_file_settings WHERE name = 'shared_buffers';
    sourcefile | sourceline | seqno | name | setting | applied | error
    ---------------------------------+------------+-------+----------------+---------+---------+-------
    /pgdata/06/data/postgresql.conf | 136 | 2 | shared_buffers | 128MB | f |
    /etc/pangolin/lab_conf/lab.conf | 1 | 22 | shared_buffers | 512MB | t |
    (2 rows)
    postgres@postgres=# SHOW shared_buffers;
    shared_buffers
    ----------------
    512MB
    (1 row)

    Параметр успешно применен.

  10. Добавьте в файл /etc/pangolin/lab_conf/lab.conf заведомо неверную настройку и проверьте содержимое pg_file_settings:

    postgres@postgres=# \q
    [postgres@ServerName ~]$ vi /etc/pangolin/lab_conf/lab.conf
    shared_buffers = mb
    [postgres@ServerName ~]$ psql -U postgres -h localhost
    psql (15.5)
    Type "help" for help.
    postgres@postgres=# SELECT * FROM pg_file_settings WHERE name = 'shared_buffers';
    sourcefile | sourceline | seqno | name | setting | applied | error
    ---------------------------------+------------+-------+----------------+---------+---------+------------------------------
    /pgdata/06/data/postgresql.conf | 136 | 2 | shared_buffers | 128MB | f |
    /etc/pangolin/lab_conf/lab.conf | 1 | 22 | shared_buffers | 512MB | f |
    /etc/pangolin/lab_conf/lab.conf | 3 | 24 | shared_buffers | mb | f | setting could not be applied
    (3 rows)
  11. Попробуйте перезапустить сервер:

    postgres@postgres=# \q
    [student@ServerName ~]$ sudo systemctl restart postgresql
    Job for postgresql.service failed because the control process exited with error code.
    See "systemctl status postgresql.service" and "journalctl -xe" for details.

    Это привело к ошибке, так как в конфигурации присутствует некорректное значение.

  12. Восстановите настройки в postgresql.conf из копии и перезапустите сервер:

    [student@ServerName ~]$ sudo -u postgres cp -v $PGDATA/postgresql.conf{.orig,}
    '/pgdata/06/data/postgresql.conf.orig' -> '/pgdata/06/data/postgresql.conf'
    [student@ServerName ~]$ sudo systemctl restart postgresql

Команда ALTER SYSTEM​

  1. Запустите сеанс Bash от имени postgres и перейдите в каталог PGDATA. Выведите содержимое postgresql.auto.conf:

    [student@ServerName ~]$ sudo su - postgres
    [postgres@ServerName ~]$ cd $PGDATA
    [postgres@ServerName data]$ cat postgresql.auto.conf
    # Do not edit this file manually!
    # It will be overwritten by the ALTER SYSTEM command.
  2. Командой ALTER SYSTEM установите значение shared_buffers равным 256MB:

    [postgres@ServerName data]$ psql -c "ALTER SYSTEM SET shared_buffers TO '256MB'"
    ALTER SYSTEM
    [postgres@ServerName data]$ psql -c "SELECT * FROM pg_file_settings WHERE name = 'shared_buffers'"
    sourcefile | sourceline | seqno | name | setting | applied | error
    --------------------------------------+------------+-------+----------------+---------+---------+------------------------------
    /pgdata/06/data/postgresql.conf | 136 | 2 | shared_buffers | 128MB | f |
    /pgdata/06/data/postgresql.auto.conf | 3 | 22 | shared_buffers | 256MB | f | setting could not be applied
    (2 rows)
  3. Проверьте, что записалось в postgresql.auto.conf:

    [postgres@ServerName data]$ cat postgresql.auto.conf
    # Do not edit this file manually!
    # It will be overwritten by the ALTER SYSTEM command.
    shared_buffers = '256MB'
  4. Снова повторите настройку для shared_buffers, но установите теперь значение 512MB. Проверьте содержимое postgresql.auto.conf:

    [postgres@ServerName data]$ psql -c "ALTER SYSTEM SET shared_buffers TO '512MB'"
    ALTER SYSTEM
    [postgres@ServerName data]$ cat postgresql.auto.conf
    # Do not edit this file manually!
    # It will be overwritten by the ALTER SYSTEM command.
    shared_buffers = '512MB'

    Обратите внимание на то, что предыдущая настройка со значением 256MB удалена.

  5. С помощью ALTER SYSTEM установите значение 8MB для параметра work_mem. Проверьте содержимое postgresql.auto.conf:

    [postgres@ServerName data]$ psql -c "ALTER SYSTEM SET work_mem TO '8MB'"
    ALTER SYSTEM
    [postgres@ServerName data]$ cat postgresql.auto.conf
    # Do not edit this file manually!
    # It will be overwritten by the ALTER SYSTEM command.
    shared_buffers = '512MB'
    work_mem = '8MB'
  6. Сбросьте значение параметра shared_buffers. Проверьте содержимое postgresql.auto.conf:

    [postgres@ServerName data]$ psql -c "ALTER SYSTEM RESET shared_buffers"
    ALTER SYSTEM
    [postgres@ServerName data]$ cat postgresql.auto.conf
    # Do not edit this file manually!
    # It will be overwritten by the ALTER SYSTEM command.
    work_mem = '8MB'
  7. Сбросьте значения всех параметров:

    [postgres@ServerName data]$ psql -c "ALTER SYSTEM RESET ALL"
    ALTER SYSTEM
    [postgres@ServerName data]$ cat postgresql.auto.conf
    # Do not edit this file manually!
    # It will be overwritten by the ALTER SYSTEM command.

Представление pg_settings​

  1. Отредактируйте файл postgresql.conf так, чтобы параметр work_mem имел значение 8MB:

    [postgres@ServerName ~]$ cd $PGDATA
    [postgres@ServerName data]$ sed -i.bak 's/^#work_mem.*$/work_mem = 8MB/' postgresql.conf
  2. Проверьте этот параметр в pg_file_settings и pg_settings:

    [postgres@ServerName data]$ psql
    psql (15.5)
    Type "help" for help.
    postgres@postgres=# SELECT * FROM pg_file_settings WHERE name = 'work_mem' \gx
    -[ RECORD 1 ]-------------------------------
    sourcefile | /pgdata/06/data/postgresql.conf
    sourceline | 147
    seqno | 3
    name | work_mem
    setting | 8MB
    applied | t
    error |
    postgres@postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx
    -[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------
    name | work_mem
    setting | 4096
    unit | kB
    category | Resource Usage / Memory
    short_desc | Sets the maximum memory to be used for query workspaces.
    extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.
    context | user
    vartype | integer
    source | default
    min_val | 64
    max_val | 2147483647
    enumvals |
    boot_val | 4096
    reset_val | 4096
    sourcefile |
    sourceline |
    pending_restart | f
    postgres@postgres=# SHOW work_mem;
    work_mem
    ----------
    4MB
    (1 row)

    Параметр записан в конфигурационный файл (pg_file_settings показывает applied = t), но текущее значение (pg_settings и SHOW) осталось прежним – 4MB. Это связано с тем, что изменение было внесено в файл, но сервер его еще не применил. Контекст параметра user требует перечитать конфигурацию.

  3. Перечитайте конфигурацию и проверьте pg_settings:

    postgres@postgres=# SELECT pg_reload_conf();
    pg_reload_conf
    ----------------
    t
    (1 row)
    postgres@postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx
    -[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------
    name | work_mem
    setting | 8192
    unit | kB
    category | Resource Usage / Memory
    short_desc | Sets the maximum memory to be used for query workspaces.
    extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.
    context | user
    vartype | integer
    source | configuration file
    min_val | 64
    max_val | 2147483647
    enumvals |
    boot_val | 4096
    reset_val | 8192
    sourcefile | /pgdata/06/data/postgresql.conf
    sourceline | 147
    pending_restart | f

    Значение по умолчанию 4096kB, текущее значение 8192kB, а в поле source указано configuration file.

    Если в сессии сделать RESET work_mem, то значение будет 8MB, поскольку оно установлено в postgresql.conf.

Сессионные параметры​

  1. Установите в текущей сессии значение параметра work_mem, равное 16MB, и проверьте pg_settings:

    postgres@postgres=# SET work_mem TO '16MB';
    SET
    postgres@postgres=# \dconfig+ work_mem
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    -----------+-------+---------+---------+-------------------
    work_mem | 16MB | integer | user |
    (1 row)
    postgres@postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx
    -[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------
    name | work_mem
    setting | 16384
    unit | kB
    category | Resource Usage / Memory
    short_desc | Sets the maximum memory to be used for query workspaces.
    extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.
    context | user
    vartype | integer
    source | session
    min_val | 64
    max_val | 2147483647
    enumvals |
    boot_val | 4096
    reset_val | 8192
    sourcefile |
    sourceline |
    pending_restart | f
  2. Перезапустите сессию и снова проверьте pg_settings:

    postgres@postgres=# \c
    You are now connected to database "postgres" as user "postgres".
    postgres@postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx
    -[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------
    name | work_mem
    setting | 8192
    unit | kB
    category | Resource Usage / Memory
    short_desc | Sets the maximum memory to be used for query workspaces.
    extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.
    context | user
    vartype | integer
    source | configuration file
    min_val | 64
    max_val | 2147483647
    enumvals |
    boot_val | 4096
    reset_val | 8192
    sourcefile | /pgdata/06/data/postgresql.conf
    sourceline | 147
    pending_restart | f

    Параметр сессионный, поэтому был сброшен при перезапуске сессии.

Транзакционные параметры​

  1. Установите значение параметра work_mem, равное 16MB, в транзакции. Проверьте значение во время транзакции и после ее отката:

    postgres@postgres=# BEGIN;
    BEGIN
    postgres@postgres=*# SET work_mem = '16MB';
    SET
    postgres@postgres=*# \dconfig+ work_mem
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    -----------+-------+---------+---------+-------------------
    work_mem | 16MB | integer | user |
    (1 row)
    postgres@postgres=*# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx
    -[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------
    name | work_mem
    setting | 16384
    unit | kB
    category | Resource Usage / Memory
    short_desc | Sets the maximum memory to be used for query workspaces.
    extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files.
    context | user
    vartype | integer
    source | session
    min_val | 64
    max_val | 2147483647
    enumvals |
    boot_val | 4096
    reset_val | 8192
    sourcefile |
    sourceline |
    pending_restart | f
    postgres@postgres=*# ROLLBACK;
    ROLLBACK
    postgres@postgres=# \dconfig+ work_mem
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    -----------+-------+---------+---------+-------------------
    work_mem | 8MB | integer | user |
    (1 row)

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

  2. Запустите транзакцию, установите в ней два параметра командой SET, но для одного параметра добавьте LOCAL. Далее зафиксируйте транзакцию и проверьте значения параметров после фиксации:

    postgres@postgres=# \dconfig+ (work|hash)_mem*
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    ---------------------+-------+---------+---------+-------------------
    hash_mem_multiplier | 2 | real | user |
    work_mem | 8MB | integer | user |
    (2 rows)
    postgres@postgres=# BEGIN;
    BEGIN
    postgres@postgres=*# SET work_mem = '16MB';
    SET
    postgres@postgres=*# SET LOCAL hash_mem_multiplier = 3;
    SET
    postgres@postgres=*# \dconfig+ (work|hash)_mem*
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    ---------------------+-------+---------+---------+-------------------
    hash_mem_multiplier | 3 | real | user |
    work_mem | 16MB | integer | user |
    (2 rows)
    postgres@postgres=*# COMMIT;
    COMMIT
    postgres@postgres=# \dconfig+ (work|hash)_mem*
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    ---------------------+-------+---------+---------+-------------------
    hash_mem_multiplier | 2 | real | user |
    work_mem | 16MB | integer | user |
    (2 rows)

    После фиксации транзакции значение установленного в транзакции параметра work_mem так и осталось 16MB, а значение установленного командой SET LOCAL параметра hash_mem_multiplier вернулось к исходному значению.

  3. Выполните команду RESET для параметра work_mem и получите его значение после этого:

    postgres@postgres=# RESET work_mem;
    RESET
    postgres@postgres=# \dconfig+ work_mem
    List of configuration parameters
    Parameter | Value | Type | Context | Access privileges
    -----------+-------+---------+---------+-------------------
    work_mem | 8MB | integer | user |
    (1 row)
  4. Выйдите из среды psql и сеанса пользователя postgres:

    postgres@postgres=# \q
    [postgres@ServerName ~]$ exit
    logout

Самопроверка​

Вопрос 1

В сеансе psql последовательно выполнены следующие команды:

postgres=# SELECT name, setting, unit, context FROM pg_settings WHERE name = 'max_wal_size';
name     | setting | unit | context
--------------+---------+------+---------
max_wal_size | 1024    | MB   | sighup
(1 строка)

postgres=# SELECT sourcefile, name, setting, applied FROM pg_file_settings WHERE name = 'max_wal_size';
sourcefile                    |     name     | setting | applied
--------------------------------------------------+--------------+---------+---------
/pgdata/06/data/postgresql.conf                  | max_wal_size | 2GB     | f
/pgdata/06/data/postgresql.conf                  | max_wal_size | 1GB     | f
/pgdata/06/data/postgresql.auto.conf             | max_wal_size | 512MB   | t
(2 строки)

postgres=# SHOW max_wal_size;
(1 строка)

Известно, что параллельная настройка конфигурационных параметров не выполнялась.

Какое значение параметра max_wal_size будет выведено в результате выполнения последней команды?

Вопрос 2

В сеансе psql последовательно выполнены следующие команды:

postgres=# SELECT name, setting, unit, context FROM pg_settings WHERE name='shared_buffers';
name      | setting | unit |  context
----------------+---------+------+------------
shared_buffers | 16384   | 8kB  | postmaster
(1 строка)

postgres=# ALTER SYSTEM SET shared_buffers TO '512MB';
ALTER SYSTEM

postgres=# SELECT pg_reload_conf();
pg_reload_conf
----------------
t
(1 строка)

postgres=# ALTER SYSTEM SET shared_buffers TO '1GB';
ALTER SYSTEM

postgres=# SHOW shared_buffers;

Известно, что параллельная настройка конфигурационных параметров не выполнялась.

Какое значение параметра shared_buffers будет выведено в результате выполнения последней команды?

Вопрос 3

В сеансе psql последовательно выполнены следующие команды:

postgres=# \dconfig work_mem
Список параметров конфигурации
Параметр | Значение
----------+----------
work_mem | 4MB
(1 строка)

postgres=# SET work_mem TO '8MB';
SET
postgres=# \c
You are now connected to database "postgres" as user "postgres".

postgres=# SHOW work_mem;

Какое значение параметра shared_buffers будет выведено в результате выполнения последней команды?

Вопрос 4

В сеансе psql последовательно выполнены следующие команды:

postgres=# \dconfig work_mem
Список параметров конфигурации
Параметр | Значение
----------+----------
work_mem | 4MB
(1 строка)

postgres=# SET work_mem TO '6MB';
SET

postgres=# BEGIN;
BEGIN

postgres=*# SET work_mem TO '8MB';
SET

postgres=*# COMMIT;
COMMIT

postgres=# \dconfig work_mem

Какое значение параметра shared_buffers будет выведено в результате выполнения последней команды?