バージョンごとのドキュメント一覧

26.3. 継続的アーカイブとポイントインタイムリカバリ(PITR) #

<title>Continuous Archiving and Point-in-Time Recovery (PITR)</title>

At all times, <productname>PostgreSQL</productname> maintains a <firstterm>write ahead log</firstterm> (WAL) in the <filename>pg_wal/</filename> subdirectory of the cluster's data directory. The log records every change made to the database's data files. This log exists primarily for crash-safety purposes: if the system crashes, the database can be restored to consistency by <quote>replaying</quote> the log entries made since the last checkpoint. However, the existence of the log makes it possible to use a third strategy for backing up databases: we can combine a file-system-level backup with backup of the WAL files. If recovery is needed, we restore the file system backup and then replay from the backed-up WAL files to bring the system to a current state. This approach is more complex to administer than either of the previous approaches, but it has some significant benefits: PostgreSQLは常に、クラスタのデータディレクトリ以下のpg_wal/ディレクトリ内で先行書き込みログ(WAL)を管理しています。 このログはデータベースのデータファイルに行われた全ての変更を記録します。 このログは主にクラッシュ時の安全性を目的としています。 システムがクラッシュしたとしても、最後のチェックポイント以降に作成されたログ項目をやり直しすることで、データベースを整合性を維持した状態にリストアすることができます。 しかし、この存在するログファイルを使用して、データベースのバックアップ用の第3の戦略が可能になりました。 ファイルシステムレベルのバックアップとWALファイルのバックアップを組み合わせるという戦略です。 復旧が必要ならば、ファイルシステムバックアップをリストアし、その後にバックアップされたWALファイルを再生することで、システムを最新の状態にできます。 管理者にとって、この方法はこれまで説明した方法よりかなり複雑になりますが、以下のような大きな利点が複数あります。

注記

<application>pg_dump</application> and <application>pg_dumpall</application> do not produce file-system-level backups and cannot be used as part of a continuous-archiving solution. Such dumps are <emphasis>logical</emphasis> and do not contain enough information to be used by WAL replay. pg_dumppg_dumpallはファイルシステムレベルのバックアップを生成しませんので、継続的アーカイブ方式の一部として使うことはできません。 そのダンプは論理的なものであり、WALのやり直しで使うのに十分な情報を含んでいません。

As with the plain file-system-backup technique, this method can only support restoration of an entire database cluster, not a subset. Also, it requires a lot of archival storage: the base backup might be bulky, and a busy system will generate many megabytes of WAL traffic that have to be archived. Still, it is the preferred backup technique in many situations where high reliability is needed. 通常のファイルシステムバックアップ技術の場合と同様、この方法は、一部ではなく、データベースクラスタ全体のリストア処理のみをサポートできます。 また、アーカイブ用に大量の格納領域を必要とします。 ベースバックアップはかさばる場合があり、また、高負荷なシステムではアーカイブしなければならないWALの流量をメガバイト単位で生成します。 しかし、これは、高信頼性が必要な、多くの状況でむしろ好まれるバックアップ手法です。

To recover successfully using continuous archiving (also called <quote>online backup</quote> by many database vendors), you need a continuous sequence of archived WAL files that extends back at least as far as the start time of your backup. So to get started, you should set up and test your procedure for archiving WAL files <emphasis>before</emphasis> you take your first base backup. Accordingly, we first discuss the mechanics of archiving WAL files. 継続的アーカイブ(多くのデータベースベンダでオンラインバックアップとも呼ばれます)を使用して復旧を成功させるためには、少なくともバックアップの開始時点まで遡る、連続した一連のアーカイブ済みWALファイルが必要です。 ですので、運用するためには、最初のベースバックアップを取得するにWALファイルをアーカイブする手順を設定し試験しなければなりません。 したがって、まずWALファイルのアーカイブ機構について説明します。

26.3.1. WALアーカイブの設定 #

<title>Setting Up WAL Archiving</title>

In an abstract sense, a running <productname>PostgreSQL</productname> system produces an indefinitely long sequence of WAL records. The system physically divides this sequence into WAL <firstterm>segment files</firstterm>, which are normally 16MB apiece (although the segment size can be altered during <application>initdb</application>). The segment files are given numeric names that reflect their position in the abstract WAL sequence. When not using WAL archiving, the system normally creates just a few segment files and then <quote>recycles</quote> them by renaming no-longer-needed segment files to higher segment numbers. It's assumed that segment files whose contents precede the last checkpoint are no longer of interest and can be recycled. 抽象的な意味では、実行中のPostgreSQLシステムは無限に長い一連のWALレコードを生成します。 システムは物理的にこの並びを、通常1つ16メガバイト(このセグメントサイズはinitdbの実行時に変更可能です)の、WALセグメントファイルに分割します。 このセグメントファイルには、概念的なWALの並び内の位置を反映した、数字の名前が付与されます。 WALアーカイブを行わない場合、システムは通常数個のセグメントファイルを生成し、不要となったセグメントファイルの名前をより大きなセグメント番号に変更することでそれをリサイクルします。 最後のチェックポイントより前の内容を持つセグメントファイルはもはや重要でなく、リサイクルできると見なされます。

When archiving WAL data, we need to capture the contents of each segment file once it is filled, and save that data somewhere before the segment file is recycled for reuse. Depending on the application and the available hardware, there could be many different ways of <quote>saving the data somewhere</quote>: we could copy the segment files to an NFS-mounted directory on another machine, write them onto a tape drive (ensuring that you have a way of identifying the original name of each file), or batch them together and burn them onto CDs, or something else entirely. To provide the database administrator with flexibility, <productname>PostgreSQL</productname> tries not to make any assumptions about how the archiving will be done. Instead, <productname>PostgreSQL</productname> lets the administrator specify a shell command or an archive library to be executed to copy a completed segment file to wherever it needs to go. This could be as simple as a shell command that uses <literal>cp</literal>, or it could invoke a complex C function &mdash; it's all up to you. WALデータをアーカイブする場合、完成したセグメントファイルのそれぞれの内容を取り出し、再利用のために回収される前にそのデータをどこかに保存することが必要です。 アプリケーションと利用できるハードウェアに依存しますが、数多くのデータをどこかに保存する方法があります。 例えば、NFSでマウントした他のマシンのディレクトリにセグメントファイルをコピーすること、あるいは、テープ装置に書き出すこと(元々のファイル名を識別する手段があることを確認してください)、それらを一度にまとめてCDに焼くこと、そのほか全く異なったなんらかの方法などです。 柔軟性をデータベース管理者に提供するために、PostgreSQLは、どのようにアーカイブがなされたかについて一切想定しないようになっています。 その代わりにPostgreSQLは、管理者に完全なセグメントファイルをどこか必要な場所にコピーするシェルコマンドあるいはアーカイブライブラリを指定させます。 このコマンドは単純なcpを使ったシェルコマンドでも構いませんし、また、複雑なC関数を呼び出しても構いません。 全て管理者に任されています。

To enable WAL archiving, set the <xref linkend="guc-wal-level"/> configuration parameter to <literal>replica</literal> or higher, <xref linkend="guc-archive-mode"/> to <literal>on</literal>, specify the shell command to use in the <xref linkend="guc-archive-command"/> configuration parameter or specify the library to use in the <xref linkend="guc-archive-library"/> configuration parameter. In practice these settings will always be placed in the <filename>postgresql.conf</filename> file. WALアーカイブを有効にするには、wal_level設定パラメータをreplica以上に、archive_modeonに設定し、archive_command設定パラメータで使用するシェルコマンドを指定するか、archive_library設定パラメータで使用するライブラリを指定します。 実際には、これらの設定は常にpostgresql.confファイルに置かれます。

