pg_resetxlog
Название
pg_resetxlog -- очистка журнала упреждающей записи и другой управляющей информацию кластера PostgreSQLСинтаксис
pg_resetxlog [ -f ] [ -n ] [-o oid] [-x xid] [-e xid_epoch] [-m mxid,mxid] [-O mxoff] [-l xlogfile] datadir
Описание
pg_resetxlog очищает журнал упреждающей записи (WAL) и может сбросить некоторую другую управляющую информацию, хранящуюся в файле pg_control. Это необходимо в случае повреждения этих файлов, и должно использоваться лишь при крайних мерах.
После запуска этой команды, старт сервера, скорее всего, будет возможен, однако, стоит учитывать, что сервер может оказаться не в целостном состоянии. Требуется немедленно выгрузить данные (dump), выполнить initdb и загрузить данные. После чего проверить целостность и при необходимости восстановить.
Утилита может запускаться лишь от пользователя, установившего сервер, так как требуются права записи/чтения в каталоге хранения данных кластера. В целях безопасности каталог необходимо указывать в командной строке. pg_resetxlog не поддерживает переменную окружения PGDATA.
Если pg_resetxlog выводит сообщение о невозможности определить данные из pg_control, то команду можно запустить принудительно, указав -f. В этом случае будут использованы наиболее вероятные значения. Для большинства полей это нормально, но для некоторых может потребоваться явное указание: следующее значение OID, следующее значение ID транзакции и времени, ID мультитранзакции и смещение, начальный адрес WAL. Эти значения можно указать с помощью далее описанных параметров. Если их невозможно определить, то флаг f позволяет это обойти, однако, достоверность данных восстановленной базы останется под сомнением: незамедлительная выгрузка с последующим восстановлением данных крайне необходимы. Не выполняйте никаких операций модификации до создания дампа данных, так как это может привести к ещё более печальным последствиям.
Чтобы указать значения следующих OID, ID транзакции, времени транзакции, ID мультитранзакции, смещения мультитранзакции и начального адреса WAL, используются соответствующие параметры -o, -x, -e, -m, -O, и -l. Это требуется, когда pg_resetxlog не может самостоятельно определить значения из файла pg_control. Безопасные значения вычисляются, как описано далее:
Чтобы определить следующее безопасное значение идентификатора транзакции (-x), необходимо в каталоге pg_clog найти файл, имя которого представляет наибольшее числовое значение, добавить к нему один и затем умножить на 1048576. Имена файлов представлены в шестнадцатеричном формате, и значение параметра проще указывать в нём же. Например, если в pg_clog найден файл 0011, будет корректным значение -x 0x1200000 (пять замыкающих нулей представляют требуемый множитель).
Безопасное значение следующего идентификатора мультитранзакции (первый аргумент параметра -m) можно вычислить, найдя наибольшее числовое значение среди имён файлов, расположенных в каталоге pg_multixact/offsets. К найденному значению необходимо прибавить один, затем умножить на 65536. Для вычисления же наиболее старшего ID мультитранзакции (второй аргумент параметра -m), необходимо найти наименьшее числовое значение среди тех же файлов, и умножить его на 65536. Как было описано ранее, имена представлены в шестнадцатеричном формате, поэтому значения аргументов лучше указывать в нём же, приписав четыре замыкающих нуля.
Чтобы определить безопасное значение следующего смещения (-O), необходимо найти наибольшее числовое значение в имени файла в каталоге pg_multixact/members, прибавить один, а затем умножить на 52352. Имена файлов также представлены в шестнадцатеричном формате, однако не существует однозначного решения в добавлении замыкающих нулей, аналогично ранее описанным.
Начальный адрес журнала WAL (-l) должен превышать наибольшее значение сегмента в имени файла, расположенного в каталоге pg_xlog. Имена также представлены в шестнадцатеричном формате и состоят из трёх частей. Первая из них это "ID временного интервала" (обычно оставляют неизменным), например, если 00000001000000320000004A имеет наибольшее значение в pg_xlog, то можно использовать -l 00000001000000320000004B, либо выше.
Замечание: pg_resetxlog ищет среди файлов каталога pg_xlog, и по умолчанию выбирает значение для флага -l, идущее следующим после найденного. Корректировка значения параметра -l требуется лишь в ситуации, когда известно о существовании других сегментов WAL, отсутствующих на момент в каталоге pg_xlog, например, из архивного файла, или при полной потере данных в pg_xlog.
Не существует относительно простого пути вычисления следующего за наибольшим из существующих значением OID, однако, это не критично.
Время ID транзакции не хранится в базе данных кроме поля, устанавливаемого командой pg_resetxlog, поэтому принимается любая допустимая величина. Возможно, понадобиться поправить значение для обеспечения работоспособности репликации, например, Slony-I. Значение должно соответствовать состоянию реплицируемой базы данных.
С флагом -n (без выполнения) команда pg_resetxlog отображает извлечённые из pg_control данные, а также значения, которые можно изменить. Режим полезен для отладки и тестирования предстоящей операции без реального применения изменений.
Флаги -V и --version выводят версию pg_resetxlog и прерывают дальнейшее выполнение. Ключи -? и --help выводят справку по поддерживаемым аргументам.
Замечания
Команду нельзя выполнять на работающем сервере. pg_resetxlog отклонит выполнение при обнаруженном блокирующем файле в каталоге хранения данных. Иногда при аварии сервера блокирующий файл может остаться в системе. В этом случае необходимо самостоятельно удалить его, чтобы дать возможность pg_resetxlog отработать. Перед выполнением операции дважды убедитесь, что сервер остановлен.
| Пред. | Начало | След. |
| pg_ctl | Уровень выше | postgres |
pg_resetxlog
Name
pg_resetxlog -- reset the write-ahead log and other control information of a PostgreSQL database clusterSynopsis
pg_resetxlog [-f] [-n] [-o oid] [-x xid] [-e xid_epoch] [-m mxid,mxid] [-O mxoff] [-l xlogfile] datadir
Description
pg_resetxlog clears the write-ahead log (WAL) and optionally resets some other control information stored in the pg_control file. This function is sometimes needed if these files have become corrupted. It should be used only as a last resort, when the server will not start due to such corruption.
After running this command, it should be possible to start the server, but bear in mind that the database might contain inconsistent data due to partially-committed transactions. You should immediately dump your data, run initdb, and reload. After reload, check for inconsistencies and repair as needed.
This utility can only be run by the user who installed the server, because it requires read/write access to the data directory. For safety reasons, you must specify the data directory on the command line. pg_resetxlog does not use the environment variable PGDATA.
If pg_resetxlog complains that it cannot determine valid data for pg_control, you can force it to proceed anyway by specifying the -f (force) option. In this case plausible values will be substituted for the missing data. Most of the fields can be expected to match, but manual assistance might be needed for the next OID, next transaction ID and epoch, next multitransaction ID and offset, and WAL starting address fields. These fields can be set using the options discussed below. If you are not able to determine correct values for all these fields, -f can still be used, but the recovered database must be treated with even more suspicion than usual: an immediate dump and reload is imperative. Do not execute any data-modifying operations in the database before you dump, as any such action is likely to make the corruption worse.
The -o, -x, -e, -m, -O, and -l options allow the next OID, next transaction ID, next transaction ID's epoch, next and oldest multitransaction ID, next multitransaction offset, and WAL starting address values to be set manually. These are only needed when pg_resetxlog is unable to determine appropriate values by reading pg_control. Safe values can be determined as follows:
A safe value for the next transaction ID (-x) can be determined by looking for the numerically largest file name in the directory pg_clog under the data directory, adding one, and then multiplying by 1048576. Note that the file names are in hexadecimal. It is usually easiest to specify the option value in hexadecimal too. For example, if 0011 is the largest entry in pg_clog, -x 0x1200000 will work (five trailing zeroes provide the proper multiplier).
A safe value for the next multitransaction ID (first part of -m) can be determined by looking for the numerically largest file name in the directory pg_multixact/offsets under the data directory, adding one, and then multiplying by 65536. Conversely, a safe value for the oldest multitransaction ID (second part of -m) can be determined by looking for the numerically smallest file name in the same directory and multiplying by 65536. As above, the file names are in hexadecimal, so the easiest way to do this is to specify the option value in hexadecimal and append four zeroes.
A safe value for the next multitransaction offset (-O) can be determined by looking for the numerically largest file name in the directory pg_multixact/members under the data directory, adding one, and then multiplying by 52352. As above, the file names are in hexadecimal. There is no simple recipe such as the ones above of appending zeroes.
The WAL starting address (-l) should be larger than any WAL segment file name currently existing in the directory pg_xlog under the data directory. These names are also in hexadecimal and have three parts. The first part is the "timeline ID" and should usually be kept the same. For example, if 00000001000000320000004A is the largest entry in pg_xlog, use -l 00000001000000320000004B or higher.
Note: pg_resetxlog itself looks at the files in pg_xlog and chooses a default -l setting beyond the last existing file name. Therefore, manual adjustment of -l should only be needed if you are aware of WAL segment files that are not currently present in pg_xlog, such as entries in an offline archive; or if the contents of pg_xlog have been lost entirely.
There is no comparably easy way to determine a next OID that's beyond the largest one in the database, but fortunately it is not critical to get the next-OID setting right.
The transaction ID epoch is not actually stored anywhere in the database except in the field that is set by pg_resetxlog, so any value will work so far as the database itself is concerned. You might need to adjust this value to ensure that replication systems such as Slony-I work correctly — if so, an appropriate value should be obtainable from the state of the downstream replicated database.
The -n (no operation) option instructs pg_resetxlog to print the values reconstructed from pg_control and values about to be changed, and then exit without modifying anything. This is mainly a debugging tool, but can be useful as a sanity check before allowing pg_resetxlog to proceed for real.
The -V and --version options print the pg_resetxlog version and exit. The options -? and --help show supported arguments, and exit.
Notes
This command must not be used when the server is running. pg_resetxlog will refuse to start up if it finds a server lock file in the data directory. If the server crashed then a lock file might have been left behind; in that case you can remove the lock file to allow pg_resetxlog to run. But before you do so, make doubly certain that there is no server process still alive.