Уровень 3.0
Практика. Конфигурация сервера
-
Очистите предыдущие настройки в
postgresql.auto.confи перезапустите сервер:[postgres@ServerName ~]$ psql -U postgres -h localhostpsql (15.5)Type "help" for help.postgres@postgres=# ALTER SYSTEM RESET ALL;ALTER SYSTEMpostgres@postgres=# \q[postgres@ServerName ~] exit[student@ServerName ~]$ sudo systemctl restart postgresqlПримечаниеПерезапуск сервера потребовался для применения значений сброшенных параметров. Перезапуск выполнен командой
systemctl restart, поскольку ранее был создан и запущен сервисsystemdдля экземпляра СУБД Pangolin.Если экземпляр был запущен командой
pg_ctl start, его перезапуск необходимо выполнить командойpg_ctl restartот имени пользователяpostgres. -
Подсчитайте количество параметров конфигурации для каждого контекста, отсортировав по возрастанию суммарного количества параметров в контекстах:
[postgres@ServerName ~]$ psql -U postgres -h localhostpsql (15.5)Type "help" for help.postgres@postgres=# SELECT context, count(*) FROM pg_settings GROUP BY context ORDER BY 2;context | count-------------------+-------backend | 2superuser-backend | 4internal | 22superuser | 65user | 160postmaster | 164sighup | 170(7 rows)
Представление pg_file_settings
-
Получите список всех параметров, имеющих контекст
superuser(из может изменять только суперпользователь) и значения которых установлены в конфигурационных файлах:postgres@postgres=# SELECT fs.sourcefile, fs.sourceline, fs.name FROM pg_file_settings fs, pg_settings stWHERE fs.name = st.name AND st.context = 'superuser';sourcefile | sourceline | name---------------------------------+------------+-------------/pgdata/06/data/postgresql.conf | 741 | lc_messages(1 row) -
Запустите оболочку Bash от имени
postgres. Скопируйте конфигурационный файлpostgresql.conf:[postgres@ServerName ~]$ cd $PGDATA[postgres@ServerName data]$ cp -v postgresql.conf{,.orig}'postgresql.conf' -> 'postgresql.conf.orig' -
Закомментируйте все строки, начинающиеся с
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. -
Добавьте в конец файла
postgresql.confдирективуinclude_dirи выйдите из сеанса пользователяpostgres:[postgres@ServerName ~]$ echo "include_dir '/etc/pangolin/lab_conf'" >> postgresql.conf[postgres@ServerName ~]$ tail -1 postgresql.confinclude_dir '/etc/pangolin/lab_conf'[postgres@ServerName ~]$ exitlogout -
Создайте каталог
/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_confdrwxr-xr-x 2 postgres postgres 4096 Nov 8 20:42 /etc/pangolin/lab_conf -
Запишите в файл
/etc/pangolin/lab_conf/lab.confнастройки для размера кеша буферов512MBи рабочей памяти для обслуживания128MB:[student@ServerName ~]$ sudo vi /etc/pangolin/lab_conf/lab.confshared_buffers = 512MBmaintenance_work_mem = 128MB -
Зайдите в сеанс psql пользователем
postgres. Проверьте, что показываетpg_file_settingsдля настройкиshared_buffersиmaintenance_work_mem:[postgres@ServerName ~]$ psql -U postgres -h localhostpostgres@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, что значит, что он может быть применен. -
Получите текущие значения параметров
shared_buffersиmaintenance_work_mem. Затем перечитайте их и проверьте снова:postgres@postgres=# \dconfig shared_buffers|m*work_memList of configuration parametersParameter | Value----------------------+-------maintenance_work_mem | 64MBshared_buffers | 128MB(2 rows)postgres=# SELECT pg_reload_conf();pg_reload_conf----------------t(1 row)postgres@postgres=# \dconfig shared_buffers|m*work_memList of configuration parametersParameter | Value----------------------+-------maintenance_work_mem | 128MBshared_buffers | 128MB(2 rows)Параметр
maintenance_work_memприменился сразу после перечитывания конфигурации, так как он имеет контекстuser, а изменение параметраshared_buffersтребует перезапуск сервера (контекст —postmaster). -
Перезапустите экземпляр и проверьте параметр
shared_buffersснова:postgres=# \q[student@ServerName ~]$ sudo systemctl restart postgresql[postgres@ServerName ~]$ psql -U postgres -h localhostpsql (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)Параметр успешно применен.
-
Добавьте в файл
/etc/pangolin/lab_conf/lab.confзаведомо неверную настройку и проверьте содержимоеpg_file_settings:postgres@postgres=# \q[postgres@ServerName ~]$ vi /etc/pangolin/lab_conf/lab.confshared_buffers = mb[postgres@ServerName ~]$ psql -U postgres -h localhostpsql (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) -
Попробуйте перезапустить сервер:
postgres@postgres=# \q[student@ServerName ~]$ sudo systemctl restart postgresqlJob for postgresql.service failed because the control process exited with error code.See "systemctl status postgresql.service" and "journalctl -xe" for details.Это привело к ошибке, так как в конфигурации присутствует некорректное значение.
-
Восстановите настройки в
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
-
Запустите сеанс 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. -
Командой
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) -
Проверьте, что записалось в
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' -
Снова повторите настройку для
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удалена. -
С помощью
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' -
Сбросьте значение параметра
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' -
Сбросьте значения всех параметров:
[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
-
Отредактируйте файл
postgresql.confтак, чтобы параметрwork_memимел значение8MB:[postgres@ServerName ~]$ cd $PGDATA[postgres@ServerName data]$ sed -i.bak 's/^#work_mem.*$/work_mem = 8MB/' postgresql.conf -
Проверьте этот параметр в
pg_file_settingsиpg_settings:[postgres@ServerName data]$ psqlpsql (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.confsourceline | 147seqno | 3name | work_memsetting | 8MBapplied | terror |postgres@postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx-[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------name | work_memsetting | 4096unit | kBcategory | Resource Usage / Memoryshort_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 | uservartype | integersource | defaultmin_val | 64max_val | 2147483647enumvals |boot_val | 4096reset_val | 4096sourcefile |sourceline |pending_restart | fpostgres@postgres=# SHOW work_mem;work_mem----------4MB(1 row)Параметр записан в конфигурационный файл (
pg_file_settingsпоказываетapplied = t), но текущее значение (pg_settingsиSHOW) осталось прежним –4MB. Это связано с тем, что изменение было внесено в файл, но сервер его еще не применил. Контекст параметраuserтребует перечитать конфигурацию. -
Перечитайте конфигурацию и проверьте
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_memsetting | 8192unit | kBcategory | Resource Usage / Memoryshort_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 | uservartype | integersource | configuration filemin_val | 64max_val | 2147483647enumvals |boot_val | 4096reset_val | 8192sourcefile | /pgdata/06/data/postgresql.confsourceline | 147pending_restart | fЗначение по умолчанию
4096kB, текущее значение8192kB, а в полеsourceуказаноconfiguration file.Если в сессии сделать
RESET work_mem, то значение будет8MB, поскольку оно установлено вpostgresql.conf.
Сессионные параметры
-
Установите в текущей сессии значение параметра
work_mem, равное16MB, и проверьтеpg_settings:postgres@postgres=# SET work_mem TO '16MB';SETpostgres@postgres=# \dconfig+ work_memList of configuration parametersParameter | 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_memsetting | 16384unit | kBcategory | Resource Usage / Memoryshort_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 | uservartype | integersource | sessionmin_val | 64max_val | 2147483647enumvals |boot_val | 4096reset_val | 8192sourcefile |sourceline |pending_restart | f -
Перезапустите сессию и снова проверьте
pg_settings:postgres@postgres=# \cYou are now connected to database "postgres" as user "postgres".postgres@postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem' \gx-[ RECORD 1 ]---+----------------------------------------------------------------------------------------------------------------------name | work_memsetting | 8192unit | kBcategory | Resource Usage / Memoryshort_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 | uservartype | integersource | configuration filemin_val | 64max_val | 2147483647enumvals |boot_val | 4096reset_val | 8192sourcefile | /pgdata/06/data/postgresql.confsourceline | 147pending_restart | fПараметр сессионный, поэтому был сброшен при перезапуске сессии.
Транзакционные параметры
-
Установите значение параметра
work_mem, равное16MB, в транзакции. Проверьте значение во время транзакции и после ее отката:postgres@postgres=# BEGIN;BEGINpostgres@postgres=*# SET work_mem = '16MB';SETpostgres@postgres=*# \dconfig+ work_memList of configuration parametersParameter | 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_memsetting | 16384unit | kBcategory | Resource Usage / Memoryshort_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 | uservartype | integersource | sessionmin_val | 64max_val | 2147483647enumvals |boot_val | 4096reset_val | 8192sourcefile |sourceline |pending_restart | fpostgres@postgres=*# ROLLBACK;ROLLBACKpostgres@postgres=# \dconfig+ work_memList of configuration parametersParameter | Value | Type | Context | Access privileges-----------+-------+---------+---------+-------------------work_mem | 8MB | integer | user |(1 row)Транзакция не зафиксирована — был откат, поэтому при выходе из нее значение параметра, установленного в этой транзакции, было сброшено.
-
Запустите транзакцию, установите в ней два параметра командой
SET, но для одного параметра добавьтеLOCAL. Далее зафиксируйте транзакцию и проверьте значения параметров после фиксации:postgres@postgres=# \dconfig+ (work|hash)_mem*List of configuration parametersParameter | Value | Type | Context | Access privileges---------------------+-------+---------+---------+-------------------hash_mem_multiplier | 2 | real | user |work_mem | 8MB | integer | user |(2 rows)postgres@postgres=# BEGIN;BEGINpostgres@postgres=*# SET work_mem = '16MB';SETpostgres@postgres=*# SET LOCAL hash_mem_multiplier = 3;SETpostgres@postgres=*# \dconfig+ (work|hash)_mem*List of configuration parametersParameter | Value | Type | Context | Access privileges---------------------+-------+---------+---------+-------------------hash_mem_multiplier | 3 | real | user |work_mem | 16MB | integer | user |(2 rows)postgres@postgres=*# COMMIT;COMMITpostgres@postgres=# \dconfig+ (work|hash)_mem*List of configuration parametersParameter | 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вернулось к исходному значению. -
Выполните команду
RESETдля параметраwork_memи получите его значение после этого:postgres@postgres=# RESET work_mem;RESETpostgres@postgres=# \dconfig+ work_memList of configuration parametersParameter | Value | Type | Context | Access privileges-----------+-------+---------+---------+-------------------work_mem | 8MB | integer | user |(1 row) -
Выйдите из среды psql и сеанса пользователя
postgres:postgres@postgres=# \q[postgres@ServerName ~]$ exitlogout
Самопроверка
Вопрос 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 будет выведено в результате выполнения последней команды?