In <varname>archive_command</varname>, <literal>%p</literal> is replaced by the path name of the file to archive, while <literal>%f</literal> is replaced by only the file name. (The path name is relative to the current working directory, i.e., the cluster's data directory.) Use <literal>%%</literal> if you need to embed an actual <literal>%</literal> character in the command. The simplest useful command is something like: archive_commandでは、%pはアーカイブするファイルのパス名に置き換えられますが、%fはファイル名のみに置き換えられます。 (パス名は現在の作業ディレクトリ、つまりクラスタのデータディレクトリからの相対パスです。) 実際の%文字をコマンドに埋め込む必要がある場合は%%を使用してください。 最も簡単で便利なコマンドは以下のようなものです。

archive_command = 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'  # Unix
archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"'  # Windows

which will copy archivable WAL segments to the directory <filename>/mnt/server/archivedir</filename>. (This is an example, not a recommendation, and might not work on all platforms.) After the <literal>%p</literal> and <literal>%f</literal> parameters have been replaced, the actual command executed might look like this: これは、アーカイブ可能なWALセグメントを/mnt/server/archivedirディレクトリにコピーします (これは一例です。 推奨するものではなく、また、全てのプラットフォームで動作しない可能性があります)。 %pおよび%fパラメータが置き換えられたあと、実行された実コマンドは以下のようになります。

test ! -f /mnt/server/archivedir/00000001000000A900000065 && cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065

A similar command will be generated for each new file to be archived. 類似したコマンドがアーカイブされるそれぞれの新規ファイルに生成されます。

The archive command will be executed under the ownership of the same user that the <productname>PostgreSQL</productname> server is running as. Since the series of WAL files being archived contains effectively everything in your database, you will want to be sure that the archived data is protected from prying eyes; for example, archive into a directory that does not have group or world read access. このアーカイブ用コマンドはPostgreSQLサーバを稼働させるユーザと同じ所有権で実行されます。 アーカイブされる一連のWALファイルには、実質、データベース内の全てが含まれていますので、アーカイブしたデータをのぞき見から確実に保護しなければならないでしょう。 例えば、グループや全員に読み込み権限を付与していないディレクトリにデータをアーカイブしてください。

It is important that the archive command return zero exit status if and only if it succeeds. Upon getting a zero result, <productname>PostgreSQL</productname> will assume that the file has been successfully archived, and will remove or recycle it. However, a nonzero status tells <productname>PostgreSQL</productname> that the file was not archived; it will try again periodically until it succeeds. アーカイブ用コマンドが成功した場合のみにゼロという終了ステータスを返すことが重要です。 PostgreSQLは、ゼロという結果に基づいて、そのファイルのアーカイブが成功したことを想定し、そのファイルを削除したり回収するかもしれません。 しかし、非ゼロのステータスは、PostgreSQLに対してファイルがアーカイブされなかったことを通知し、成功するまで定期的に再試行させます。

Another way to archive is to use a custom archive module as the <varname>archive_library</varname>. Since such modules are written in <literal>C</literal>, creating your own may require considerably more effort than writing a shell command. However, archive modules can be more performant than archiving via shell, and they will have access to many useful server resources. For more information about archive modules, see <xref linkend="archive-modules"/>. アーカイブするための別の方法は、archive_libraryとしてカスタム・アーカイブ・モジュールを使用することです。 このようなモジュールはCで記述されているため、独自のモジュールを作成するには、シェル・コマンドを記述するよりもかなり多くの労力が必要になる場合があります。 しかし、アーカイブ・モジュールはシェルを介したアーカイブよりもパフォーマンスが高く、多くの有用なサーバー・リソースにアクセスできます。 アーカイブ・モジュールの詳細は第51章を参照してください。

When the archive command is terminated by a signal (other than <systemitem>SIGTERM</systemitem> that is used as part of a server shutdown) or an error by the shell with an exit status greater than 125 (such as command not found), or if the archive function emits an <literal>ERROR</literal> or <literal>FATAL</literal>, the archiver process aborts and gets restarted by the postmaster. In such cases, the failure is not reported in <xref linkend="pg-stat-archiver-view"/>. アーカイブコマンドがシグナル(サーバのシャットダウンの一部として使用されるSIGTERM以外)やシェルによる125以上の終了ステータスを持つエラー(command not foundなど)、あるいはアーカイブ関数がERRORまたはFATALを出力したことによって終了すると、アーカイバプロセスは中止され、postmasterによって再起動されます。 このような場合、失敗はpg_stat_archiverでは報告されません。

Archive commands and libraries should generally be designed to refuse to overwrite any pre-existing archive file. This is an important safety feature to preserve the integrity of your archive in case of administrator error (such as sending the output of two different servers to the same archive directory). It is advisable to test your proposed archive library to ensure that it does not overwrite an existing file. 通常アーカイブ用コマンドあるいはライブラリは、既存のアーカイブ済みファイルの上書きを行わないように設計されなければなりません。 これは、管理者のミス(例えば2つの異なるサーバの出力を同一のアーカイブ用ディレクトリに送信してしまうなど)といった場合からアーカイブ状況の整合性を保護するための安全策として重要です。 確実に既存のファイルを上書きしないように、使用予定のアーカイブライブラリを試験することをお勧めします。

In rare cases, <productname>PostgreSQL</productname> may attempt to re-archive a WAL file that was previously archived. For example, if the system crashes before the server makes a durable record of archival success, the server will attempt to archive the file again after restarting (provided archiving is still enabled). When an archive command or library encounters a pre-existing file, it should return a zero status or <literal>true</literal>, respectively, if the WAL file has identical contents to the pre-existing archive and the pre-existing archive is fully persisted to storage. If a pre-existing file contains different contents than the WAL file being archived, the archive command or library <emphasis>must</emphasis> return a nonzero status or <literal>false</literal>, respectively. まれに、PostgreSQLは以前にアーカイブされたWALファイルを再アーカイブしようとすることがあります。 たとえば、サーバがアーカイブの成功を永続的に記録する前にシステムがクラッシュした場合、サーバは再起動後にファイルを再びアーカイブしようとします(アーカイブがまだ有効になっている場合)。 アーカイブコマンドやライブラリが既に存在するファイルに遭遇した場合、WALファイルの内容が既に存在するアーカイブと同じであり、既に存在するアーカイブがストレージに完全に永続化されている場合、それぞれ0のステータス、trueを返すことが必要です。 既に存在するファイルがアーカイブされるWALファイルと異なる内容を含む場合、アーカイブコマンドやライブラリは、それぞれ0のステータス、falseを返さなければなりません

The example command above for Unix avoids overwriting a pre-existing archive by including a separate <command>test</command> step. On some Unix platforms, <command>cp</command> has switches such as <option>-i</option> that can be used to do the same thing less verbosely, but you should not rely on these without verifying that the right exit status is returned. (In particular, GNU <command>cp</command> will return status zero when <option>-i</option> is used and the target file already exists, which is <emphasis>not</emphasis> the desired behavior.) 上のUnix用のコマンド例では、別途testという段階を含めることで、既に存在するアーカイブへの上書きを防いでいます。 いくつかのUnixプラットフォームではcpコマンドには-i 引数を使うことで煩雑な出力を少なくし使うことができますが、正しい終了コードが返ることを確認せずに使用するべきではありません。 (具体的にはGNUのcpコマンドは-i オプションを使い、ターゲットファイルがすでに存在している場合、ゼロのステータスを返します。これは期待していない動作です。)

While designing your archiving setup, consider what will happen if the archive command or library fails repeatedly because some aspect requires operator intervention or the archive runs out of space. For example, this could occur if you write to tape without an autochanger; when the tape fills, nothing further can be archived until the tape is swapped. You should ensure that any error condition or request to a human operator is reported appropriately so that the situation can be resolved reasonably quickly. The <filename>pg_wal/</filename> directory will continue to fill with WAL segment files until the situation is resolved. (If the file system containing <filename>pg_wal/</filename> fills up, <productname>PostgreSQL</productname> will do a PANIC shutdown. No committed transactions will be lost, but the database will remain offline until you free some space.) アーカイブ設定を設計する時には、操作者の介入が必要であったり、アーカイブ場所の容量不足の理由でアーカイブ用コマンドあるいはライブラリが繰り返し失敗した時にどうなるかを考慮してください。 例えば、これはオートチェンジャ機能のないテープに書き出している場合に発生する可能性があります。 テープが一杯になった場合、テープを交換するまでアーカイブを行うことができなくなります。 こうした状況を相応の早さで解消できるよう、適切に操作者に対しエラーや要求を確実に連絡できるようにしなければなりません。 この状況が解消するまで、WALセグメントファイルはpg_wal/ディレクトリ内に格納され続けます。 (pg_wal/を含むファイルシステムがいっぱいになると、PostgreSQLはパニック停止します。コミットされたトランザクションは失われませんが、データベースはいくらかの容量を解放するまでオフラインのままです。)

The speed of the archive command or library is unimportant as long as it can keep up with the average rate at which your server generates WAL data. Normal operation continues even if the archiving process falls a little behind. If archiving falls significantly behind, this will increase the amount of data that would be lost in the event of a disaster. It will also mean that the <filename>pg_wal/</filename> directory will contain large numbers of not-yet-archived segment files, which could eventually exceed available disk space. You are advised to monitor the archiving process to ensure that it is working as you intend. サーバのWALデータの生成に要する平均速度に追いついている限り、アーカイブ用コマンドあるいはライブラリの処理速度は重要ではありません。 アーカイブプロセスが多少遅れたとしても通常の操作は続けられます。 アーカイブ処理がかなり遅れると、災害時に損失するデータの量が増加することになります。 また、これはpg_wal/ディレクトリ内に多くのアーカイブ処理待ちのセグメントファイルが格納され、ディスク容量が不足する状況になる可能性があることを意味します。 アーカイブ処理が確実に意図通りに動作しているかを監視することを推奨します。

In writing your archive command or library, you should assume that the file names to be archived can be up to 64 characters long and can contain any combination of ASCII letters, digits, and dots. It is not necessary to preserve the original relative path (<literal>%p</literal>) but it is necessary to preserve the file name (<literal>%f</literal>). アーカイブ用コマンドあるいはライブラリを作成する時、アーカイブされるファイル名は最長64文字までで、ASCII文字と数字とドットのどんな組合せを使用しても構いません。 元の相対パス(%p)を保存する必要はありませんが、ファイル名(%f)を保存する必要はあります。

Note that although WAL archiving will allow you to restore any modifications made to the data in your <productname>PostgreSQL</productname> database, it will not restore changes made to configuration files (that is, <filename>postgresql.conf</filename>, <filename>pg_hba.conf</filename> and <filename>pg_ident.conf</filename>), since those are edited manually rather than through SQL operations. You might wish to keep the configuration files in a location that will be backed up by your regular file system backup procedures. See <xref linkend="runtime-config-file-locations"/> for how to relocate the configuration files. WALアーカイブによってPostgreSQLデータベースでなされた変更は全てリストアすることができますが、設定ファイルはSQL操作ではなく手作業で変更されますので、設定ファイル(postgresql.confpg_hba.conf、およびpg_ident.conf)になされた変更までリストアしないことに注意してください。 通常のファイルシステムバックアップ手続きでバックアップされる場所に設定ファイルを保持したい場合があります。 設定ファイルの設置場所を変更するには20.2を参照してください。

The archive command or function is only invoked on completed WAL segments. Hence, if your server generates only little WAL traffic (or has slack periods where it does so), there could be a long delay between the completion of a transaction and its safe recording in archive storage. To put a limit on how old unarchived data can be, you can set <xref linkend="guc-archive-timeout"/> to force the server to switch to a new WAL segment file at least that often. Note that archived files that are archived early due to a forced switch are still the same length as completely full files. It is therefore unwise to set a very short <varname>archive_timeout</varname> &mdash; it will bloat your archive storage. <varname>archive_timeout</varname> settings of a minute or so are usually reasonable. アーカイブコマンドあるいは関数は完全なWALセグメントに対してのみ呼び出されます。 このため、サーバが少ししかWAL流量がない(処理を行わないなぎの期間がある)場合、トランザクションの完了とアーカイブ格納領域への安全な記録との間に長期にわたる遅延があることになります。 古い未アーカイブのデータをどうするかについて制限を付けるために、archive_timeoutを設定して、強制的にサーバを新しいWALセグメントにある程度の間隔で切り替えるようにすることができます。 強制切り替えにより早期にアーカイブされたアーカイブ済みファイルは完全に完了したファイルと同じ大きさを持つことに注意してください。 そのため、非常に小さなarchive_timeoutを使用することはお勧めしません。 格納領域を膨張させてしまいます。 通常ならば分単位のarchive_timeout設定が合理的です。

Also, you can force a segment switch manually with <function>pg_switch_wal</function> if you want to ensure that a just-finished transaction is archived as soon as possible. Other utility functions related to WAL management are listed in <xref linkend="functions-admin-backup-table"/>. 終わったばかりのトランザクションをできるだけ早くアーカイブさせたい場合、pg_switch_walを使用して手作業でセグメント切り替えを強制することができます。 この他のWAL管理に関連した関数を表 9.91に列挙します。

When <varname>wal_level</varname> is <literal>minimal</literal> some SQL commands are optimized to avoid WAL logging, as described in <xref linkend="populate-pitr"/>. If archiving or streaming replication were turned on during execution of one of these statements, WAL would not contain enough information for archive recovery. (Crash recovery is unaffected.) For this reason, <varname>wal_level</varname> can only be changed at server start. However, <varname>archive_command</varname> and <varname>archive_library</varname> can be changed with a configuration file reload. If you are archiving via shell and wish to temporarily stop archiving, one way to do it is to set <varname>archive_command</varname> to the empty string (<literal>''</literal>). This will cause WAL files to accumulate in <filename>pg_wal/</filename> until a working <varname>archive_command</varname> is re-established. wal_levelminimalの場合、14.4.7に書かれているように、いくつかのSQLコマンドはWALロギングを回避するため最適化されます。 アーカイビングもしくはストリーミングレプリケーションがこれら構文の1つを実行中に作動させられると、アーカイブ復旧のための十分な情報をWALが含まなくなります。(クラッシュ復旧は影響を受けません。) このことにより、wal_levelはサーバの起動時のみ変更可能です。 とは言っても、archive_commandarchive_libraryは構成ファイルを再読み込みすることで変更できます。 シェルでアーカイブしており、一時的にアーカイビングを停止したい場合、1つの方法はarchive_commandを空文字列('')に設定することです。 このようにすると、動作するarchive_commandが再構築されるまでWALファイルはpg_wal/に蓄積します。

26.3.2. ベースバックアップの作成 #

<title>Making a Base Backup</title>

The easiest way to perform a base backup is to use the <xref linkend="app-pgbasebackup"/> tool. It can create a base backup either as regular files or as a tar archive. If more flexibility than <xref linkend="app-pgbasebackup"/> can provide is required, you can also make a base backup using the low level API (see <xref linkend="backup-lowlevel-base-backup"/>). ベースバックアップを取得する最も簡単な方法はpg_basebackup を実行する方法です。 通常のファイルやTAR形式のファイルとしてベースバックアップを取得することができます。 もし、pg_basebackupより柔軟性が求められる場合は、低レベルなAPIを使ってバックアップを作成することもできます(詳細は 26.3.3を参照)。

It is not necessary to be concerned about the amount of time it takes to make a base backup. However, if you normally run the server with <varname>full_page_writes</varname> disabled, you might notice a drop in performance while the backup runs since <varname>full_page_writes</varname> is effectively forced on during backup mode. ベースバックアップを取得するための時間を考慮する必要はありません。 しかし、普段、full_page_writesを無効にして運用している場合、バックアップ取得中は強制的にfull_page_writesが有効になるため、パフォーマンスが落ちていると感じる可能性があります。

To make use of the backup, you will need to keep all the WAL segment files generated during and after the file system backup. To aid you in doing this, the base backup process creates a <firstterm>backup history file</firstterm> that is immediately stored into the WAL archive area. This file is named after the first WAL segment file that you need for the file system backup. For example, if the starting WAL file is <literal>0000000100001234000055CD</literal> the backup history file will be named something like <literal>0000000100001234000055CD.007C9330.backup</literal>. (The second part of the file name stands for an exact position within the WAL file, and can ordinarily be ignored.) Once you have safely archived the file system backup and the WAL segment files used during the backup (as specified in the backup history file), all archived WAL segments with names numerically less are no longer needed to recover the file system backup and can be deleted. However, you should consider keeping several backup sets to be absolutely certain that you can recover your data. バックアップを使用するためには、ファイルシステムのバックアップ取得中、および、その後に生成されるWALセグメントファイル全てが保存されている必要があります。 この目的のために、ベースバックアップの過程で即座にWALアーカイブ領域にバックアップ履歴ファイルが作成されます。 このファイルにはファイルシステムのバックアップに最初に必要とされるWALセグメントの名前が付けられます。 例えば、最初のWALファイルが 0000000100001234000055CDである場合、バックアップ履歴ファイルは0000000100001234000055CD.007C9330.backupというように名付けられます。 (ファイル名の2番目のパートはWALファイルの厳密な位置が記載されます。通常は無視することができます。) 一旦、安全にファイルシステムのバックアップとそのバックアップ中に使用されたWALセグメントファイル(バックアップ履歴ファイルから特定できます)を取得すると、それより数値の小さな全てのWALアーカイブセグメントはファイルシステムの復旧には必要が無く、削除することができます。 しかし、データを確実に復旧させるためには数世代のバックアップセットを保持することを考慮すべきです。

The backup history file is just a small text file. It contains the label string you gave to <xref linkend="app-pgbasebackup"/>, as well as the starting and ending times and WAL segments of the backup. If you used the label to identify the associated dump file, then the archived history file is enough to tell you which dump file to restore. バックアップ履歴ファイルは、ほんの小さなテキストファイルです。 これにはpg_basebackupで与えたラベル文字列の他、バックアップの開始、終了時間およびバックアップのWALセグメントが含まれます。 このラベルをバックアップを構成するために使うことで、アーカイブ履歴ファイルはどのバックアップをリストアするべきか間違いなく判断することができます。

Since you have to keep around all the archived WAL files back to your last base backup, the interval between base backups should usually be chosen based on how much storage you want to expend on archived WAL files. You should also consider how long you are prepared to spend recovering, if recovery should be necessary &mdash; the system will have to replay all those WAL segments, and that could take awhile if it has been a long time since the last base backup. 最後のベースバックアップ以降のWALアーカイブを保持し続ける必要があるため、通常、ベースバックアップを取得すべき期間は、WALアーカイブを保持するためにどのくらいのストレージを拡張できるかによって決定されます。 また、復旧が必要になった場合に、どのくらいの時間を復旧に使うと覚悟するのかも考慮すべきです。— システムは全てのWALセグメントを適用する必要があるため、もし、最後のベースバックアップを取得してから長い時間が経過している場合、適用に時間を要する可能性があります。

26.3.3. 低レベルAPIを使用したベースバックアップの作成 #

<title>Making a Base Backup Using the Low Level API</title>

The procedure for making a base backup using the low level APIs contains a few more steps than the <xref linkend="app-pgbasebackup"/> method, but is relatively simple. It is very important that these steps are executed in sequence, and that the success of a step is verified before proceeding to the next step. 低レベルのAPIを使ったベースバックアップを取得するにはpg_basebackup を使う方法に加えて数ステップが必要ですが、比較的簡単です。 これらのステップは順番に実行することが重要で、次のステップに進む前にこれらのステップが成功していることを確認する必要があります。

Multiple backups are able to be run concurrently (both those started using this backup API and those started using <xref linkend="app-pgbasebackup"/>). 複数のバックアップを同時に実行できます(このバックアップAPIを使用して開始されたバックアップとpg_basebackupを使用して開始されたバックアップの両方)。

  1. Ensure that WAL archiving is enabled and working. WALアーカイブが有効であり、正常に動作することを確認してください。

  2. Connect to the server (it does not matter which database) as a user with rights to run <function>pg_backup_start</function> (superuser, or a user who has been granted <literal>EXECUTE</literal> on the function) and issue the command: pg_backup_startの実行権限を持つユーザとしてサーバ(どのデータベースであってもかまいません)に接続します。ユーザはスーパーユーザか、またはこの関数にEXECUTE権限を与えられたユーザです。以下のコマンドを発行します。

    SELECT pg_backup_start(label => 'label', fast => false);
    

    where <literal>label</literal> is any string you want to use to uniquely identify this backup operation. The connection calling <function>pg_backup_start</function> must be maintained until the end of the backup, or the backup will be automatically aborted. ここでlabelは、このバックアップ操作を一意に識別するために使用したい文字列です。 pg_backup_startを呼び出す接続は、バックアップが終了するまで維持されなければなりません。 さもないと、バックアップは自動的に打ち切られます。

    Online backups are always started at the beginning of a checkpoint. By default, <function>pg_backup_start</function> will wait for the next regularly scheduled checkpoint to complete, which may take a long time (see the configuration parameters <xref linkend="guc-checkpoint-timeout"/> and <xref linkend="guc-checkpoint-completion-target"/>). This is usually preferable as it minimizes the impact on the running system. If you want to start the backup as soon as possible, pass <literal>true</literal> as the second parameter to <function>pg_backup_start</function> and it will request an immediate checkpoint, which will finish as fast as possible using as much I/O as possible. オンラインバックアップは、常にチェックポイントの先頭から開始されます。 デフォルトでは、pg_backup_startは、次の定期的にスケジュールされたチェックポイントが完了するまで待機します。 これには長い時間がかかる場合があります(設定パラメータcheckpoint_timeoutおよびcheckpoint_completion_targetを参照してください)。 これは、実行中のシステムへの影響を最小限に抑えるため、通常は望ましい方法です。 できるだけ早くバックアップを開始したい場合は、pg_backup_startの2番目のパラメータとしてtrueを渡すと、即時のチェックポイントが要求されます。 このチェックポイントは、できるだけ多くのI/Oを使用してできるだけ早く完了します。

  3. Perform the backup, using any convenient file-system-backup tool such as <application>tar</application> or <application>cpio</application> (not <application>pg_dump</application> or <application>pg_dumpall</application>). It is neither necessary nor desirable to stop normal operation of the database while you do this. See <xref linkend="backup-lowlevel-base-backup-data"/> for things to consider during this backup. pg_dumppg_dumpallではなく)tarcpioなどの使い慣れた任意のファイルシステムバックアップツールを使用して、バックアップを実行してください。 この作業時に、データベースの通常の操作を停止することは不要ですし、望ましい方法でもありません。 このバックアップの実行中に考慮すべき点は26.3.3.1を参照してください。

  4. In the same connection as before, issue the command: 以前と同じ接続の中で、以下のコマンドを実行します。

    SELECT * FROM pg_backup_stop(wait_for_archive => true);
    

    This terminates backup mode. On a primary, it also performs an automatic switch to the next WAL segment. On a standby, it is not possible to automatically switch WAL segments, so you may wish to run <function>pg_switch_wal</function> on the primary to perform a manual switch. The reason for the switch is to arrange for the last WAL segment file written during the backup interval to be ready to archive. これはバックアップモードを終了し、プライマリでは、次のWALセグメントへの自動切換えを行います。 スタンバイでは、WALセグメントを自動的に切り替えることはできません。 ですから、手動切り替えを行うためにプライマリでpg_switch_walを実行することをお勧めします。 この切換えの理由は、バックアップ期間中に書き出された最後のWALファイルがアーカイブできるよう準備することです。

    <function>pg_backup_stop</function> will return one row with three values. The second of these fields should be written to a file named <filename>backup_label</filename> in the root directory of the backup. The third field should be written to a file named <filename>tablespace_map</filename> unless the field is empty. These files are vital to the backup working and must be written byte for byte without modification, which may require opening the file in binary mode. pg_backup_stopは3つの値を含んだ1行を返します。 2番目の値は、バックアップのルートディレクトリ内のbackup_labelという名称のファイルを作成の上、値を書き込む必要があります。 3番目の値は、空でない限りはtablespace_mapという名称のファイルを作成の上、値を書き込む必要があります。 これらのファイルはバックアップが動作するために極めて重要であり、1バイトも変更なしに書き込まれる必要があるため、バイナリモードで開かれる必要があるかもしれません。

  5. Once the WAL segment files active during the backup are archived, you are done. The file identified by <function>pg_backup_stop</function>'s first return value is the last segment that is required to form a complete set of backup files. On a primary, if <varname>archive_mode</varname> is enabled and the <literal>wait_for_archive</literal> parameter is <literal>true</literal>, <function>pg_backup_stop</function> does not return until the last segment has been archived. On a standby, <varname>archive_mode</varname> must be <literal>always</literal> in order for <function>pg_backup_stop</function> to wait. Archiving of these files happens automatically since you have already configured <varname>archive_command</varname> or <varname>archive_library</varname>. In most cases this happens quickly, but you are advised to monitor your archive system to ensure there are no delays. If the archive process has fallen behind because of failures of the archive command or library, it will keep retrying until the archive succeeds and the backup is complete. If you wish to place a time limit on the execution of <function>pg_backup_stop</function>, set an appropriate <varname>statement_timeout</varname> value, but make note that if <function>pg_backup_stop</function> terminates because of this your backup may not be valid. バックアップ中に使用されたWALセグメントファイルがアーカイブされれば完了です。 pg_backup_stopの返り値の1番目の値で識別されるファイルは、バックアップファイル一式を完結させるのに必要となる最終セグメントです。 プライマリでは、archive_modeが有効で、かつwait_for_archiveパラメータがtrueであれば、pg_backup_stop は最終セグメントがアーカイブされるまで戻りません。 スタンバイでは、pg_backup_stopがアーカイブ完了を待つためには、archive_modealwaysでなければなりません。 すでにarchive_commandあるいはarchive_libraryを設定していますので、これらのファイルのアーカイブ操作は自動的に発生します。 ほとんどの場合、これは瞬時に行われます。 しかし、バックアップの完了を確認できるよう、アーカイブシステムを監視し、遅延が無いことの確認をお勧めします。 アーカイブコマンドの失敗によりアーカイブ処理が遅れてしまったとしても、アーカイブが成功し、そしてバックアップが完了するまで再試行を繰り返すようになっています。 pg_backup_stop実行においての時間期限を設けたい場合、適切なstatement_timeoutの値を設定できますが、この設定値によってpg_backup_stopが中断したときにバックアップが正当ではない可能性があるということを肝に銘じてください。

    If the backup process monitors and ensures that all WAL segment files required for the backup are successfully archived then the <literal>wait_for_archive</literal> parameter (which defaults to true) can be set to false to have <function>pg_backup_stop</function> return as soon as the stop backup record is written to the WAL. By default, <function>pg_backup_stop</function> will wait until all WAL has been archived, which can take some time. This option must be used with caution: if WAL archiving is not monitored correctly then the backup might not include all of the WAL files and will therefore be incomplete and not able to be restored. バックアップに必要なすべてのWALセグメントファイルのアーカイブが成功したことを、バックアップ作業の中で監視して確認するのであれば、wait_for_archiveパラメータ(デフォルトでtrueです)をfalseに設定し、バックアップレコードがWALに書き込まれたら即座にpg_backup_stopが戻るようにすることができます。 デフォルトでは、pg_backup_stopはすべてのWALがアーカイブされるのを待つので、少し時間がかかることがあります。 このオプションは慎重に使わなければなりません。 WALのアーカイブを適切に監視していない場合、バックアップにはすべてのWALファイルが含まれず、不完全かもしれません。 そうなると、リストアできません。

