pgpro_tune
pgpro_tune — утилита командной строки для автоматической настройки
Синтаксис
pgpro_tune [параметр...] [ -D | --pgdata ]каталогимя_пресета
Описание #
pgpro_tune — это утилита командной строки для автоматической настройки. Оптимальные значения различных параметров конфигурации Postgres Pro зависят от оборудования. Утилита pgpro_tune собирает информацию о системе и преобразует её в набор параметров, записываемых в файл конфигурации.
Использование #
Использование pgpro_tune включено в initdb по умолчанию. Утилита запускается автоматически во время инициализации нового кластера баз данных. Это гарантирует, что для кластера будут заданы базовые параметры, наиболее точно подходящие для оборудования. Это поведение контролируется двумя параметрами initdb:
--no-tune: отключает утилиту.--tune: передаёт утилите дополнительные параметры.
Утилиту можно также запустить вручную в любое время после инициализации кластера, выполнив следующую команду:
pgpro_tune -P имя_пресетаЭто полезно после обновления оборудования, например добавления оперативной памяти или ядер процессора, или изменения характера нагрузки на СУБД. После ручного запуска утилиты примените обновлённые параметры конфигурации. В зависимости от того, какие параметры были изменены, вызовите функцию pg_reload_conf или перезапустите сервер.
По умолчанию pgpro_tune применяет пресет default.tune первым. Дополнительные пресеты можно задать с помощью параметра -P или --preset или указав имя пресета в качестве последнего аргумента командной строки. Можно использовать несколько пресетов одновременно. Они применяются последовательно в порядке, указанном в параметре -P или --preset. Пресет default.tune всегда применяется первым, кроме случаев, когда установлен параметр --no-default. Если один и тот же пресет указан несколько раз, он применяется повторно. Параметры конфигурации из пресетов изменяются инкрементально. В целях прозрачности промежуточные изменения записываются в файл конфигурации postgresql.conf.
Пресеты, не применяемые по умолчанию, имеют приоритет, так как они применяются после default.tune, и из значений, записанных в postgresql.conf, действуют только последние.
В данный момент доступны следующие пресеты по умолчанию:
default.tune: Основной на данный момент пресет, который обеспечивает различные конфигурации в зависимости от редакции и версии сервера.regress.tune: Этот пресет применяется для отладки. Он отменяет изменения, произведённые конфигурационными параметрами пресетаdefault.tune. Таким образом обеспечивается успешное выполнение регрессионных тестов, результаты которых могут различаться из-за аппаратно-зависимых настроек.1c.tune: Этот пресет содержит параметры, специфичные для 1С, некоторые из которых требуют установки plantuner. Подробную информацию о настройках Postgres Pro для решений 1С можно найти в Приложении K.extensions.tune: Этот пресет содержит дополнительные параметры для расширений. Эти параметры требуют установки других модулей (таких как pg_stat_statements).
Дополнительные параметры можно указать с помощью -O или --options для любого пресета, но для пресета по умолчанию следует использовать --default-options.
Дополнительные переменные окружения для пресета можно установить в параметре --set. Эти значения будут одинаковыми как для пресета по умолчанию, так и для всех пользовательских.
По умолчанию пресеты размещаются в каталоге share, но можно указать их расположение вручную в параметре --preset-dir.
По умолчанию pgpro_tune работает с файлом конфигурации postgresql.conf, расположенным в каталоге данных. Каталог данных можно указать с помощью -D или --pgdata, либо задать с помощью переменной окружения PGDATA. При запуске pgpro_tune в initdb утилита будет использовать каталог данных initdb.
Файл конфигурации также можно указать с помощью --config-file.
Утилита pgpro_tune записывает свои изменения в отдельный блок в конце файла конфигурации с комментарием, что он был добавлен pgpro_tune. За подробностями обратитесь к примеру пресета.
Параметры #
--config-file=имя_файлаУказывает имя основного файла конфигурации.
-Dкаталог_данных--pgdata=каталог_данныхУказывает каталог, где будет храниться кластер баз данных.
--default-options=параметрыЗадаёт параметры для стандартного пресета.
--no-defaultОтключает стандартный пресет. Обратите внимание, что в этом случае обязательно должен быть указан другой пресет либо с помощью параметра
-P, либо в качестве последнего параметра в виде имени этого пресета.-Oпараметры-пресета--options=параметры-пресетаУказывает параметры, которые необходимо передать непосредственно пресету, заданному ранее в параметре
-P, или пресету, указанному в качестве последнего параметра командной строки, если-Pне использовался.-Pимя--preset=имяУказывает имя пресета. Если указано несколько имён, пресеты выполняются по очереди с учётом вывода предыдущего пресета.
Примечание
Имя пресета может быть указано либо в этом параметре, либо в качестве последнего параметра. Использование обоих вариантов одновременно приведёт к ошибке.
--preset-dir=имяУказывает каталог, содержащий пресеты. По умолчанию пресеты находятся в каталоге
share.--set=имязначениеУстанавливает переменную окружения для пресетов.
--showПоказывает все доступные пресеты из каталога, указанного в параметре
--preset-dir, если он задан, или из каталога по умолчанию в противном случае.-V--versionВывести версию pgpro_tune и завершиться.
-?--helpПоказать справку по аргументам командной строки pgpro_tune и завершиться.
Переменные окружения #
pgpro_tune устанавливает следующие переменные окружения перед запуском пресетов.
ENABLE_CRASH_INFO— если установлена, Postgres Pro был собран с параметром--enable-crash-info.ENABLE_NLS— если установлена, Postgres Pro был собран с параметром--enable-nls.ENABLE_PGPRO_TUNE— если установлена, Postgres Pro был собран с параметром--enable-pgpro-tune.MEMMB— размер оперативной памяти в мегабайтах. Эта переменная окружения может быть не задана, если размер оперативной памяти невозможно достоверно определить.NCPU— количество процессоров. Эта переменная окружения может быть не задана, если количество процессоров невозможно достоверно определить.USE_BONJOUR— если установлена, Postgres Pro был собран с параметром--with-bonjour.USE_BSD_AUTH— если установлена, Postgres Pro был собран с параметром--with-bsd-auth.USE_ICU— если установлена, Postgres Pro был собран с параметром--with-icu.USE_LDAP— если установлена, Postgres Pro был собран с параметром--with-ldap.USE_LIBUNWIND— если установлена, Postgres Pro был собран с параметром--with-libunwind.USE_LIBXML— если установлена, Postgres Pro был собран с параметром--with-libxml.USE_LIBXSLT— если установлена, Postgres Pro был собран с параметром--with-libxslt.USE_LLVM— если установлена, Postgres Pro был собран с параметром--with-llvm.USE_LZ4— если установлена, Postgres Pro был собран с параметром--with-lz4.USE_OPENSSL— если установлена, Postgres Pro был собран с параметром--with-openssl.USE_PAM— если установлена, Postgres Pro был собран с параметром--with-pam.USE_SYSTEMD— если установлена, Postgres Pro был собран с параметром--with-systemd.USE_ZSTD— если установлена, Postgres Pro был собран с параметром--with-zstd.
Создание пресетов #
Пресет — это исполняемый файл, обычно скрипт оболочки, который преобразует информацию, передаваемую через переменные окружения, в набор параметров конфигурации.
Ожидаемый вывод пресета — набор специально отформатированных строк. Первый непробельный символ — индикатор интерпретации содержимого строки для pgpro_tune. Индикатор должен быть одним из следующих символов:
#для комментирования, остальная часть выходной строки будет записана в файл конфигурации после «#».=для замены, остальная часть выходной строки должна содержать пару параметровNAMEиVALUE(приемлемы оба варианта:NAME=VALUEиNAMEVALUE). СтрокаNAME = VALUEбудет записана в файл конфигурации. Текст послеVALUEбудет добавлен как комментарий.=+или+=для добавления, остальная часть выходной строки должна содержать пару параметровNAMEиVALUE.VALUEбудет добавлен к предыдущему действующему значению параметраNAMEсзади (=+) или спереди (+=). Если действующего значения нет,ADDработает как замена. Текст послеVALUEбудет добавлен как комментарий.-=для отмены, остальная часть выходной строки должна содержать пару параметровNAMEиVALUE. Если параметрNAMEимеет действующее значение, содержащееVALUE, оно будет удалено, а остальная часть действующего значения останется прежней. Текст послеVALUEбудет добавлен в качестве комментария. Если действующего значения нет, ничего не меняется.
Пример пресета #
Предположим, есть следующий файл конфигурации с именем test.conf:
work_mem = 4MB # Default value shared_preload_libraries = 'plantuner' search_path = '"$user",wrong_schema,public'
И следующий пресет с именем test.tune:
echo "# Adding new configuration parameters." #Replace configuration parameter value by a new one echo "work_mem = 8MB" #Append to the start of existing value echo "shared_preload_libraries += pg_stat_statements" #Append to the end of existing value echo "shared_preload_libraries =+ pg_prewarm" #Withdraw from existing value echo "search_path -= 'wrong_schema'"
Чтобы использовать этот пресет, выполните следующую команду:
pgpro_tune --config-file=/path/to/test.conf -P/path/to/test.tune --no-default
Эта команда приведёт к следующим изменениям файла конфигурации:
#------------------------------------------------------------------------------ # The following settings were added by pgpro_tune. # pgpro_tune was run with the following options: # --config-file=/path/to/test/conf -P/path/to/test/tune --no-default # The following presets were used: # "/path/to/test/tune" # At DD.MM.YYYY HH:MM:SS #------------------------------------------------------------------------------ # Adding new configuration parameters. work_mem = 8MB shared_preload_libraries = 'pg_stat_statements, plantuner' shared_preload_libraries = 'pg_stat_statements, plantuner, pg_prewarm' search_path = '"$user", public' #------------------------------------------------------------------------------ # End of settings added by pgpro_tune at DD.MM.YYYY HH:MM:SS #------------------------------------------------------------------------------
pgpro_tune
pgpro_tune — a command-line tool for automatic tuning
Synopsis
pgpro_tune [option...] [ -D | --pgdata ] directory preset_name
Description #
The pgpro_tune utility is a command-line tool for automatic tuning. Optimal values for different configuration parameters of Postgres Pro depend on the hardware configuration. The pgpro_tune utility collects information about the system and transforms it into a set of parameters written into the configuration file.
Usage #
The use of pgpro_tune is enabled in initdb by default. The utility runs automatically during initialization of a new database cluster, ensuring that the cluster is configured with hardware-appropriate baseline parameters. Two initdb options control this behavior:
--no-tune: Disables the utility.--tune: Passes additional options to the utility.
The utility can also be run manually at any time after cluster initialization by executing the following command:
pgpro_tune -P preset_name
This is useful after hardware upgrades, e.g., adding RAM or CPUs, or changes in DBMS workload characteristics. After manually running the utility, apply the updated configuration parameters. Depending on which configuration parameters were modified, either call the pg_reload_conf function, or restart the server.
By default, pgpro_tune applies the default.tune preset first. Additional presets can be specified using the -P or --preset option, or by providing the preset name as the last command-line argument. Multiple presets may be used simultaneously; they are applied sequentially in the order specified in -P or --preset. The default.tune preset is always applied first unless --no-default is specified. If the same preset appears multiple times, it is applied repeatedly. Configuration parameters from presets are modified incrementally, and for transparency, all intermediate changes are written to the postgresql.conf configuration file.
Non-default presets take precedence because they are applied after default.tune, and only the final values written to postgresql.conf take effect.
The following default presets are currently available:
default.tune: This is currently the main preset, which provides different configurations specific to the server's edition and version.regress.tune: This preset is useful for debugging purposes. It reverts changes made by thedefault.tuneconfiguration parameters to ensure that regression tests will complete successfully since their output may vary due to different hardware-specific configurations.1c.tune: This preset contains 1C-specific options, some of which require the plantuner module to be installed. For more information about configuring Postgres Pro for 1C solutions, see Appendix K.extensions.tune: This preset contains additional options for extensions. These options require other modules (such as pg_stat_statements) to be installed.
Additional options may be passed via -O or --options parameter for any preset, but for the default preset --default-options should be used.
Additional environment variables can be set for presets with the --set parameter. These values will be the same both for the default preset and all custom presets.
By default, the presets are placed in the share directory, but you can specify their location manually in the --preset-dir parameter.
By default, pgpro_tune works with the postgresql.conf configuration file located in the data directory. The data directory can be specified with -D or --pgdata, or provided with environment variable PGDATA. When runing pgpro_tune from initdb, the tool will use the data directory of initdb.
Configuration file can also be specified with --config-file.
The pgpro_tune tool writes its changes into a separate block at the end of the configuration file, which is commented as added by pgpro_tune. For details, see the example of the preset.
Options #
--config-file=filenameSpecifies the main configuration file name.
-Ddatadir--pgdata=datadirSpecifies the directory where the database cluster should be stored.
--default-options=optionsSpecifies parameters for the default preset.
--no-defaultDisables the default preset. Note that in this case another preset must be specified anyway either with the
-Poption or as the last parameter with the preset name.-Opreset-options--options=preset-optionsSpecifies options to be passed directly to the preset that was previously specified in the
-Pparameter or to the preset indicated as the last command-line parameter, if-Pwas not used.-Pname--preset=nameSpecifies the preset name. If several names are indicated, presets are executed in turn, taking into account the output of the previous preset.
Note
The preset name may be specified either with this option or as the last parameter. Using both will cause an error.
--preset-dir=nameSpecifies the directory containing presets. By default, presets are located in the
sharedirectory.--set=namevalueSets the environment variable for presets.
--showShows all available presets from the directory specified in the
--preset-diroption, if it is set, or from the default directory otherwise.-V--versionPrint the pgpro_tune version and exit.
-?--helpShow help about pgpro_tune command line arguments, and exit.
Environment variables #
pgpro_tune sets the following environment variables before running presets.
ENABLE_CRASH_INFO— if set, Postgres Pro was built with the--enable-crash-infooption.ENABLE_NLS— if set, Postgres Pro was built with the--enable-nlsoption.ENABLE_PGPRO_TUNE— if set, Postgres Pro was built with the--enable-pgpro-tuneoption.MEMMB— the RAM size in megabytes. This environment variable may not be set if it is impossible to reliably determine the RAM size.NCPU— the number of CPUs. This environment variable may not be set if it is impossible to reliably determine the number of CPUs.USE_BONJOUR— if set, Postgres Pro was built with the--with-bonjouroption.USE_BSD_AUTH— if set, Postgres Pro was built with the--with-bsd-authoption.USE_ICU— if set, Postgres Pro was built the--with-icuoption.USE_LDAP— if set, Postgres Pro was built with the--with-ldapoption.USE_LIBUNWIND— if set, Postgres Pro was built with the--with-libunwindoption.USE_LIBXML— if set, Postgres Pro was built with the--with-libxmloption.USE_LIBXSLT— if set, Postgres Pro was built with the--with-libxsltoption.USE_LLVM— if set, Postgres Pro was built with the--with-llvmoption.USE_LZ4— if set, Postgres Pro was built with the--with-lz4option.USE_OPENSSL— if set, Postgres Pro was built with the--with-openssloption.USE_PAM— if set, Postgres Pro was built with the--with-pamoption.USE_SYSTEMD— if set, Postgres Pro was built with the--with-systemdoption.USE_ZSTD— if set, Postgres Pro was built with the--with-zstdoption.
Writing presets #
A preset is an executable, usually a shell script, that transforms the information passed through environment variables into the set of configuration parameters.
The expected output of the preset is the set of specifically formatted lines. The first non-whitespace character is the indicator of the line content interpretation for pgpro_tune. The indicator should be one of the following:
#for the comment action, the rest of the output line will be written into the configuration file after '#'.=for the replace action, the rest of the output line should contain a pair of parametersNAMEandVALUE(bothNAME=VALUEandNAMEVALUEare acceptable). LineNAME = VALUEwill be written into the configuration file. The text afterVALUEwill be added as a comment.=+or+=for the add action, the rest of the output line should contain a pair of parametersNAMEandVALUE.VALUEwill be added to the previous effective value of the parameterNAMEat the back (=+) or at the front (+=). If there is no effective value, theADDaction works like the replace action. The text afterVALUEwill be added as a comment.-=for the withdraw action, the rest of the output line should contain a pair of parametersNAMEandVALUE. If theNAMEparameter has the effective value containingVALUE, it will be removed and the rest of the effective value will remain the same. The text afterVALUEwill be added as a comment. If there is no effective value, nothing happens.
Example of the preset #
Suppose you have the following configuration file called test.conf:
work_mem = 4MB # Default value shared_preload_libraries = 'plantuner' search_path = '"$user",wrong_schema,public'
And the following preset called test.tune:
echo "# Adding new configuration parameters." #Replace configuration parameter value by a new one echo "work_mem = 8MB" #Append to the start of existing value echo "shared_preload_libraries += pg_stat_statements" #Append to the end of existing value echo "shared_preload_libraries =+ pg_prewarm" #Withdraw from existing value echo "search_path -= 'wrong_schema'"
Run the following command to use this preset:
pgpro_tune --config-file=/path/to/test.conf -P/path/to/test.tune --no-default
This command will result in the following changes of the configuration file:
#------------------------------------------------------------------------------ # The following settings were added by pgpro_tune. # pgpro_tune was run with the following options: # --config-file=/path/to/test/conf -P/path/to/test/tune --no-default # The following presets were used: # "/path/to/test/tune" # At DD.MM.YYYY HH:MM:SS #------------------------------------------------------------------------------ # Adding new configuration parameters. work_mem = 8MB shared_preload_libraries = 'pg_stat_statements, plantuner' shared_preload_libraries = 'pg_stat_statements, plantuner, pg_prewarm' search_path = '"$user", public' #------------------------------------------------------------------------------ # End of settings added by pgpro_tune at DD.MM.YYYY HH:MM:SS #------------------------------------------------------------------------------