19.17. Обработка ошибок #

exit_on_error (boolean) #

Если этот параметр включён, любая ошибка приведёт к прерыванию текущего сеанса. По умолчанию он отключён, так что сеанс будет прерываться только при критических ошибках.

restart_after_crash (boolean) #

Когда этот параметр включён (это состояние по умолчанию), Postgres Pro будет автоматически перезагружаться после сбоя серверного процесса. Такой вариант позволяет обеспечить максимальную степень доступности базы данных. Однако в некоторых обстоятельствах, например, когда Postgres Pro управляется кластерным ПО, такую перезагрузку лучше отключить, чтобы кластерное ПО могло вмешаться и выполнить, возможно, более подходящие действия.

Задать этот параметр можно только в postgresql.conf или в командной строке при запуске сервера.

data_sync_retry (boolean) #

При выключенном значении этого параметра (по умолчанию) Postgres Pro будет выдавать ошибку уровня PANIC в случае неудачи при попытке сохранить изменённые данные в файловой системе. В результате сервер баз данных остановится аварийно. Задать этот параметр можно только при запуске сервера.

В некоторых операционных системах состояние данных в кеше внутри ядра оказывается неопределённым при ошибке записи. В каких-то случаях эти данные могут быть просто утеряны, и повторять попытку записи небезопасно: вторая попытка может оказаться успешной, тогда как на деле данные не сохранены. В этих обстоятельствах единственный способ избежать потери данных — восстановить их из WAL после такого сбоя, но перед этим желательно выяснить причину проблемы и, возможно, заменить нерабочее оборудование.

Если включить этот параметр, Postgres Pro в случае сбоя при записи выдаст ошибку, но продолжит работу в расчёте повторить операцию сохранения данных при последующей контрольной точке. Включать его следует, только если достоверно известно, как поступает система с данными в буфере при ошибке записи.

recovery_init_sync_method (enum) #

Со значением fsync (это значение по умолчанию), Postgres Pro будет рекурсивно открывать и синхронизировать все файлы в каталоге данных до начала восстановления после сбоя. Поиск файлов будет осуществляться по символическим ссылкам для каталога WAL и каждого настроенного табличного пространства (но не другим символическим ссылкам). Это делается для того, чтобы убедиться, что все файлы WAL и данных надёжно сохранены на диске перед воспроизведением изменений, и применяется при запуске кластера базы данных, который не был остановлен штатным образом (это касается и копий созданных программой pg_basebackup).

В Linux возможен вариант syncfs, когда от ОС требуется синхронизировать каждую из файловых систем, содержащих каталог данных, файлы WAL и табличные пространства (но не те файловые системы, которые подключены по символическим ссылкам). При этом не нужно открывать каждый отдельный файл, поэтому данный вариант может работать гораздо быстрее, чем fsync. С другой стороны, он может быть медленнее, если файловую систему совместно используют и другие приложения, изменяющие множество файлов, поскольку эти файлы также будут записываться на диск. Более того, Linux версий до 5.8 может не всегда сообщать Postgres Pro об ошибках ввода-вывода, произошедших при записи данных на диск, так что соответствующие сообщения можно увидеть только в журналах ядра.

Задать этот параметр можно только в postgresql.conf или в командной строке при запуске сервера.

crash_info (boolean) #

Если установлено значение по умолчанию on, Postgres Pro записывает диагностическую информацию о сбое сервера в файл.

Этот параметр можно задать только при запуске сервера.

crash_info_dump (text) #