26.3.3.1. データディレクトリのバックアップ #

<title>Backing Up the Data Directory</title>

Some file system backup tools emit warnings or errors if the files they are trying to copy change while the copy proceeds. When taking a base backup of an active database, this situation is normal and not an error. However, you need to ensure that you can distinguish complaints of this sort from real errors. For example, some versions of <application>rsync</application> return a separate exit code for <quote>vanished source files</quote>, and you can write a driver script to accept this exit code as a non-error case. Also, some versions of GNU <application>tar</application> return an error code indistinguishable from a fatal error if a file was truncated while <application>tar</application> was copying it. Fortunately, GNU <application>tar</application> versions 1.16 and later exit with 1 if a file was changed during the backup, and 2 for other errors. With GNU <application>tar</application> version 1.23 and later, you can use the warning options <literal>&#45;-warning=no-file-changed &#45;-warning=no-file-removed</literal> to hide the related warning messages. ファイルシステムのバックアップツール中には複写している途中でファイルが変更されると警告もしくはエラーを報告するものがあります。 稼働しているデータベースのベースバックアップを取っている場合には、この状況は正常でエラーではありません。 しかし、この種の警告と本当のエラーとを区別できるか確認が必要です。 例えば、rsyncのバージョンによっては消滅したソースファイルに対して別の終了コードを返し、そしてこの終了コードをエラーではないと受け付けるドライバスクリプトを記述することができます。 同時にGNU tarのバージョンによっては、tarがそれを複写していた途中でファイルが切り詰められると、致命的エラーと識別できないエラーコードを返します。 ありがたいことに、GNU tarのバージョン1.16もしくはそれ以降では、バックアップ中にファイルが変更されると1で、それ以外のエラーの時は2でプログラムから抜けます。 GNUの tarで1.23以降のバージョンを使用しているのであれば、--warning=no-file-changed --warning=no-file-removedオプションをつけることで関連する警告メッセージを隠すオプションを使用することができます。

