pg_ctl
pg_ctl — инициализировать, запустить, остановить или управлять сервером PostgreSQL
Синтаксис
pg_ctl init[db] [-D каталог_данных] [-s] [-o параметры-initdb]
pg_ctl start [-D каталог_данных] [-l имя_файла] [-W] [-t секунды] [-s] [-o параметры] [-p путь] [-c]
pg_ctl stop [-D каталог_данных] [-m s[mart] | f[ast] | i[mmediate] ] [-W] [-t секунды] [-s]
pg_ctl restart [-D каталог_данных] [-m s[mart] | f[ast] | i[mmediate] ] [-W] [-t секунды] [-s] [-o параметры] [-c]
pg_ctl reload [-D каталог_данных] [-s]
pg_ctl status [-D каталог_данных]
pg_ctl promote [-D каталог_данных] [-W] [-t секунды] [-s]
pg_ctl logrotate [-D каталог_данных] [-s]
pg_ctl kill имя_сигнала ид_процесса
В системах Microsoft Windows также:
pg_ctl register [-D каталог_данных] [-N имя_службы] [-U имя_пользователя] [-P пароль] [-S a[uto] | d[emand] ] [-e источник] [-W] [-t секунды] [-s] [-o параметры]
pg_ctl unregister [-N имя_службы]
Описание
pg_ctl — это утилита для начальной инициализации, запуска, остановки, повторного запуска и управления кластером баз данных PostgreSQL (postgres). Сервер можно стартовать в ручном режиме, но pg_ctl реализует задачи направления вывода в журнал и отсоединения от терминала и группы процессов, а также предоставляет удобный интерфейс остановки кластера.
Команда init (initdb) создаёт кластер баз данных PostgreSQL, то есть коллекцию баз данных, которой будет управлять один экземпляр сервера. Эта команда вызывает программу initdb. За подробностями обратитесь к initdb.
Команда start запускает сервер. Процесс запускается в фоне, а стандартный ввод связывается с /dev/null (или nul в Windows). По умолчанию в Unix-подобных системах вывод и ошибки сервера пишутся в устройство стандартного вывода (не ошибок) pg_ctl. Вывод pg_ctl следует перенаправить в файл или процесс, например, приложение ротации журналов rotatelogs; иначе postgres будет писать вывод в управляющий терминал (в фоновом режиме) и останется в группе процессов оболочки. В Windows сообщения и ошибки сервера по умолчанию перенаправляются в терминал. Это поведение по умолчанию можно изменить и направить вывод сервера в файл, добавив ключ -l. Предпочтительными вариантами является использование -l или перенаправление вывода.
Команда stop останавливает сервер, работающий с указанным каталогом данных. Параметр -m позволяет выбрать один из трёх режимов остановки. Режим «Smart» запрещает новые подключения, а затем ожидает отключения всех существующих клиентов и завершения всех текущих процессов резервного копирования. Если сервер работает в режиме горячего резерва, восстановление и потоковая репликация будут прерваны, как только отключатся все клиенты. Режим «Fast» (выбираемый по умолчанию) не ожидает отключения клиентов и завершает все текущие процессы резервного копирования. Все активные транзакции откатываются, а клиенты принудительно отключаются, после чего сервер останавливается. Режим «Immediate» незамедлительно прерывает все серверные процессы, не выполняя процедуру штатной остановки. Этот вариант влечёт необходимость выполнить восстановление после сбоя при следующем запуске сервера.
Команда restart по сути производит остановку и последующий запуск сервера. Это позволяет изменить параметры командной строки postgres либо применить изменения в файле конфигурации, не вступающие в силу без перезапуска сервера. Если в командной строке при запуске сервера указывались относительные пути, команда restart может не выполниться, если вызвать pg_ctl не в том каталоге, где производился предыдущий запуск.
Команда reload просто посылает процессу сервера postgres сигнал SIGHUP, получив который он перечитывает свои файлы конфигурации (postgresql.conf, pg_hba.conf и т. д.). Это позволяет применить изменения параметров в файле конфигурации, не требующие полного перезапуска сервера.
Команда status проверяет, работает ли сервер в указанном каталоге данных. Если да, она выдаёт PID сервера и параметры командной строки, с которыми он был запущен. Если сервер не работает, pg_ctl возвращает код завершения 3. Если в параметрах не указан доступный каталог данных, pg_ctl возвращает код завершения 4.
Команда promote указывает серверу, работающему в режиме резерва с указанным каталогом данных, выйти из этого режима и начать операции чтения/записи.
Команда logrotate прокручивает файл журнала сервера. Подробнее о том, как использовать это с внешними средствами прокрутки журнала, рассказывается в Разделе 24.3.
Команда kill передаёт сигнал заданному процессу. Прежде все это полезно в Microsoft Windows, где отсутствует встроенная команда kill. Для получения списка имён поддерживаемых сигналов воспользуйтесь ключом --help.
Команда register регистрирует сервер PostgreSQL в качестве системной службы в Microsoft Windows. Параметр -S позволяет выбрать тип запуска службы: «auto» (запускать службу автоматически при загрузке системы) или «demand» (запускать службу по требованию).
Режим unregister разрегистрирует системную службу в Microsoft Windows. Эта операция отменяет действие команды register.
Параметры
-c--core-filesСпособствует сбросу дампа памяти процесса при крахе сервера на платформах, где это возможно, поднимая мягкие ограничения, задаваемые для файлов дампа. Это полезно при отладке и диагностике проблем, так как позволяет получить трассировку стека отказавшего процесса сервера.
-Dкаталог_данных--pgdata=каталог_данныхУказывает размещение конфигурационных файлов кластера. Если этот ключ опущен, используется значение переменной окружения
PGDATA.-lимя_файла--log=имя_файлаНаправляет вывод сообщений сервера в файл
имя_файла. Файл создаётся, если он ещё не существует. При этом устанавливается umask 077, что предотвращает доступ других пользователей к этому файлу.-mрежим--mode=режимЗадаёт режим остановки кластера. Значением
режимможет бытьsmart,fastилиimmediate, либо первая буква этих вариантов. Если этот ключ опущен, по умолчанию выбирается режимfast.-oпараметры--options=параметрыУказывает параметры, которые будут передаваться непосредственно программе
postgres. Ключ-oможно указывать несколько раз, при этом ей будут переданы параметры из всех ключей.Задаваемые
параметрыобычно следует обрамлять одинарными или двойными кавычками, чтобы они передавались одной группой.-oпараметры-initdb--options=параметры-initdbУказывает параметры, которые будут передаваться непосредственно программе
initdb. Ключ-oможно указывать несколько раз, при этом ей будут переданы параметры из всех ключей.Задаваемые
параметры-initdbобычно следует обрамлять одинарными или двойными кавычками, чтобы они передавались вместе одной группой.-pпутьУказывает размещение исполняемого файла
postgres. По умолчанию задействуется исполняемый файлpostgresиз того же каталога, из которого запускалсяpg_ctl, а если это невозможно, из жёстко заданного каталога инсталляции. Применять этот параметр может понадобиться, только если вы делаете что-то необычное или получаете сообщения, что найти исполняемый файлpostgresне удаётся.В режиме
initэтот параметр аналогичным образом задаёт размещение исполняемого файлаinitdb.-s--silentВыводить лишь ошибки, без сообщений информационного характера.
-tсекунды--timeout=секундыЗадаёт максимальное время (в секундах) ожидания завершения операции (см. параметр
-w). По умолчанию действует значение переменной средыPGCTLTIMEOUTили, если оно не задано, 60 секунд.-V--versionВыводит версию pg_ctl и прерывает выполнение.
-w--waitЖдать завершения операции. Этот режим поддерживается (и действует по умолчанию) для команд
start,stop,restart,promoteиregister.В процессе ожидания
pg_ctlпостоянно проверяет PID-файл сервера, приостанавливаясь на короткое время между проверками. Запуск считается завершённым, когда PID-файл указывает на то, что сервер готов принимать подключения. Остановка считается завершённой, когда сервер удаляет свой PID-файл. Программаpg_ctlвозвращает код завершения в зависимости от успеха запуска или остановки.Если операция не заканчивается за отведённое время (см. параметр
-t), программаpg_ctlзавершается с ненулевым кодом выхода. Но заметьте, что при этом выполнение операции может продолжиться и в конце концов увенчаться успехом.-W--no-waitНе ждать завершения операции. Этот режим противоположен режиму
-w.Если ожидание отключено, запрошенное действие вызывается, но о его результате ничего не известно. В этом случае для проверки текущего состояния и результата операции потребуется обратиться к файлу журнала сервера или воспользоваться внешней системой мониторинга.
В предыдущих выпусках PostgreSQL этот режим действовал по умолчанию (кроме команды
stop).-?--helpВывести справку по команде pg_ctl и прервать выполнение.
Если некоторый параметр является допустимым, но не применим к выбранному режиму работы, pg_ctl игнорирует его.
Параметры, специфичные для Windows
-eисточникИмя источника событий, с которым pg_ctl будет записывать в системный журнал события при запуске в виде службы Windows. Имя по умолчанию —
PostgreSQL. Заметьте, что это влияет только на сообщения, которые выдаёт сам pg_ctl; как только сервер запустится, он будет использовать источник событий, заданный в event_source. Если произойдёт ошибка при запуске сервера на ранней стадии, прежде чем будет считан этот параметр, он может также выдавать сообщения с источником по умолчаниюPostgreSQL.-Nимя_службыИмя регистрируемой системной службы. Оно станет и собственно именем службы, и отображаемым именем. По умолчанию —
PostgreSQL.-PпарольПароль для пользователя, запускающего службу.
-Sтип-запускаТип запуска системной службы. В качестве значения
тип-запускаможно задатьauto,demandили первую букву этих слов. По умолчанию выбирается типauto.-Uимя_пользователяИмя пользователя, от имени которого будут запущена служба. Для доменных пользователей используйте формат
DOMAIN\username.
Переменные окружения
PGCTLTIMEOUTЗначение по умолчанию для максимального времени ожидания запуска или остановки сервера (в секундах). По умолчанию это время составляет 60 секунд.
PGDATAРазмещение каталога хранения данных по умолчанию.
Для большинства режимов pg_ctl требуется знать расположение каталога данных; поэтому если не задана переменная PGDATA, параметр -D является обязательным.
Список дополнительных переменных, влияющих на работу сервера, можно найти в postgres.
Файлы
postmaster.pidПроверяя этот файл в каталоге данных, pg_ctl определяет, работает ли сервер в настоящий момент.
postmaster.optsЕсли файл существует в каталоге хранения данных, то pg_ctl (при
restart) передаст его содержимое в качестве аргументов postgres, если не указаны иные значения в-o. Содержимое файла также отображается при вызове в режимеstatus.
Примеры
Запуск сервера
Запуск сервера и ожидание момента, когда он начнёт принимать подключения:
$pg_ctl start
Чтобы запустить сервер с использованием порта 5433 и без fsync, выполните:
$pg_ctl -o "-F -p 5433" start
Остановка сервера
Чтобы остановить сервер, выполните:
$pg_ctl stop
Ключ -m позволяет управлять тем, как сервер будет остановлен:
$pg_ctl stop -m smart
Повторный запуск сервера
Перезапуск сервера почти равнозначен остановке и запуску сервера за исключением того, что по умолчанию pg_ctl сохраняет параметры командной строки, которые были переданы ранее запущенному экземпляру. Таким образом, чтобы перезапустить сервер с теми же параметрами, с какими он был запущен, выполните:
$pg_ctl restart
Но если добавляется ключ -o, он заменяет все предыдущие параметры. Эта команда осуществит перезапуск с использованием порта 5433 и без fsync:
$pg_ctl -o "-F -p 5433" restart
Вывод состояния сервера
Ниже представлен примерный вывод pg_ctl:
$pg_ctl statuspg_ctl: server is running (PID: 13718) /usr/local/pgsql/bin/postgres "-D" "/usr/local/pgsql/data" "-p" "5433" "-B" "128"
Во второй строке показывается команда, которая будет выполнена в режиме перезапуска.
pg_ctl
pg_ctl — initialize, start, stop, or control a PostgreSQL server
Synopsis
pg_ctl init[db] [-D datadir] [-s] [-o initdb-options]
pg_ctl start [-D datadir] [-l filename] [-W] [-t seconds] [-s] [-o options] [-p path] [-c]
pg_ctl stop [-D datadir] [-m s[mart] | f[ast] | i[mmediate] ] [-W] [-t seconds] [-s]
pg_ctl restart [-D datadir] [-m s[mart] | f[ast] | i[mmediate] ] [-W] [-t seconds] [-s] [-o options] [-c]
pg_ctl reload [-D datadir] [-s]
pg_ctl status [-D datadir]
pg_ctl promote [-D datadir] [-W] [-t seconds] [-s]
pg_ctl logrotate [-D datadir] [-s]
pg_ctl kill signal_name process_id
On Microsoft Windows, also:
pg_ctl register [-D datadir] [-N servicename] [-U username] [-P password] [-S a[uto] | d[emand] ] [-e source] [-W] [-t seconds] [-s] [-o options]
pg_ctl unregister [-N servicename]
Description
pg_ctl is a utility for initializing a PostgreSQL database cluster, starting, stopping, or restarting the PostgreSQL database server (postgres), or displaying the status of a running server. Although the server can be started manually, pg_ctl encapsulates tasks such as redirecting log output and properly detaching from the terminal and process group. It also provides convenient options for controlled shutdown.
The init or initdb mode creates a new PostgreSQL database cluster, that is, a collection of databases that will be managed by a single server instance. This mode invokes the initdb command. See initdb for details.
start mode launches a new server. The server is started in the background, and its standard input is attached to /dev/null (or nul on Windows). On Unix-like systems, by default, the server's standard output and standard error are sent to pg_ctl's standard output (not standard error). The standard output of pg_ctl should then be redirected to a file or piped to another process such as a log rotating program like rotatelogs; otherwise postgres will write its output to the controlling terminal (from the background) and will not leave the shell's process group. On Windows, by default the server's standard output and standard error are sent to the terminal. These default behaviors can be changed by using -l to append the server's output to a log file. Use of either -l or output redirection is recommended.
stop mode shuts down the server that is running in the specified data directory. Three different shutdown methods can be selected with the -m option. “Smart” mode disallows new connections, then waits for all existing clients to disconnect and any online backup to finish. If the server is in hot standby, recovery and streaming replication will be terminated once all clients have disconnected. “Fast” mode (the default) does not wait for clients to disconnect and will terminate an online backup in progress. All active transactions are rolled back and clients are forcibly disconnected, then the server is shut down. “Immediate” mode will abort all server processes immediately, without a clean shutdown. This choice will lead to a crash-recovery cycle during the next server start.
restart mode effectively executes a stop followed by a start. This allows changing the postgres command-line options, or changing configuration-file options that cannot be changed without restarting the server. If relative paths were used on the command line during server start, restart might fail unless pg_ctl is executed in the same current directory as it was during server start.
reload mode simply sends the postgres server process a SIGHUP signal, causing it to reread its configuration files (postgresql.conf, pg_hba.conf, etc.). This allows changing configuration-file options that do not require a full server restart to take effect.
status mode checks whether a server is running in the specified data directory. If it is, the server's PID and the command line options that were used to invoke it are displayed. If the server is not running, pg_ctl returns an exit status of 3. If an accessible data directory is not specified, pg_ctl returns an exit status of 4.
promote mode commands the standby server that is running in the specified data directory to end standby mode and begin read-write operations.
logrotate mode rotates the server log file. For details on how to use this mode with external log rotation tools, see Section 24.3.
kill mode sends a signal to a specified process. This is primarily valuable on Microsoft Windows which does not have a built-in kill command. Use --help to see a list of supported signal names.
register mode registers the PostgreSQL server as a system service on Microsoft Windows. The -S option allows selection of service start type, either “auto” (start service automatically on system startup) or “demand” (start service on demand).
unregister mode unregisters a system service on Microsoft Windows. This undoes the effects of the register command.
Options
-c--core-filesAttempt to allow server crashes to produce core files, on platforms where this is possible, by lifting any soft resource limit placed on core files. This is useful in debugging or diagnosing problems by allowing a stack trace to be obtained from a failed server process.
-Ddatadir--pgdata=datadirSpecifies the file system location of the database configuration files. If this option is omitted, the environment variable
PGDATAis used.-lfilename--log=filenameAppend the server log output to
filename. If the file does not exist, it is created. The umask is set to 077, so access to the log file is disallowed to other users by default.-mmode--mode=modeSpecifies the shutdown mode.
modecan besmart,fast, orimmediate, or the first letter of one of these three. If this option is omitted,fastis the default.-ooptions--options=optionsSpecifies options to be passed directly to the
postgrescommand.-ocan be specified multiple times, with all the given options being passed through.The
optionsshould usually be surrounded by single or double quotes to ensure that they are passed through as a group.-oinitdb-options--options=initdb-optionsSpecifies options to be passed directly to the
initdbcommand.-ocan be specified multiple times, with all the given options being passed through.The
initdb-optionsshould usually be surrounded by single or double quotes to ensure that they are passed through as a group.-ppathSpecifies the location of the
postgresexecutable. By default thepostgresexecutable is taken from the same directory aspg_ctl, or failing that, the hard-wired installation directory. It is not necessary to use this option unless you are doing something unusual and get errors that thepostgresexecutable was not found.In
initmode, this option analogously specifies the location of theinitdbexecutable.-s--silentPrint only errors, no informational messages.
-tseconds--timeout=secondsSpecifies the maximum number of seconds to wait when waiting for an operation to complete (see option
-w). Defaults to the value of thePGCTLTIMEOUTenvironment variable or, if not set, to 60 seconds.-V--versionPrint the pg_ctl version and exit.
-w--waitWait for the operation to complete. This is supported for the modes
start,stop,restart,promote, andregister, and is the default for those modes.When waiting,
pg_ctlrepeatedly checks the server's PID file, sleeping for a short amount of time between checks. Startup is considered complete when the PID file indicates that the server is ready to accept connections. Shutdown is considered complete when the server removes the PID file.pg_ctlreturns an exit code based on the success of the startup or shutdown.If the operation does not complete within the timeout (see option
-t), thenpg_ctlexits with a nonzero exit status. But note that the operation might continue in the background and eventually succeed.-W--no-waitDo not wait for the operation to complete. This is the opposite of the option
-w.If waiting is disabled, the requested action is triggered, but there is no feedback about its success. In that case, the server log file or an external monitoring system would have to be used to check the progress and success of the operation.
In prior releases of PostgreSQL, this was the default except for the
stopmode.-?--helpShow help about pg_ctl command line arguments, and exit.
If an option is specified that is valid, but not relevant to the selected operating mode, pg_ctl ignores it.
Options for Windows
-esourceName of the event source for pg_ctl to use for logging to the event log when running as a Windows service. The default is
PostgreSQL. Note that this only controls messages sent from pg_ctl itself; once started, the server will use the event source specified by its event_source parameter. Should the server fail very early in startup, before that parameter has been set, it might also log using the default event source namePostgreSQL.-NservicenameName of the system service to register. This name will be used as both the service name and the display name. The default is
PostgreSQL.-PpasswordPassword for the user to run the service as.
-Sstart-typeStart type of the system service.
start-typecan beauto, ordemand, or the first letter of one of these two. If this option is omitted,autois the default.-UusernameUser name for the user to run the service as. For domain users, use the format
DOMAIN\username.
Environment
PGCTLTIMEOUTDefault limit on the number of seconds to wait when waiting for startup or shutdown to complete. If not set, the default is 60 seconds.
PGDATADefault data directory location.
Most pg_ctl modes require knowing the data directory location; therefore, the -D option is required unless PGDATA is set.
For additional variables that affect the server, see postgres.
Files
postmaster.pidpg_ctl examines this file in the data directory to determine whether the server is currently running.
postmaster.optsIf this file exists in the data directory, pg_ctl (in
restartmode) will pass the contents of the file as options to postgres, unless overridden by the-ooption. The contents of this file are also displayed instatusmode.
Examples
Starting the Server
To start the server, waiting until the server is accepting connections:
$pg_ctl start
To start the server using port 5433, and running without fsync, use:
$pg_ctl -o "-F -p 5433" start
Stopping the Server
To stop the server, use:
$pg_ctl stop
The -m option allows control over how the server shuts down:
$pg_ctl stop -m smart
Restarting the Server
Restarting the server is almost equivalent to stopping the server and starting it again, except that by default, pg_ctl saves and reuses the command line options that were passed to the previously-running instance. To restart the server using the same options as before, use:
$pg_ctl restart
But if -o is specified, that replaces any previous options. To restart using port 5433, disabling fsync upon restart:
$pg_ctl -o "-F -p 5433" restart
Showing the Server Status
Here is sample status output from pg_ctl:
$pg_ctl statuspg_ctl: server is running (PID: 13718) /usr/local/pgsql/bin/postgres "-D" "/usr/local/pgsql/data" "-p" "5433" "-B" "128"
The second line is the command that would be invoked in restart mode.