Указывает разделённый запятыми список текстовых строк, содержащих источники данных для аварийных дампов. Возможны следующие значения строк:

  • queries — тексты запросов.

  • memory_context — контекст памяти Postgres Pro (за подробностями обратитесь к Разделу 49.3).

  • system — информация об ОС.

  • module — информация о модулях, загруженных в процесс postgres.

  • cpuinfo — информация о процессоре: число ядер, набор инструкций, и т. д.

  • cpu_context:

    • Регистры контекста процессора.

    • Общая информация об ошибке: номер сигнала, информация о коде сигнала, PID, PID родительского процесса, идентификатор пользователя и т. д.

  • virtual_memory — информация о виртуальной памяти

  • instruction_pointer — байты около RIP (return instruction pointer, указатель возврата инструкции, который указывает на адрес памяти, по которому можно судить о прогрессе выполнения программы в памяти).

  • stack — размер стека (байты). Стек выгружается в отдельный файл из каталога, куда записывается диагностическая информация о сбоях сервера (по умолчанию PGDATA/crash_info). Этот файл называется так же, как и журнал сбоев, но имеет расширение .data. Адреса верхней и нижней границ стека записываются в журнал сбоев.

Значение по умолчанию — system,module,queries,cpu_context,instruction_pointer.

Этот параметр можно задать только при запуске сервера.

crash_info_location (string) #

Указывает каталог, в котором должна храниться информация о сбое сервера. При значении stderr информация о сбое отправляется в каталог stderr. Если в этом параметре указана пустая строка '' (по умолчанию), используется каталог $PGDATA/crash_info. Если нужно сохранять файлы в другом месте, заранее создайте целевой каталог и выдайте соответствующие права.

Этот параметр можно задать только при запуске сервера.

crash_info_timer (boolean) #

Включает или отключает выгрузку состояния длительных запросов по таймеру, что позволяет профилировать такие запросы. Таймер запускается по интервалу, значение которого указывается в crash_info_timer_interval, и измеряет время обработки запроса. Когда время выполнения запроса превышает пороговое значение, указанное в crash_info_query_threshold, состояние запроса выгружается на диск. Значение по умолчанию — off. Чтобы таймер работал, для crash_info_dump должно быть установлено значение по крайней мере queries. Изменить этот параметр могут только суперпользователи командой SET в текущем сеансе или глобально в файле конфигурации.

Этот параметр можно задать только при запуске сервера в файле postgresql.conf. Чтобы перечитать значение параметра, перезапустите сервер или отправьте сигнал SIGHUP главному серверному процессу.

crash_info_timer_interval (integer) #

Задаёт временной интервал для запуска таймера (в миллисекундах). Значение по умолчанию — 1000. Изменить этот параметр могут только суперпользователи командой SET в текущем сеансе или глобально в файле конфигурации.

Этот параметр можно задать только при запуске сервера в файле postgresql.conf. Чтобы перечитать значение параметра, перезапустите сервер или отправьте сигнал SIGHUP главному серверному процессу.

crash_info_query_threshold (integer) #

Задаёт пороговое значение времени обработки запроса (в миллисекундах). При достижении значения состояние запроса выгружается на диск. Значение по умолчанию — 3000. Изменить этот параметр могут только суперпользователи командой SET в текущем сеансе или глобально в файле конфигурации.

Этот параметр можно задать только при запуске сервера в файле postgresql.conf. Чтобы перечитать значение параметра, перезапустите сервер или отправьте сигнал SIGHUP главному серверному процессу.

19.17. Error Handling #

exit_on_error (boolean) #

If on, any error will terminate the current session. By default, this is set to off, so that only FATAL errors will terminate the session.

restart_after_crash (boolean) #

When set to on, which is the default, Postgres Pro will automatically reinitialize after a backend crash. Leaving this value set to on is normally the best way to maximize the availability of the database. However, in some circumstances, such as when Postgres Pro is being invoked by clusterware, it may be useful to disable the restart so that the clusterware can gain control and take any actions it deems appropriate.

This parameter can only be set in the postgresql.conf file or on the server command line.

data_sync_retry (boolean) #

When set to off, which is the default, Postgres Pro will raise a PANIC-level error on failure to flush modified data files to the file system. This causes the database server to crash. This parameter can only be set at server start.

On some operating systems, the status of data in the kernel's page cache is unknown after a write-back failure. In some cases it might have been entirely forgotten, making it unsafe to retry; the second attempt may be reported as successful, when in fact the data has been lost. In these circumstances, the only way to avoid data loss is to recover from the WAL after any failure is reported, preferably after investigating the root cause of the failure and replacing any faulty hardware.