Be certain that your backup includes all of the files under the database cluster directory (e.g., <filename>/usr/local/pgsql/data</filename>). If you are using tablespaces that do not reside underneath this directory, be careful to include them as well (and be sure that your backup archives symbolic links as links, otherwise the restore will corrupt your tablespaces). バックアップに、データベースクラスタディレクトリ(例えば/usr/local/pgsql/data)以下にある全てのファイルが含まれていることを確認してください。 このディレクトリ以下に存在しないテーブル空間を使用している場合、注意して、同様にそれらを含めてください (そして、バックアップがリンクとしてシンボリックリンクをアーカイブしていることを確認してください。 さもないとリストアはテーブル空間を壊してしまいます)。

You should, however, omit from the backup the files within the cluster's <filename>pg_wal/</filename> subdirectory. This slight adjustment is worthwhile because it reduces the risk of mistakes when restoring. This is easy to arrange if <filename>pg_wal/</filename> is a symbolic link pointing to someplace outside the cluster directory, which is a common setup anyway for performance reasons. You might also want to exclude <filename>postmaster.pid</filename> and <filename>postmaster.opts</filename>, which record information about the running <application>postmaster</application>, not about the <application>postmaster</application> which will eventually use this backup. (These files can confuse <application>pg_ctl</application>.) しかし、クラスタのpg_wal/サブディレクトリにあるファイルをバックアップから省いてください。 このちょっとした調整は、リストア処理中の失敗の危険性を低減できますので、行う価値があります。 pg_wal/がクラスタディレクトリ外のどこかを指し示すシンボリックリンクの場合は調整が簡単です。 これは性能上の理由でよく使用される設定です。 また、いずれこのバックアップを使うpostmasterではなく、今起動しているpostmasterの情報を記録しているpostmaster.pidpostmaster.optsも除外できます。 (これらのファイルはpg_ctlを誤作動させる可能性があります。)

