pgpro_tune
pgpro_tune — утилита командной строки для автоматической настройки
Синтаксис
pgpro_tune [параметр...] [ -D | --pgdata ]каталогимя_пресета
Описание #
pgpro_tune — это утилита командной строки для автоматической настройки. Оптимальные значения различных параметров конфигурации Postgres Pro зависят от оборудования. Утилита pgpro_tune собирает информацию о системе и преобразует её в набор параметров, записываемых в файл конфигурации.
Использование #
Использование pgpro_tune включено в initdb по умолчанию. Для этой утилиты предусмотрено два параметра initdb: --no-tune отключает её использование, --tune=OPTIONS позволяет передавать дополнительные параметры для запуска pgpro_tune.
Сначала pgpro_tune запускает стандартный пресет. Дополнительные пресеты могут быть заданы с помощью параметра -P или --preset=NAME, или путём указания имени пресета в качестве последнего аргумента командной строки. Чтобы отключить стандартный пресет, используйте параметр --no-default.
В данный момент доступны следующие пресеты по умолчанию:
default.tune: Основной на данный момент пресет, который обеспечивает различные конфигурации в зависимости от редакции и версии сервера.regress.tune: Этот пресет применяется для отладки. Он отменяет изменения, произведённые конфигурационными параметрами пресетаdefault.tune. Таким образом обеспечивается успешное выполнение регрессионных тестов, результаты которых могут различаться из-за аппаратно-зависимых настроек.1c.tune: Этот пресет содержит параметры, специфичные для 1С, некоторые из которых требуют установки plantuner. Подробную информацию о настройках Postgres Pro для решений 1С можно найти в Приложении K.extensions.tune: Этот пресет содержит дополнительные параметры для расширений. Эти параметры требуют установки других модулей (таких как pgpro_stats).
Дополнительные параметры можно указать с помощью -O или --options=OPTIONS для любого пресета, но для пресета по умолчанию следует использовать --default-options=OPTIONS.
Дополнительные переменные окружения для пресета можно установить в параметре --set NAME=VALUE. Эти значения будут одинаковыми как для пресета по умолчанию, так и для всех пользовательских.
По умолчанию пресеты размещаются в каталоге share, но можно указать их расположение вручную в параметре --preset-dir=NAME.
По умолчанию pgpro_tune работает с файлом конфигурации postgresql.conf, расположенным в каталоге данных. Каталог данных можно указать с помощью -D или --pgdata=DATADIR, либо задать с помощью переменной окружения PGDATA. При запуске pgpro_tune в initdb утилита будет использовать каталог данных initdb.
Файл конфигурации также можно указать с помощью --config-file=FILENAME.
Утилита 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.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: # --no-default --config-file=/path/to/test/conf -P/path/to/test/tune --no-default # At YYYY-MM-DD 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 YYYY-MM-DD 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. There are two initdb options for this tool: --no-tune disables its usage, --tune=OPTIONS allows passing additional options for the pgpro_tune run.
First pgpro_tune runs the default preset. Additional presets may be provided by using -P or --preset=NAME option, or specifying the preset name as the last command-line argument. To disable the default preset, use the --no-default option.
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 pgpro_stats) to be installed.
Additional options may be passed via -O or --options=OPTIONS parameter for any preset, but for the default preset --default-options=OPTIONS should be used.
Additional environment variables can be set for presets with the --set NAME=VALUE 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=NAME 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=DATADIR, 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=FILENAME.
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.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: # --no-default --config-file=/path/to/test/conf -P/path/to/test/tune --no-default # At YYYY-MM-DD 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 YYYY-MM-DD HH-MM-SS #------------------------------------------------------------------------------