If set to on, Postgres Pro will instead report an error but continue to run so that the data flushing operation can be retried in a later checkpoint. Only set it to on after investigating the operating system's treatment of buffered data in case of write-back failure.

recovery_init_sync_method (enum) #

When set to fsync, which is the default, Postgres Pro will recursively open and synchronize all files in the data directory before crash recovery begins. The search for files will follow symbolic links for the WAL directory and each configured tablespace (but not any other symbolic links). This is intended to make sure that all WAL and data files are durably stored on disk before replaying changes. This applies whenever starting a database cluster that did not shut down cleanly, including copies created with pg_basebackup.

On Linux, syncfs may be used instead, to ask the operating system to synchronize the file systems that contain the data directory, the WAL files and each tablespace (but not any other file systems that may be reachable through symbolic links). This may be a lot faster than the fsync setting, because it doesn't need to open each file one by one. On the other hand, it may be slower if a file system is shared by other applications that modify a lot of files, since those files will also be written to disk. Furthermore, on versions of Linux before 5.8, I/O errors encountered while writing data to disk may not be reported to Postgres Pro, and relevant error messages may appear only in kernel logs.

This parameter can only be set in the postgresql.conf file or on the server command line.

crash_info (boolean) #

When set to on, which is the default, Postgres Pro will write diagnostic information about a backend crash into a file.

This parameter can only be set at server start.

crash_info_dump (text) #

Specifies a comma-separated list of character strings that contain data sources to provide data for a crash dump. Possible values of the strings are as follows:

  • queries — query texts.

  • memory_contextPostgres Pro memory context (see Section 49.3 for details).

  • system — information on the OS.

  • module — information on modules loaded to the postgres process.

  • cpuinfo — information on the processor: number of cores, instruction set, etc.

  • cpu_context:

    • Processor context registers.

    • General information on the error: signal number, signal code information, PID, PID of the parent process, user ID, etc.

  • virtual_memory — information on virtual memory regions

  • instruction_pointer — bytes near RIP (the return instruction pointer, which points to a memory address indicating the progress of a program execution in memory).

  • stack — stack bytes. The stack is dumped to an individual file in the directory where diagnostic information about backend crashes is logged (PGDATA/crash_info by default). This file has the same name as the crash log file, but the .data extension. The addresses of the upper and lower stack bounds are written to the crash log file.

The default value is system,module,queries,cpu_context,instruction_pointer.

This parameter can only be set at server start.

crash_info_location (string) #

Specifies the directory where information about a backend crash is to be stored. The value of stderr sends information about the crash to stderr. If this parameter is set to the empty string '', which is the default, the $PGDATA/crash_info directory is used. If you wish to keep the files elsewhere, create the target directory in advance and grant appropriate privileges.

This parameter can only be set at server start.

crash_info_timer (boolean) #

Enables or disables dumping of long-running query state by timer, which allows profiling such queries. The timer is launched by the interval specified in crash_info_timer_interval and measures query processing time. When query execution time exceeds the threshold specified in crash_info_query_threshold, the query state is dumped to disk. The default value is off. For the timer to operate, crash_info_dump must be set at least to queries. This setting can be changed only by superusers using the SET command in the current session or in the configuration file globally.

This parameter can only be set at server start in the postgresql.conf file. To re-read the parameter value, restart the server or send the SIGHUP signal to the main server process.

crash_info_timer_interval (integer) #

Sets the time interval to launch the timer, in milliseconds. The default value is 1000. This setting can be changed only by superusers using the SET command in the current session or in the configuration file globally.

This parameter can only be set at server start in the postgresql.conf file. To re-read the parameter value, restart the server or send the SIGHUP signal to the main server process.

crash_info_query_threshold (integer) #

Sets the threshold value for the query processing time, in milliseconds. When reached, the query state is dumped to disk. The default value is 3000. This setting can be changed only by superusers using the SET command in the current session or in the configuration file globally.

This parameter can only be set at server start in the postgresql.conf file. To re-read the parameter value, restart the server or send the SIGHUP signal to the main server process.

FAQ