It is often a good idea to also omit from the backup the files within the cluster's <filename>pg_replslot/</filename> directory, so that replication slots that exist on the primary do not become part of the backup. Otherwise, the subsequent use of the backup to create a standby may result in indefinite retention of WAL files on the standby, and possibly bloat on the primary if hot standby feedback is enabled, because the clients that are using those replication slots will still be connecting to and updating the slots on the primary, not the standby. Even if the backup is only intended for use in creating a new primary, copying the replication slots isn't expected to be particularly useful, since the contents of those slots will likely be badly out of date by the time the new primary comes on line. プライマリ上に存在するレプリケーションスロットがバックアップに含まれないようにするために、クラスタの中のpg_replslot/ディレクトリをバックアップから除くのもしばしば良い考えです。 もし、スタンバイを作成するためのバックアップを続けて使用すると、スタンバイのWALファイルの保持を無制限に保留する結果になり、ホットスタンバイからのフィードバックを有効にしている場合、プライマリのWALを膨張させます。 これは、これらのレプリケーションスロットを使っているクライアントはまだ、スタンバイではなく、プライマリのスロットを接続し続け、更新しているからです。 バックアップが新しいプライマリを作成するためだけに作成されたとしても、レプリケーションスロットをコピーすることは特に有益であるとは考えられません。 このようにバックアップにレプリケーションスロットを含むことは、新しいプライマリがオンラインになったときにはスロットの内容が期限切れしており、有害である可能性があります。

The contents of the directories <filename>pg_dynshmem/</filename>, <filename>pg_notify/</filename>, <filename>pg_serial/</filename>, <filename>pg_snapshots/</filename>, <filename>pg_stat_tmp/</filename>, and <filename>pg_subtrans/</filename> (but not the directories themselves) can be omitted from the backup as they will be initialized on postmaster startup. ディレクトリpg_dynshmem/pg_notify/pg_serial/pg_snapshots/pg_stat_tmp/pg_subtrans/の中身はバックアップから除外できます。(ただし、ディレクトリ自体は除外できません。) というのも、postmaster起動時に初期化されるからです。

Any file or directory beginning with <filename>pgsql_tmp</filename> can be omitted from the backup. These files are removed on postmaster start and the directories will be recreated as needed. pgsql_tmpで始まるすべてのファイルとディレクトリはバックアップから除外できます。 これらのファイルはpostmasterの起動時に削除されますし、ディレクトリも必要なら再作成されます。

<filename>pg_internal.init</filename> files can be omitted from the backup whenever a file of that name is found. These files contain relation cache data that is always rebuilt when recovering. pg_internal.initという名前のファイルが見つかった場合、それはバックアップから省くことができます。 このファイルはリレーションキャッシュデータを含んでおり、常にリカバリの際に再構築されます。

The backup label file includes the label string you gave to <function>pg_backup_start</function>, as well as the time at which <function>pg_backup_start</function> was run, and the name of the starting WAL file. In case of confusion it is therefore possible to look inside a backup file and determine exactly which backup session the dump file came from. The tablespace map file includes the symbolic link names as they exist in the directory <filename>pg_tblspc/</filename> and the full path of each symbolic link. These files are not merely for your information; their presence and contents are critical to the proper operation of the system's recovery process. バックアップラベルファイルには、pg_backup_startに付与したラベル文字列とpg_backup_startが実行された時刻、最初のWALファイルの名前が含まれます。 したがって、当惑した時にバックアップファイルの中身を検索し、そのダンプファイルがどのバックアップセッションに由来したものかを確認することができます。 テーブル空間マップファイルにはディレクトリpg_tblspc/に存在するシンボリックリンク名と各シンボリックリンクのフルパスが含まれています。 このファイルはあなたのためだけの情報ではありません。 その存在と内容はシステムのリカバリプロセスが適切に動作するために非常に重要です。

It is also possible to make a backup while the server is stopped. In this case, you obviously cannot use <function>pg_backup_start</function> or <function>pg_backup_stop</function>, and you will therefore be left to your own devices to keep track of which backup is which and how far back the associated WAL files go. It is generally better to follow the continuous archiving procedure above. サーバが停止している時にバックアップを作成することも可能です。 この場合、わかりきったことですが、pg_backup_startpg_backup_stopを使用することができません。 そのため、どのバックアップが、どのWALファイルと関連し、どこまで戻せばよいかを独自の方法で残さなければなりません。 通常は、上述の継続的アーカイブ手順に従う方をお勧めします。

26.3.4. 継続的アーカイブによるバックアップを使用した復旧 #

<title>Recovering Using a Continuous Archive Backup</title>

