pg_isready
pg_isready — проверить соединение с сервером PostgreSQL
Синтаксис
pg_isready [параметр-подключения...] [параметр...]
Описание
Утилита pg_isready предназначена для проверки соединения с сервером баз данных PostgreSQL. Результат проверки передаётся в коде завершения.
Параметры
-ddbname--dbname=dbnameУказывает имя базы данных для подключения. В данном аргументе может задаваться строка подключения. В этом случае параметры в строке подключения переопределяют одноимённые параметры, заданные в командной строке.
-hкомпьютер--host=компьютерУказывает имя компьютера, на котором работает сервер. Если значение начинается с косой черты, оно определяет каталог Unix-сокета.
-pпорт--port=портУказывает TCP-порт или расширение файла локального Unix-сокета, через который сервер принимает подключения. Значение по умолчанию определяется переменной среды
PGPORT, если она установлена, либо числом, заданным при компиляции, обычно 5432.-q--quietНе выводить сообщение о состоянии. Это полезно в скриптах.
-tсекунды--timeout=секундыМаксимальное время ожидания (в секундах) при попытке подключения, по истечении которого констатируется, что сервер не отвечает. Значение по умолчанию — 3 секунды.
-Uимя_пользователя--username=имя_пользователяПодключиться к базе данных с заданным именем пользователя вместо подразумеваемого по умолчанию.
-V--versionСообщить версию pg_isready и завершиться.
-?--helpПоказать справку по аргументам командной строки pg_isready и завершиться.
Код завершения
Утилита pg_isready возвращает в оболочку 0, если сервер принимает подключения, 1, если он сбрасывает подключения (например, во время загрузки), 2, если при попытке подключения не получен ответ, и 3, если попытки подключения не было (например, из-за некорректных параметров).
Переменные окружения
Как и большинство других утилит PostgreSQL, pg_isready также использует переменные среды, поддерживаемые libpq (см. Раздел 34.15).
Переменная окружения PG_COLOR выбирает вариант использования цвета в диагностических сообщениях. Возможные значения: always (всегда), auto (автоматически) и never (никогда).
Примечания
Чтобы получить состояние сервера, передавать имя пользователя, пароль и имя базы данных не требуется; но если передать некорректные значения, сервер выведет в журнал сообщение о неудачной попытке подключения.
Примеры
Обычное использование:
$pg_isready/tmp:5432 - accepting connections$echo $?0
Запуск с параметрами подключения, во время загрузки кластера PostgreSQL:
$pg_isready -h localhost -p 5433localhost:5433 - rejecting connections$echo $?1
Запуск с параметрами подключения, в случае, когда кластер PostgreSQL недоступен:
$pg_isready -h someremotehostsomeremotehost:5432 - no response$echo $?2
pg_isready
pg_isready — check the connection status of a PostgreSQL server
Synopsis
pg_isready [connection-option...] [option...]
Description
pg_isready is a utility for checking the connection status of a PostgreSQL database server. The exit status specifies the result of the connection check.
Options
-ddbname--dbname=dbnameSpecifies the name of the database to connect to. The
dbnamecan be a connection string. If so, connection string parameters will override any conflicting command line options.-hhostname--host=hostnameSpecifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix-domain socket.
-pport--port=portSpecifies the TCP port or the local Unix-domain socket file extension on which the server is listening for connections. Defaults to the value of the
PGPORTenvironment variable or, if not set, to the port specified at compile time, usually 5432.-q--quietDo not display status message. This is useful when scripting.
-tseconds--timeout=secondsThe maximum number of seconds to wait when attempting connection before returning that the server is not responding. Setting to 0 disables. The default is 3 seconds.
-Uusername--username=usernameConnect to the database as the user
usernameinstead of the default.-V--versionPrint the pg_isready version and exit.
-?--helpShow help about pg_isready command line arguments, and exit.
Exit Status
pg_isready returns 0 to the shell if the server is accepting connections normally, 1 if the server is rejecting connections (for example during startup), 2 if there was no response to the connection attempt, and 3 if no attempt was made (for example due to invalid parameters).
Environment
pg_isready, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 34.15).
The environment variable PG_COLOR specifies whether to use color in diagnostic messages. Possible values are always, auto and never.
Notes
It is not necessary to supply correct user name, password, or database name values to obtain the server status; however, if incorrect values are provided, the server will log a failed connection attempt.
Examples
Standard Usage:
$pg_isready/tmp:5432 - accepting connections$echo $?0
Running with connection parameters to a PostgreSQL cluster in startup:
$pg_isready -h localhost -p 5433localhost:5433 - rejecting connections$echo $?1
Running with connection parameters to a non-responsive PostgreSQL cluster:
$pg_isready -h someremotehostsomeremotehost:5432 - no response$echo $?2