Okay, the worst has happened and you need to recover from your backup. Here is the procedure: さて、最悪の事態が発生し、バックアップから復旧する必要が出てきたものとします。 以下にその手順を説明します。

  1. Stop the server, if it's running. もし稼働しているのであればサーバを停止してください。

  2. If you have the space to do so, copy the whole cluster data directory and any tablespaces to a temporary location in case you need them later. Note that this precaution will require that you have enough free space on your system to hold two copies of your existing database. If you do not have enough space, you should at least save the contents of the cluster's <filename>pg_wal</filename> subdirectory, as it might contain WAL files which were not archived before the system went down. もし容量があるのであれば、後で必要になる場合に備えてクラスタデータディレクトリ全体とテーブル空間を全て一時的な場所にコピーしてください。 この予防措置は、既存のデータベースを2つ分保持できるだけの空き領域を必要とします。 十分な領域がない場合でも、少なくともクラスタのpg_walサブディレクトリの内容は保存すべきです。 ここには、システムが停止する前にアーカイブされなかったWALファイルが含まれているかも知れないからです。

  3. Remove all existing files and subdirectories under the cluster data directory and under the root directories of any tablespaces you are using. クラスタデータディレクトリ以下、および、使用中のテーブル空間の最上位ディレクトリ以下にある既存の全てのファイルとサブディレクトリを削除してください。

  4. Restore the database files from your file system backup. Be sure that they are restored with the right ownership (the database system user, not <literal>root</literal>!) and with the right permissions. If you are using tablespaces, you should verify that the symbolic links in <filename>pg_tblspc/</filename> were correctly restored. ファイルシステムバックアップからデータベースファイルをリストアします。 ファイルが正しい所有権(rootではなくデータベースシステムユーザです!)でリストアされていることを確認してください。 テーブル空間を使用している場合は、pg_tblspc/内のシンボリックリンクが正しくリストアされていることを検証する必要があります。

  5. Remove any files present in <filename>pg_wal/</filename>; these came from the file system backup and are therefore probably obsolete rather than current. If you didn't archive <filename>pg_wal/</filename> at all, then recreate it with proper permissions, being careful to ensure that you re-establish it as a symbolic link if you had it set up that way before. pg_wal/内にあるファイルをすべて削除してください。 これらはファイルシステムバックアップから生成されたものであり、おそらく現在のものより古く使用できないものです。 pg_wal/をまったくアーカイブしていなければ、適切な権限で再作成してください。 以前シンボリックリンクとして設定していたのであれば、そのように確実に再構築するように注意してください。

  6. If you have unarchived WAL segment files that you saved in step 2, copy them into <filename>pg_wal/</filename>. (It is best to copy them, not move them, so you still have the unmodified files if a problem occurs and you have to start over.) 手順2で退避させた未アーカイブのWALセグメントファイルがあるのであれば、pg_wal/にコピーしてください。 (問題が発生し、初めからやり直さなければならない場合に未変更のファイルが残るように、移動させるのではなくコピーすることが最善です。)

  7. Set recovery configuration settings in <filename>postgresql.conf</filename> (see <xref linkend="runtime-config-wal-archive-recovery"/>) and create a file <filename>recovery.signal</filename> in the cluster data directory. You might also want to temporarily modify <filename>pg_hba.conf</filename> to prevent ordinary users from connecting until you are sure the recovery was successful. postgresql.conf20.5.5を参照してください)に復旧の設定を記述し、クラスタデータディレクトリにrecovery.signalファイルを作成します。 また、一時的にpg_hba.confを変更し、復旧の成功を確認できるまで一般ユーザが接続できないようにする必要があるかもしれません。

  8. Start the server. The server will go into recovery mode and proceed to read through the archived WAL files it needs. Should the recovery be terminated because of an external error, the server can simply be restarted and it will continue recovery. Upon completion of the recovery process, the server will remove <filename>recovery.signal</filename> (to prevent accidentally re-entering recovery mode later) and then commence normal database operations. サーバを起動してください。 サーバは復旧モードに入り、必要なアーカイブ済みWALファイル群の読み込みを行います。 外部的なエラーにより復旧が中断したら、サーバを単に再起動させて、復旧処理を継続してください。 復旧処理が完了したら、(誤って後で復旧モードに再度入らないように)サーバはrecovery.signalを削除します。 その後通常のデータベース操作を開始します。

  9. Inspect the contents of the database to ensure you have recovered to the desired state. If not, return to step 1. If all is well, allow your users to connect by restoring <filename>pg_hba.conf</filename> to normal. データベースの内容を検査し、希望する状態まで復旧できていることを確認してください。 復旧できなかった場合は手順1に戻ってください。 全て問題なければ、ユーザが接続できるようにpg_hba.confを正常状態に戻してください。

The key part of all this is to set up a recovery configuration that describes how you want to recover and how far the recovery should run. The one thing that you absolutely must specify is the <varname>restore_command</varname>, which tells <productname>PostgreSQL</productname> how to retrieve archived WAL file segments. Like the <varname>archive_command</varname>, this is a shell command string. It can contain <literal>%f</literal>, which is replaced by the name of the desired WAL file, and <literal>%p</literal>, which is replaced by the path name to copy the WAL file to. (The path name is relative to the current working directory, i.e., the cluster's data directory.) Write <literal>%%</literal> if you need to embed an actual <literal>%</literal> character in the command. The simplest useful command is something like: ここで重要となるのは、どのように復旧させたいのかやどこまで復旧させたいかを記述する復旧設定を設定することです。 絶対に指定しなければならないことは、アーカイブ済みWALファイルセグメントをどのように戻すかをPostgreSQLに通知するrestore_commandです。 archive_command同様、これはシェルコマンド文字列です。 ここには、対象のWALファイルの名前で置換される%fやWALファイルのコピー先を示すパスで置換される%pを含めることができます。 (パス名は現在の作業用ディレクトリ、つまり、クラスタのデータディレクトリから見た相対パスです。) コマンド内に%文字自体を埋め込む必要があれば%%と記載してください。 最も簡単でよく使われるコマンドは以下のようなものです。

restore_command = 'cp /mnt/server/archivedir/%f %p'

which will copy previously archived WAL segments from the directory <filename>/mnt/server/archivedir</filename>. Of course, you can use something much more complicated, perhaps even a shell script that requests the operator to mount an appropriate tape. これは事前にアーカイブされたWALセグメントを/mnt/server/archivedirディレクトリからコピーします。 当然ながら、もっと複雑なものを使用することができます。 例えば、操作者に適切なテープをマウントさせることを要求するようなシェルスクリプトでさえ可能です。

It is important that the command return nonzero exit status on failure. The command <emphasis>will</emphasis> be called requesting files that are not present in the archive; it must return nonzero when so asked. This is not an error condition. An exception is that if the command was terminated by a signal (other than <systemitem>SIGTERM</systemitem>, which is used as part of a database server shutdown) or an error by the shell (such as command not found), then recovery will abort and the server will not start up. このコマンドが失敗した時に非ゼロの終了ステータスを返すことが重要です。 このコマンドは、アーカイブに存在しないファイルを要求するかもしれませんが、その場合でも非ゼロを返さなければなりません。 これはエラー状態ではありません。 例外は、コマンドがシグナルによって中断された場合(データベースの停止に使用されるSIGTERM以外)か、シェルによるエラー(コマンドが見つかりませんなど)で復旧が中断され、サーバが起動しない場合です。

Not all of the requested files will be WAL segment files; you should also expect requests for files with a suffix of <literal>.history</literal>. Also be aware that the base name of the <literal>%p</literal> path will be different from <literal>%f</literal>; do not expect them to be interchangeable. 要求されるファイルはWALセグメントファイルだけではありません。 .historyが付いているファイルが要求されることも想定しなければなりません。 同時に、%pパスのファイル名部分は%fと異なることに注意してください。 これらが相互に置き換え可能であるとは考えないでください。

WAL segments that cannot be found in the archive will be sought in <filename>pg_wal/</filename>; this allows use of recent un-archived segments. However, segments that are available from the archive will be used in preference to files in <filename>pg_wal/</filename>. アーカイブ場所で見つけられなかったWALセグメントはpg_wal/から検索されます。 これにより、最近の未アーカイブのセグメントを使用することができます。 しかし、アーカイブ場所から利用できるセグメントはpg_wal/内のファイルよりも優先的に使用されます。

Normally, recovery will proceed through all available WAL segments, thereby restoring the database to the current point in time (or as close as possible given the available WAL segments). Therefore, a normal recovery will end with a <quote>file not found</quote> message, the exact text of the error message depending upon your choice of <varname>restore_command</varname>. You may also see an error message at the start of recovery for a file named something like <filename>00000001.history</filename>. This is also normal and does not indicate a problem in simple recovery situations; see <xref linkend="backup-timelines"/> for discussion. 通常は利用可能な全てのWALセグメントを使用して復旧処理が行われます。 その結果、データベースを現時点まで(もしくは、利用可能なWALセグメントで得られる限り現在に近い時点まで)リストアします。 従って、通常の復旧はfile not foundメッセージで終了します。 エラーメッセージの正確な文言はrestore_commandの選択によります。 また、復旧の開始時点で00000001.historyのようなファイル名のエラーメッセージが出ることがあります。 これも単純な復旧作業では不具合を意味するものでなく正常です。 論議については26.3.5を参照してください。

If you want to recover to some previous point in time (say, right before the junior DBA dropped your main transaction table), just specify the required <link linkend="runtime-config-wal-recovery-target">stopping point</link>. You can specify the stop point, known as the <quote>recovery target</quote>, either by date/time, named restore point or by completion of a specific transaction ID. As of this writing only the date/time and named restore point options are very usable, since there are no tools to help you identify with any accuracy which transaction ID to use. もし以前のある時点まで復旧させたい場合(例えば、経験不足のデータベース管理者が主トランザクションテーブルを消去した直前)、要求する停止時点を指定するだけです。 停止時点は、recovery targetとして既知の停止時点で指定することも、日付と時刻で指定することも、リストアポイントか完了した特定のトランザクションIDで指定することもできます。 本ドキュメントの執筆時点では使用するトランザクションIDの識別を補助するツールがありませんので、ほとんどの場合は日付と時刻による指定のみを使用することになるでしょう。

注記

The stop point must be after the ending time of the base backup, i.e., the end time of <function>pg_backup_stop</function>. You cannot use a base backup to recover to a time when that backup was in progress. (To recover to such a time, you must go back to your previous base backup and roll forward from there.) 停止時点はバックアップの終了時刻、つまり、pg_backup_stopの最終時刻より後の時点でなければなりません。 バックアップを行っている最中のある時点までベースバックアップを使用して復旧させることはできません (こうした時点まで復旧させるには、その前のベースバックアップまで戻って、そこからロールフォワードしてください)。

If recovery finds corrupted WAL data, recovery will halt at that point and the server will not start. In such a case the recovery process could be re-run from the beginning, specifying a <quote>recovery target</quote> before the point of corruption so that recovery can complete normally. If recovery fails for an external reason, such as a system crash or if the WAL archive has become inaccessible, then the recovery can simply be restarted and it will restart almost from where it failed. Recovery restart works much like checkpointing in normal operation: the server periodically forces all its state to disk, and then updates the <filename>pg_control</filename> file to indicate that the already-processed WAL data need not be scanned again. 復旧時にWALデータの破損がわかると、復旧はその時点で止まり、サーバは起動しません。 こうした場合、復旧対象に破損時点より前の時点を指定することで、復旧処理が正常に完了できるよう、復旧プロセスを初めからやり直すことができます。 システムクラッシュなど外的理由により復旧処理が失敗した場合やWALアーカイブがアクセスできなくなった場合、復旧処理を単に再起動させることができます。 この場合は失敗した時点とほぼ同じところから再開します。 復旧処理の再起動は、次のような通常操作時のチェックポイント処理とほぼ同様に動作します。 サーバは定期的にすべての状態をディスクに強制し、再度スキャンする必要がない処理済みのWALデータを示すpg_controlファイルを更新します。

26.3.5. タイムライン #

<title>Timelines</title>

The ability to restore the database to a previous point in time creates some complexities that are akin to science-fiction stories about time travel and parallel universes. For example, in the original history of the database, suppose you dropped a critical table at 5:15PM on Tuesday evening, but didn't realize your mistake until Wednesday noon. Unfazed, you get out your backup, restore to the point-in-time 5:14PM Tuesday evening, and are up and running. In <emphasis>this</emphasis> history of the database universe, you never dropped the table. But suppose you later realize this wasn't such a great idea, and would like to return to sometime Wednesday morning in the original history. You won't be able to if, while your database was up-and-running, it overwrote some of the WAL segment files that led up to the time you now wish you could get back to. Thus, to avoid this, you need to distinguish the series of WAL records generated after you've done a point-in-time recovery from those that were generated in the original database history. 過去のある時点までデータベースを復旧できる機能は、タイムトラベルやパラレルユニバースといったSFの物語に類似した、多少の複雑性があります。 例えば、データベースの元の履歴で、火曜日の夕方5:15PMに重要なテーブルを削除し、水曜日のお昼まで手違いに気が付かなかったとします。 慌てずに、バックアップを取り出して、火曜日の夕方5:14PMの時点にリストアし、データベースを起動させます。 データベース世界のこの履歴では、そのテーブルを削除していません。 しかし、後になって、これは大した問題ではなかったことが分かり、元の履歴における水曜日に朝の何時かにまで戻したいと考えたと仮定しましょう。 データベースは既に起動していますので、元に戻したい時点に至るWALセグメントファイルの一部は上書きされていて、戻すことはできないかもしれません。 ですので、このことを避けるために、ポイントインタイムで復旧させた後に生成された一連のWALレコードと元のデータベースの履歴において生成されたWALレコードとを区別する必要があります。

To deal with this problem, <productname>PostgreSQL</productname> has a notion of <firstterm>timelines</firstterm>. Whenever an archive recovery completes, a new timeline is created to identify the series of WAL records generated after that recovery. The timeline ID number is part of WAL segment file names so a new timeline does not overwrite the WAL data generated by previous timelines. For example, in the WAL file name <filename>0000000100001234000055CD</filename>, the leading <literal>00000001</literal> is the timeline ID in hexadecimal. (Note that in other contexts, such as server log messages, timeline IDs are usually printed in decimal.) こうした問題を扱うためにPostgreSQLにはタイムラインという概念があります。 アーカイブ復旧が完了したときはいつでも、その復旧後に生成されたWALレコードを識別するための新しいタイムラインが生成されます。 タイムラインID番号はWALセグメントファイル名の一部です。ですので、新しいタイムラインはこれまでのタイムラインで生成されたWALデータを上書きしません。 たとえば、WALファイル名が0000000100001234000055CDの場合、先頭の00000001は16進数でのタイムラインIDです。 (たとえばサーバログメッセージのような他のコンテキストの場合、タイムラインIDは通常10進数で表示されることに注意してください。)

It is in fact possible to archive many different timelines. While that might seem like a useless feature, it's often a lifesaver. Consider the situation where you aren't quite sure what point-in-time to recover to, and so have to do several point-in-time recoveries by trial and error until you find the best place to branch off from the old history. Without timelines this process would soon generate an unmanageable mess. With timelines, you can recover to <emphasis>any</emphasis> prior state, including states in timeline branches that you abandoned earlier. 実際、多くの異なるタイムラインをアーカイブすることができます。 不要な機能と考えるかもしれませんが、命綱になることがしばしばあります。 どの時点まで復旧すればよいか確実でないといった状況を考えてみてください。 その時は、過去の履歴からの分岐点として最善の時点を見つけるために、試行錯誤して何度もポイントインタイムの復旧を行う必要があるでしょう。 タイムラインがないと、この手続きはすぐに管理不能な混乱を招いてしまいます。 タイムラインを使用して、以前捨てたタイムライン分岐における状態を含む、過去の任意の状態に復旧させることができます。

Every time a new timeline is created, <productname>PostgreSQL</productname> creates a <quote>timeline history</quote> file that shows which timeline it branched off from and when. These history files are necessary to allow the system to pick the right WAL segment files when recovering from an archive that contains multiple timelines. Therefore, they are archived into the WAL archive area just like WAL segment files. The history files are just small text files, so it's cheap and appropriate to keep them around indefinitely (unlike the segment files which are large). You can, if you like, add comments to a history file to record your own notes about how and why this particular timeline was created. Such comments will be especially valuable when you have a thicket of different timelines as a result of experimentation. 新しいタイムラインが生成される度に、PostgreSQLは、どのタイムラインがいつどこから分岐したかを示すタイムライン履歴ファイルを作成します。 この履歴ファイルは、複数のタイムラインを含むアーカイブ場所から復旧する時にシステムが正しいWALセグメントファイルを選択できるようにするために必要です。 したがって、履歴ファイルは、WALセグメントファイル同様にWALアーカイブ領域にアーカイブされます。 履歴ファイルは(巨大になるセグメントファイルとは異なり)単なる小さなテキストファイルですので、安価かつ適切に無期限で保管できます。 必要ならば、履歴ファイルにコメントを追加し、この特定のタイムラインがどのように、なぜ生成されたかについて独自の注釈を付与することができます。 特にこうしたコメントは、実験の結果いくつものタイムラインのもつれがある場合に有用です。

The default behavior of recovery is to recover to the latest timeline found in the archive. If you wish to recover to the timeline that was current when the base backup was taken or into a specific child timeline (that is, you want to return to some state that was itself generated after a recovery attempt), you need to specify <literal>current</literal> or the target timeline ID in <xref linkend="guc-recovery-target-timeline"/>. You cannot recover into timelines that branched off earlier than the base backup. 復旧処理のデフォルトは、アーカイブで見つかった最新のタイムラインへの復旧です。 ベースバックアップが取得された時点のタイムラインと同一のタイムラインや別の子タイムラインに沿って復旧させたい(つまり、復旧試行以降に生成されたある状態に戻りたい)場合は、currentrecovery_target_timelineで対象のタイムラインIDを指定しなければなりません。 ベースバックアップより前に分岐したタイムラインに沿って復旧することはできません。

26.3.6. ヒントと例 #

<title>Tips and Examples</title>

Some tips for configuring continuous archiving are given here. 継続的アーカイブを構成するいくつかのヒントを以下にあげます。

26.3.6.1. スタンドアローンホットバックアップ #

<title>Standalone Hot Backups</title>

It is possible to use <productname>PostgreSQL</productname>'s backup facilities to produce standalone hot backups. These are backups that cannot be used for point-in-time recovery, yet are typically much faster to backup and restore than <application>pg_dump</application> dumps. (They are also much larger than <application>pg_dump</application> dumps, so in some cases the speed advantage might be negated.) スタンドアローンホットバックアップを形成するためPostgreSQLのバックアップ基盤を使用することができます。 これらのバックアップはポイントインタイムリカバリに使用することはできないのですが、pg_dumpによるダンプよりバックアップとリストアが概してより速く行われます。 (同時にpg_dumpのダンプより大きくなるので、場合によっては速度による利点が打ち消されるかもしれません。)

As with base backups, the easiest way to produce a standalone hot backup is to use the <xref linkend="app-pgbasebackup"/> tool. If you include the <literal>-X</literal> parameter when calling it, all the write-ahead log required to use the backup will be included in the backup automatically, and no special action is required to restore the backup. ベースバックアップと同様に、スタンドアローンホットバックアップを作成する最も簡単な方法は pg_basebackupツールを使用する方法です。 実行時に-Xオプションをつけることでバックアップに必要な全ての先行書き込みログを自動的にバックアップに含めることができ、リストアするときには特に特別な作業を行う必要がありません。

26.3.6.2. 圧縮アーカイブログ #

<title>Compressed Archive Logs</title>

If archive storage size is a concern, you can use <application>gzip</application> to compress the archive files: もし、アーカイブのストレージ容量に懸念がある場合、アーカイブファイルを圧縮するためにgzipを使用することもできます。

archive_command = 'gzip < %p > /mnt/server/archivedir/%f.gz'

You will then need to use <application>gunzip</application> during recovery: 復旧時は gunzipを使う必要があります。

restore_command = 'gunzip < /mnt/server/archivedir/%f.gz > %p'

26.3.6.3. archive_commandスクリプト #

<title><varname>archive_command</varname> Scripts</title>

Many people choose to use scripts to define their <varname>archive_command</varname>, so that their <filename>postgresql.conf</filename> entry looks very simple: postgresql.confの記入事項が以下のように簡素となるため、多くの人がarchive_commandの定義にスクリプトの使用を選択します。

archive_command = 'local_backup_script.sh "%p" "%f"'

Using a separate script file is advisable any time you want to use more than a single command in the archiving process. This allows all complexity to be managed within the script, which can be written in a popular scripting language such as <application>bash</application> or <application>perl</application>. アーカイブ処理手順において単一ではなくそれ以上の数のコマンドを使用したい場合はいつでも、別のスクリプトファイルの使用が推奨されます。 そうするとスクリプト内で全ての複雑性が管理されます。 スクリプトはbashまたはperlのようなよくあるスクリプト言語で記載できます。

Examples of requirements that might be solved within a script include: スクリプト内で解決される要件の例として以下があります。

  • Copying data to secure off-site data storage セキュアなオフサイトデータストレージへのデータのコピー

  • Batching WAL files so that they are transferred every three hours, rather than one at a time 一回に全てではなく3時間毎に転送されるようにWALファイルのバッチ

  • Interfacing with other backup and recovery software その他のバックアップとリカバリのソフトウェアとのインタフェース

  • Interfacing with monitoring software to report errors エラー報告を行う監視ソフトとのインタフェース

ヒント

When using an <varname>archive_command</varname> script, it's desirable to enable <xref linkend="guc-logging-collector"/>. Any messages written to <systemitem>stderr</systemitem> from the script will then appear in the database server log, allowing complex configurations to be diagnosed easily if they fail. archive_commandスクリプトを使うときはlogging_collectorを使えるようにすることが望ましい方法です。 そのスクリプトがstderrに書き出したメッセージはすべて、データベースのサーバーログとして書かれます。 このため複雑な設定でエラーが発生した時に、簡単に原因を突き止められます。

26.3.7. 警告 #

<title>Caveats</title>

At this writing, there are several limitations of the continuous archiving technique. These will probably be fixed in future releases: 本ドキュメント作成時点では、継続的アーカイブ技術にいくつかの制限があります。 将来のリリースでは修正されるはずです。

  • If a <link linkend="sql-createdatabase"><command>CREATE DATABASE</command></link> command is executed while a base backup is being taken, and then the template database that the <command>CREATE DATABASE</command> copied is modified while the base backup is still in progress, it is possible that recovery will cause those modifications to be propagated into the created database as well. This is of course undesirable. To avoid this risk, it is best not to modify any template databases while taking a base backup. もしもベースバックアップが行われている時、CREATE DATABASEコマンドが実行され、ベースバックアップが処理を実行している期間にCREATE DATABASEがコピーしているtemplateデータベースが変更されると、復旧処理はこれらの変更を作成されたデータベースにも同時に伝播させることは確実です。 もちろん、これは望まれる事ではありません。 この危険を回避するには、ベースバックアップ期間中にはすべてのtemplateデータベースを変更しないことが一番です。

  • <link linkend="sql-createtablespace"><command>CREATE TABLESPACE</command></link> commands are WAL-logged with the literal absolute path, and will therefore be replayed as tablespace creations with the same absolute path. This might be undesirable if the WAL is being replayed on a different machine. It can be dangerous even if the WAL is being replayed on the same machine, but into a new data directory: the replay will still overwrite the contents of the original tablespace. To avoid potential gotchas of this sort, the best practice is to take a new base backup after creating or dropping tablespaces. CREATE TABLESPACEコマンドはリテラルの絶対パス付でWALにログが記録され、したがって、同じ絶対パスでのテーブル空間作成の時に再生されます。 これは、もしWALが異なったマシン上で再生される場合には好ましくありません。 WAL再生がたとえ同一のマシンであっても、新規のデータディレクトリであれば危険です。 なぜなら、再生は元のテーブル空間の内容を上書きし続けるからです。 この種の潜在的な振舞いを防ぐためには、テーブル空間を作成もしくは削除後に新規ベースバックアップを行うのが最良の手段です。

It should also be noted that the default <acronym>WAL</acronym> format is fairly bulky since it includes many disk page snapshots. These page snapshots are designed to support crash recovery, since we might need to fix partially-written disk pages. Depending on your system hardware and software, the risk of partial writes might be small enough to ignore, in which case you can significantly reduce the total volume of archived WAL files by turning off page snapshots using the <xref linkend="guc-full-page-writes"/> parameter. (Read the notes and warnings in <xref linkend="wal"/> before you do so.) Turning off page snapshots does not prevent use of the WAL for PITR operations. An area for future development is to compress archived WAL data by removing unnecessary page copies even when <varname>full_page_writes</varname> is on. In the meantime, administrators might wish to reduce the number of page snapshots included in WAL by increasing the checkpoint interval parameters as much as feasible. また、デフォルトのWALフォーマットは数多くのディスクページのスナップショットを含んでいるため、かなりかさばるものになってしまっていることに触れておくべきでしょう。 これらのページスナップショットは、クラッシュから回復のために設計されています。 それというのも、回復処理の際には不完全に書き込まれているディスクページを修復しなければならないことがあるからです。 システムのハードウェアやソフトウェアによっては、不完全なディスクページの書き込みが起きてしまう危険性は無視してもよい程微小です。 この場合full_page_writesパラメータを設定してページスナップショットを無効にすることで、アーカイブされたWALの総容量を大幅に縮小できます (実際に設定を行う前に、第30章の注意事項と警告を読んでください)。 ページスナップショットを無効にしても PITR処理の際にWALが使用できなくなることはありません。 将来の課題は、full_page_writesがたとえオンになっている場合であっても不要なページを取り除き、アーカイブ済みWALデータの圧縮を行うことでしょう。 差し当たり管理者は、可能な限りチェックポイント間隔パラメータを大きくすることによって、WALに含まれるページスナップショットの数を削減することができます。