X-Git-Url: https://granicus.if.org/sourcecode?a=blobdiff_plain;f=doc%2Fsrc%2Fsgml%2Fbackup.sgml;h=c14ae4306237717cb4c9a46d9653c9bd18bcc7b1;hb=048d148fe63102fafb2336ab5439c950dea7f692;hp=49f20821fa0bbd0e352f662b8548c73c440d30a3;hpb=32cebaecff605a435a1c8c5b8e2ad46ea7a569a0;p=postgresql diff --git a/doc/src/sgml/backup.sgml b/doc/src/sgml/backup.sgml index 49f20821fa..c14ae43062 100644 --- a/doc/src/sgml/backup.sgml +++ b/doc/src/sgml/backup.sgml @@ -1,4 +1,4 @@ - + Backup and Restore @@ -8,7 +8,7 @@ As with everything that contains valuable data, PostgreSQL databases should be backed up regularly. While the procedure is - essentially simple, it is important to have a basic understanding of + essentially simple, it is important to have a clear understanding of the underlying techniques and assumptions. @@ -18,16 +18,17 @@ SQL dump File system level backup - Continuous Archiving + Continuous archiving - Each has its own strengths and weaknesses. + Each has its own strengths and weaknesses; each is discussed in turn + in the following sections. <acronym>SQL</> Dump - The idea behind the SQL-dump method is to generate a text file with SQL + The idea behind this dump method is to generate a text file with SQL commands that, when fed back to the server, will recreate the database in the same state as it was at the time of the dump. PostgreSQL provides the utility program @@ -36,14 +37,14 @@ pg_dump dbname > outfile - As you see, pg_dump writes its results to the + As you see, pg_dump writes its result to the standard output. We will see below how this can be useful. pg_dump is a regular PostgreSQL client application (albeit a particularly clever one). This means - that you can do this backup procedure from any remote host that has + that you can perform this backup procedure from any remote host that has access to the database. But remember that pg_dump does not operate with special permissions. In particular, it must have read access to all tables that you want to back up, so in @@ -63,7 +64,7 @@ pg_dump dbname > - As any other PostgreSQL client application, + Like any other PostgreSQL client application, pg_dump will by default connect with the database user name that is equal to the current operating system user name. To override this, either specify the option or set the @@ -73,20 +74,30 @@ pg_dump dbname > ). + + An important advantage of pg_dump over the other backup + methods described later is that pg_dump's output can + generally be re-loaded into newer versions of PostgreSQL, + whereas file-level backups and continuous archiving are both extremely + server-version-specific. pg_dump is also the only method + that will work when transferring a database to a different machine + architecture, such as going from a 32-bit to a 64-bit server. + + Dumps created by pg_dump are internally consistent, - that is, updates to the database while pg_dump is - running will not be in the dump. pg_dump does not + meaning, the dump represents a snapshot of the database at the time + pg_dump began running. pg_dump does not block other operations on the database while it is working. (Exceptions are those operations that need to operate with an - exclusive lock, such as VACUUM FULL.) + exclusive lock, such as most forms of ALTER TABLE.) - When your database schema relies on OIDs (for instance as foreign + If your database schema relies on OIDs (for instance, as foreign keys) you must instruct pg_dump to dump the OIDs - as well. To do this, use the command line + as well. To do this, use the command-line option. @@ -101,40 +112,52 @@ pg_dump dbname > psql dbname < infile - where infile is what - you used as outfile - for the pg_dump command. The database infile is the + file output by the pg_dump command. The database dbname will not be created by this - command, you must create it yourself from template0 before executing - psql (e.g., with createdb -T template0 - dbname). - psql supports options similar to pg_dump - for controlling the database server location and the user name. See - 's reference page for more information. + command, so you must create it yourself from template0 + before executing psql (e.g., with + createdb -T template0 dbname). psql + supports options similar to pg_dump for specifying + the database server to connect to and the user name to use. See + the reference page for more information. - Not only must the target database already exist before starting to - run the restore, but so must all the users who own objects in the - dumped database or were granted permissions on the objects. If they - do not, then the restore will fail to recreate the objects with the - original ownership and/or permissions. (Sometimes this is what you want, - but usually it is not.) + Before restoring an SQL dump, all the users who own objects or were + granted permissions on objects in the dumped database must already + exist. If they do not, the restore will fail to recreate the + objects with the original ownership and/or permissions. + (Sometimes this is what you want, but usually it is not.) - Once restored, it is wise to run on each database so the optimizer has - useful statistics. An easy way to do this is to run - vacuumdb -a -z to - VACUUM ANALYZE all databases; this is equivalent to - running VACUUM ANALYZE manually. + By default, the psql script will continue to + execute after an SQL error is encountered. You might wish to run + psql with + the ON_ERROR_STOP variable set to alter that + behavior and have psql exit with an + exit status of 3 if an SQL error occurs: + +psql --set ON_ERROR_STOP=on dbname < infile + + Either way, you will only have a partially restored database. + Alternatively, you can specify that the whole dump should be + restored as a single transaction, so the restore is either fully + completed or fully rolled back. This mode can be specified by + passing the The ability of pg_dump and psql to write to or read from pipes makes it possible to dump a database - directly from one server to another; for example: + directly from one server to another, for example: pg_dump -h host1 dbname | psql -h host2 dbname @@ -144,7 +167,7 @@ pg_dump -h host1 dbname | psql -h h The dumps produced by pg_dump are relative to template0. This means that any languages, procedures, - etc. added to template1 will also be dumped by + etc. added via template1 will also be dumped by pg_dump. As a result, when restoring, if you are using a customized template1, you must create the empty database from template0, as in the example @@ -153,8 +176,13 @@ pg_dump -h host1 dbname | psql -h h - For advice on how to load large amounts of data into - PostgreSQL efficiently, refer to on each + database so the query optimizer has useful statistics; + see + and for more information. + For more advice on how to load large amounts of data + into PostgreSQL efficiently, refer to . @@ -163,12 +191,14 @@ pg_dump -h host1 dbname | psql -h h Using <application>pg_dumpall</> - The above mechanism is cumbersome and inappropriate when backing - up an entire database cluster. For this reason the program is provided. + pg_dump dumps only a single database at a time, + and it does not dump information about roles or tablespaces + (because those are cluster-wide rather than per-database). + To support convenient dumping of the entire contents of a database + cluster, the program is provided. pg_dumpall backs up each database in a given - cluster, and also preserves cluster-wide data such as users and - groups. The basic usage of this command is: + cluster, and also preserves cluster-wide data such as role and + tablespace definitions. The basic usage of this command is: pg_dumpall > outfile @@ -177,10 +207,20 @@ pg_dumpall > outfile psql -f infile postgres (Actually, you can specify any existing database name to start from, - but if you are reloading in an empty cluster then postgres - should generally be used.) It is always necessary to have + but if you are loading into an empty cluster then postgres + should usually be used.) It is always necessary to have database superuser access when restoring a pg_dumpall - dump, as that is required to restore the user and group information. + dump, as that is required to restore the role and tablespace information. + If you use tablespaces, make sure that the tablespace paths in the + dump are appropriate for the new installation. + + + + pg_dumpall works by emitting commands to re-create + roles, tablespaces, and empty databases, then invoking + pg_dump for each database. This means that while + each database will be internally consistent, the snapshots of + different databases might not be exactly in-sync. @@ -188,32 +228,30 @@ psql -f infile postgres Handling large databases - Since PostgreSQL allows tables larger - than the maximum file size on your system, it can be problematic - to dump such a table to a file, since the resulting file will likely - be larger than the maximum size allowed by your system. Since - pg_dump can write to the standard output, you can - just use standard Unix tools to work around this possible problem. + Some operating systems have maximum file size limits that cause + problems when creating large pg_dump output files. + Fortunately, pg_dump can write to the standard + output, so you can use standard Unix tools to work around this + potential problem. There are several possible methods: Use compressed dumps. You can use your favorite compression program, for example - gzip. + gzip: pg_dump dbname | gzip > filename.gz - Reload with + Reload with: -createdb dbname gunzip -c filename.gz | psql dbname - or + or: cat filename.gz | gunzip | psql dbname @@ -225,7 +263,7 @@ cat filename.gz | gunzip | psql Use split. The split command - allows you to split the output into pieces that are + allows you to split the output into smaller files that are acceptable in size to the underlying file system. For example, to make chunks of 1 megabyte: @@ -233,17 +271,16 @@ cat filename.gz | gunzip | psql dbname | split -b 1m - filename - Reload with + Reload with: -createdb dbname cat filename* | psql dbname - Use the custom dump format. + Use <application>pg_dump</>'s custom dump format. If PostgreSQL was built on a system with the zlib compression library installed, the custom dump @@ -257,25 +294,34 @@ pg_dump -Fc dbname > A custom-format dump is not a script for psql, but - instead must be restored with pg_restore. + instead must be restored with pg_restore, for example: + + +pg_restore -d dbname filename + + See the and reference pages for details. + + For very large databases, you might need to combine split + with one of the other two approaches. + + - File system level backup + File System Level Backup An alternative backup strategy is to directly copy the files that - PostgreSQL uses to store the data in the database. In - it is explained where these files - are located, but you have probably found them already if you are - interested in this method. You can use whatever method you prefer - for doing usual file system backups, for example + PostgreSQL uses to store the data in the database; + explains where these files + are located. You can use whatever method you prefer + for doing file system backups; for example: tar -cf backup.tar /usr/local/pgsql/data @@ -293,10 +339,11 @@ tar -cf backup.tar /usr/local/pgsql/data The database server must be shut down in order to get a usable backup. Half-way measures such as disallowing all connections will not work - (mainly because tar and similar tools do not take an - atomic snapshot of the state of the file system at a point in - time). Information about stopping the server can be found in - . Needless to say that you + (in part because tar and similar tools do not take + an atomic snapshot of the state of the file system, + but also because of internal buffering within the server). + Information about stopping the server can be found in + . Needless to say, you also need to shut down the server before restoring the data. @@ -304,18 +351,18 @@ tar -cf backup.tar /usr/local/pgsql/data If you have dug into the details of the file system layout of the - database, you may be tempted to try to back up or restore only certain + database, you might be tempted to try to back up or restore only certain individual tables or databases from their respective files or directories. This will not work because the - information contained in these files contains only half the - truth. The other half is in the commit log files + information contained in these files is not usable without + the commit log files, pg_clog/*, which contain the commit status of all transactions. A table file is only usable with this information. Of course it is also impossible to restore only a table and the associated pg_clog data because that would render all other tables in the database cluster useless. So file system backups only work for complete - restoration of an entire database cluster. + backup and restoration of an entire database cluster. @@ -331,24 +378,34 @@ tar -cf backup.tar /usr/local/pgsql/data above) from the snapshot to a backup device, then release the frozen snapshot. This will work even while the database server is running. However, a backup created in this way saves - the database files in a state where the database server was not + the database files in a state as if the database server was not properly shut down; therefore, when you start the database server - on the backed-up data, it will think the server had crashed - and replay the WAL log. This is not a problem, just be aware of - it (and be sure to include the WAL files in your backup). + on the backed-up data, it will think the previous server instance + crashed and will replay the WAL log. This is not a problem; just + be aware of it (and be sure to include the WAL files in your backup). + You can perform a CHECKPOINT before taking the + snapshot to reduce recovery time. - If your database is spread across multiple file systems, there may not - be any way to obtain exactly-simultaneous frozen snapshots of all + If your database is spread across multiple file systems, there might not + be any way to obtain exactly-simultaneous frozen snapshots of all the volumes. For example, if your data files and WAL log are on different disks, or if tablespaces are on different file systems, it might - not be possible to use snapshot backup because the snapshots must be - simultaneous. + not be possible to use snapshot backup because the snapshots + must be simultaneous. Read your file system documentation very carefully before trusting - to the consistent-snapshot technique in such situations. The safest - approach is to shut down the database server for long enough to - establish all the frozen snapshots. + the consistent-snapshot technique in such situations. + + + + If simultaneous snapshots are not possible, one option is to shut down + the database server long enough to establish all the frozen snapshots. + Another option is perform a continuous archiving base backup () because such backups are immune to file + system changes during the backup. This requires enabling continuous + archiving just during the backup process; restore is done using + continuous archive recovery (). @@ -363,11 +420,10 @@ tar -cf backup.tar /usr/local/pgsql/data - Note that a file system backup will not necessarily be - smaller than an SQL dump. On the contrary, it will most likely be - larger. (pg_dump does not need to dump + Note that a file system backup will typically be larger + than an SQL dump. (pg_dump does not need to dump the contents of indexes for example, just the commands to recreate - them.) + them.) However, taking a file system backup might be faster. @@ -389,39 +445,39 @@ tar -cf backup.tar /usr/local/pgsql/data At all times, PostgreSQL maintains a write ahead log (WAL) in the pg_xlog/ - subdirectory of the cluster's data directory. The log describes + 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 replaying 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 backup and - then replay from the backed-up WAL files to bring the backup up to - current time. This approach is more complex to administer than + 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: - We do not need a perfectly consistent backup as the starting point. + We do not need a perfectly consistent file system backup as the starting point. Any internal inconsistency in the backup will be corrected by log replay (this is not significantly different from what happens during - crash recovery). So we don't need file system snapshot capability, + crash recovery). So we do not need a file system snapshot capability, just tar or a similar archiving tool. - Since we can string together an indefinitely long sequence of WAL files + Since we can combine an indefinitely long sequence of WAL files for replay, continuous backup can be achieved simply by continuing to archive the WAL files. This is particularly valuable for large databases, where - it may not be convenient to take a full backup frequently. + it might not be convenient to take a full backup frequently. - There is nothing that says we have to replay the WAL entries all the + It is not necessary to replay the WAL entries all the way to the end. We could stop the replay at any point and have a consistent snapshot of the database as it was at that time. Thus, this technique supports point-in-time recovery: it is @@ -433,7 +489,7 @@ tar -cf backup.tar /usr/local/pgsql/data If we continuously feed the series of WAL files to another machine that has been loaded with the same base backup file, we - have a hot standby system: at any point we can bring up + have a warm standby system: at any point we can bring up the second machine and it will have a nearly-current copy of the database. @@ -441,18 +497,28 @@ tar -cf backup.tar /usr/local/pgsql/data + + + pg_dump and + pg_dumpall do not produce file-system-level + backups and cannot be used as part of a continuous-archiving solution. + Such dumps are logical and do not contain enough + information to be used by WAL replay. + + + 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 may be bulky, + 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. - To recover successfully using continuous archiving (also called "online - backup" by many database vendors), you need a continuous + To recover successfully using continuous archiving (also called + online backup 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 before you take your @@ -467,28 +533,28 @@ tar -cf backup.tar /usr/local/pgsql/data In an abstract sense, a running PostgreSQL system produces an indefinitely long sequence of WAL records. The system physically divides this sequence into WAL segment - files, which are normally 16MB apiece (although the size can be - altered when building PostgreSQL). The segment + files, which are normally 16MB apiece (although the segment size + can be altered when building PostgreSQL). 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 recycles them by renaming no-longer-needed segment files - to higher segment numbers. It's assumed that a segment file whose - contents precede the checkpoint-before-last is no longer of + to higher segment numbers. It's assumed that segment files whose + contents precede the checkpoint-before-last are no longer of interest and can be recycled. - When archiving WAL data, we want to capture the contents of each segment + 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 saving the data somewhere: 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 restoring the file with its original file name), or batch + 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 as much flexibility as possible, - PostgreSQL tries not to make any assumptions about how + provide the database administrator with flexibility, + PostgreSQL tries not to make any assumptions about how the archiving will be done. Instead, PostgreSQL lets the administrator specify a shell command to be executed to copy a completed segment file to wherever it needs to go. The command could be @@ -497,21 +563,34 @@ tar -cf backup.tar /usr/local/pgsql/data - The shell command to use is specified by the configuration parameter, which in practice - will always be placed in the postgresql.conf file. - In this string, - any %p is replaced by the absolute path of the file to - archive, while any %f is replaced by the file name only. - Write %% if you need to embed an actual % + To enable WAL archiving, set the + configuration parameter to archive (or hot_standby), + to on, + and specify the shell command to use in the configuration parameter. In practice + these settings will always be placed in the + postgresql.conf file. + In archive_command, + %p is replaced by the path name of the file to + archive, while %f 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 %% if you need to embed an actual % character in the command. The simplest useful command is something - like + like: -archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null' +archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null' # Unix +archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"' # Windows which will copy archivable WAL segments to the directory - /mnt/server/archivedir. (This is an example, not a - recommendation, and may not work on all platforms.) + /mnt/server/archivedir. (This is an example, not a + recommendation, and might not work on all platforms.) After the + %p and %f parameters have been replaced, + the actual command executed might look like this: + +cp -i pg_xlog/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065 </dev/null + + A similar command will be generated for each new file to be archived. @@ -525,12 +604,11 @@ archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null' It is important that the archive command return zero exit status if and - only if it succeeded. Upon getting a zero result, - PostgreSQL will assume that the WAL segment file has been - successfully archived, and will remove or recycle it. - However, a nonzero status tells - PostgreSQL that the file was not archived; it will try - again periodically until it succeeds. + only if it succeeds. Upon getting a zero result, + PostgreSQL will assume that the file has been + successfully archived, and will remove or recycle it. However, a nonzero + status tells PostgreSQL that the file was not archived; + it will try again periodically until it succeeds. @@ -541,31 +619,36 @@ archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null' directory). It is advisable to test your proposed archive command to ensure that it indeed does not overwrite an existing file, and that it returns - nonzero status in this case. We have found that cp -i does - this correctly on some platforms but not others. If the chosen command - does not itself handle this case correctly, you should add a command - to test for pre-existence of the archive file. For example, something - like + nonzero status in this case. On many Unix platforms, cp + -i causes copy to prompt before overwriting a file, and + < /dev/null causes the prompt (and overwriting) to + fail. If your platform does not support this behavior, you should + add a command to test for the existence of the archive file. For + example, something like: -archive_command = 'test ! -f .../%f && cp %p .../%f' +archive_command = 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f' works correctly on most Unix variants. While designing your archiving setup, consider what will happen if - the archive command fails repeatedly because some aspect requires + the archive command 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 + 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 relatively quickly. The pg_xlog/ directory will + is reported appropriately so that the situation can be + resolved reasonably quickly. The pg_xlog/ directory will continue to fill with WAL segment files until the situation is resolved. + (If the file system containing pg_xlog/ fills up, + PostgreSQL will do a PANIC shutdown. No committed + transactions will be lost, but the database will remain offline until + you free some space.) - The speed of the archiving command is not important, so long as it can keep up + The speed of the archiving command 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 @@ -578,20 +661,20 @@ archive_command = 'test ! -f .../%f && cp %p .../%f' In writing your archive command, you should assume that the file names to - be archived may be up to 64 characters long and may contain any + 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 - remember the original full path (%p) but it is necessary to - remember the file name (%f). + preserve the original relative path (%p) but it is necessary to + preserve the file name (%f). Note that although WAL archiving will allow you to restore any - modifications made to the data in your PostgreSQL database + modifications made to the data in your PostgreSQL database, it will not restore changes made to configuration files (that is, postgresql.conf, pg_hba.conf and pg_ident.conf), since those are edited manually rather than through SQL operations. - You may wish to keep the configuration files in a location that will + You might wish to keep the configuration files in a location that will be backed up by your regular file system backup procedures. See for how to relocate the configuration files. @@ -599,13 +682,13 @@ archive_command = 'test ! -f .../%f && cp %p .../%f' The archive command is only invoked on completed WAL segments. Hence, - if your server generates only little WAL traffic (or has slack periods + 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 to force the server to switch to a new WAL segment file at least that often. Note that archived - files that are ended early due to a forced switch are still the same + 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 archive_timeout — it will bloat your archive storage. archive_timeout settings of a minute or so are @@ -614,10 +697,25 @@ archive_command = 'test ! -f .../%f && cp %p .../%f' Also, you can force a segment switch manually with - pg_switch_xlog(), - if you want to ensure that a just-finished transaction is archived - immediately. Other utility functions related to WAL management are - listed in . + pg_switch_xlog 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 . + + + + When wal_level is minimal some SQL commands + are optimized to avoid WAL logging, as described in . 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, wal_level can only be changed at + server start. However, archive_command can be changed with a + configuration file reload. If you wish to temporarily stop archiving, + one way to do it is to set archive_command to the empty + string (''). + This will cause WAL files to accumulate in pg_xlog/ until a + working archive_command is re-established. @@ -634,7 +732,7 @@ archive_command = 'test ! -f .../%f && cp %p .../%f' - Connect to the database as a superuser, and issue the command + Connect to the database as a superuser and issue the command: SELECT pg_start_backup('label'); @@ -643,82 +741,129 @@ SELECT pg_start_backup('label'); full path where you intend to put the backup dump file.) pg_start_backup creates a backup label file, called backup_label, in the cluster directory with - information about your backup. + information about your backup, including the start time and label + string. - It does not matter which database within the cluster you connect to to + It does not matter which database within the cluster you connect to to issue this command. You can ignore the result returned by the function; but if it reports an error, deal with that before proceeding. + + + By default, pg_start_backup can take a long time to finish. + This is because it performs a checkpoint, and the I/O + required for the checkpoint will be spread out over a significant + period of time, by default half your inter-checkpoint interval + (see the configuration parameter + ). This is + usually what you want, because it minimizes the impact on query + processing. If you want to start the backup as soon as + possible, use: + +SELECT pg_start_backup('label', true); + + This forces the checkpoint to be done as quickly as possible. + Perform the backup, using any convenient file-system-backup tool - such as tar or cpio. It is neither + such as tar or cpio (not + pg_dump or + pg_dumpall). It is neither necessary nor desirable to stop normal operation of the database while you do this. - Again connect to the database as a superuser, and issue the command + Again connect to the database as a superuser, and issue the command: SELECT pg_stop_backup(); - This should return successfully. + This terminates the backup mode and performs an automatic switch to + the next WAL segment. The reason for the switch is to arrange for + the last WAL segment file written during the backup interval to be + ready to archive. - Once the WAL segment files used during the backup are archived as part - of normal database activity, you are done. The file identified by - pg_stop_backup's result is the last segment that needs - to be archived to complete the backup. + Once the WAL segment files active during the backup are archived, you are + done. The file identified by pg_stop_backup's result is + the last segment that is required to form a complete set of backup files. + If archive_mode is enabled, + pg_stop_backup does not return until the last segment has + been archived. + Archiving of these files happens automatically since you have + already configured archive_command. 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, 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 + pg_stop_backup, set an appropriate + statement_timeout value. - Some backup tools that you might wish to use emit warnings or errors + You can also use the tool to take + the backup, instead of manually copying the files. This tool will take + care of the pg_start_backup(), copy and + pg_stop_backup() steps automatically, and transfers the + backup over a regular PostgreSQL connection + using the replication protocol, instead of requiring filesystem level + access. + + + + Some file system backup tools emit warnings or errors if the files they are trying to copy change while the copy proceeds. - This situation is normal, and not an error, when taking a base backup of - an active database; so you need to ensure that you can distinguish + 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 rsync return a separate exit code for vanished - source files, and you can write a driver script to accept this exit - code as a non-error case. Also, - some versions of GNU tar consider it an error if a file - is changed while tar is copying it. There does not seem - to be any very convenient way to distinguish this error from other types - of errors, other than manual inspection of tar's messages. - GNU tar is therefore not the best tool for making base - backups. + of rsync return a separate exit code for + vanished source files, and you can write a driver script to + accept this exit code as a non-error case. Also, some versions of + GNU tar return an error code indistinguishable from + a fatal error if a file was truncated while tar was + copying it. Fortunately, GNU tar versions 1.16 and + later exit with 1 if a file was changed during the backup, + and 2 for other errors. - It is not necessary to be very concerned about the amount of time elapsed + It is not necessary to be concerned about the amount of time elapsed between pg_start_backup and the start of the actual backup, nor between the end of the backup and pg_stop_backup; a - few minutes' delay won't hurt anything. You - must however be quite sure that these operations are carried out in - sequence and do not overlap. + few minutes' delay won't hurt anything. (However, if you normally run the + server with full_page_writes disabled, you might notice a drop + in performance between pg_start_backup and + pg_stop_backup, since full_page_writes is + effectively forced on during backup mode.) You must ensure that these + steps are carried out in sequence, without any possible + overlap, or you will invalidate the backup. - Be certain that your backup dump includes all of the files underneath + Be certain that your backup dump includes all of the files under the database cluster directory (e.g., /usr/local/pgsql/data). 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 dump - archives symbolic links as links, otherwise the restore will mess up + archives symbolic links as links, otherwise the restore will corrupt your tablespaces). - You may, however, omit from the backup dump the files within the - pg_xlog/ subdirectory of the cluster directory. This - slight complication is worthwhile because it reduces the risk + You can, however, omit from the backup dump the files within the + cluster's pg_xlog/ subdirectory. This + slight adjustment is worthwhile because it reduces the risk of mistakes when restoring. This is easy to arrange if pg_xlog/ is a symbolic link pointing to someplace outside the cluster directory, which is a common setup anyway for performance @@ -726,22 +871,22 @@ SELECT pg_stop_backup(); - To make use of this backup, you will need to keep around all the WAL + 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 pg_stop_backup function creates a backup history file that is immediately stored into the WAL archive area. This file is named after the first - WAL segment file that you need to have to make use of the backup. + WAL segment file that you need for the file system backup. For example, if the starting WAL file is 0000000100001234000055CD the backup history file will be named something like 0000000100001234000055CD.007C9330.backup. (The second - number in the file name stands for an exact position within the WAL + 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 may be deleted. However, you should + 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. @@ -750,9 +895,9 @@ SELECT pg_stop_backup(); The backup history file is just a small text file. It contains the label string you gave to pg_start_backup, as well as the starting and ending times and WAL segments of the backup. - If you used the label to identify where the associated dump file is kept, + 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, should you need to do so. + restore. @@ -768,13 +913,13 @@ SELECT pg_stop_backup(); It's also worth noting that the pg_start_backup function makes a file named backup_label in the database cluster - directory, which is then removed again by pg_stop_backup. + directory, which is removed by pg_stop_backup. This file will of course be archived as a part of your backup dump file. The backup label file includes the label string you gave to pg_start_backup, as well as the time at which pg_start_backup was run, and the name of the starting WAL - file. In case of confusion it will - therefore be possible to look inside a backup dump file and determine + file. In case of confusion it is + therefore possible to look inside a backup dump file and determine exactly which backup session the dump file came from. @@ -803,53 +948,55 @@ SELECT pg_stop_backup(); If you have the space to do so, - copy the whole cluster data directory and any tablespaces to a temporary + 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 need at the least to copy the contents of the pg_xlog - subdirectory of the cluster data directory, as it may contain logs which + copies of your existing database. If you do not have enough space, + you should at least save the contents of the cluster's pg_xlog + subdirectory, as it might contain logs which were not archived before the system went down. - Clean out all existing files and subdirectories under the cluster data + Remove all existing files and subdirectories under the cluster data directory and under the root directories of any tablespaces you are using. - Restore the database files from your backup dump. Be careful that they + Restore the database files from your file system backup. Be sure that they are restored with the right ownership (the database system user, not - root!) and with the right permissions. If you are using tablespaces, - you may want to verify that the symbolic links in pg_tblspc/ + root!) and with the right permissions. If you are using + tablespaces, + you should verify that the symbolic links in pg_tblspc/ were correctly restored. Remove any files present in pg_xlog/; these came from the - backup dump and are therefore probably obsolete rather than current. - If you didn't archive pg_xlog/ at all, then re-create it, - and be sure to re-create the subdirectory - pg_xlog/archive_status/ as well. + file system backup and are therefore probably obsolete rather than current. + If you didn't archive pg_xlog/ 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. - If you had unarchived WAL segment files that you saved in step 2, + If you have unarchived WAL segment files that you saved in step 2, copy them into pg_xlog/. (It is best to copy them, - not move them, so that you still have the unmodified files if a + not move them, so you still have the unmodified files if a problem occurs and you have to start over.) Create a recovery command file recovery.conf in the cluster - data directory (see ). You may - also want to temporarily modify pg_hba.conf to prevent - ordinary users from connecting until you are sure the recovery has worked. + data directory (see ). You might + also want to temporarily modify pg_hba.conf to prevent + ordinary users from connecting until you are sure the recovery was successful. @@ -860,57 +1007,61 @@ SELECT pg_stop_backup(); simply be restarted and it will continue recovery. Upon completion of the recovery process, the server will rename recovery.conf to recovery.done (to prevent - accidentally re-entering recovery mode in case of a crash later) and then + accidentally re-entering recovery mode later) and then commence normal database operations. Inspect the contents of the database to ensure you have recovered to - where you want to be. If not, return to step 1. If all is well, - let in your users by restoring pg_hba.conf to normal. + the desired state. If not, return to step 1. If all is well, + allow your users to connect by restoring pg_hba.conf to normal. - The key part of all this is to set up a recovery command file that + The key part of all this is to set up a recovery configuration file that describes how you want to recover and how far the recovery should run. You can use recovery.conf.sample (normally - installed in the installation share/ directory) as a + located in the installation's share/ directory) as a prototype. The one thing that you absolutely must specify in recovery.conf is the restore_command, - which tells PostgreSQL how to get back archived + which tells PostgreSQL how to retrieve archived WAL file segments. Like the archive_command, this is - a shell command string. It may contain %f, which is + a shell command string. It can contain %f, which is replaced by the name of the desired log file, and %p, - which is replaced by the absolute path to copy the log file to. + which is replaced by the path name to copy the log file to. + (The path name is relative to the current working directory, + i.e., the cluster's data directory.) Write %% if you need to embed an actual % character in the command. The simplest useful command is - something like + something like: restore_command = 'cp /mnt/server/archivedir/%f %p' which will copy previously archived WAL segments from the directory - /mnt/server/archivedir. You could of course use something + /mnt/server/archivedir. Of course, you can use something much more complicated, perhaps even a shell script that requests the operator to mount an appropriate tape. It is important that the command return nonzero exit status on failure. - The command will be asked for log files that are not present + The command will be called requesting files that are not present in the archive; it must return nonzero when so asked. This is not an - error condition. Be aware also that the base name of the %p - path will be different from %f; do not expect them to be - interchangeable. + error condition. Not all of the requested files will be WAL segment + files; you should also expect requests for files with a suffix of + .backup or .history. Also be aware that + the base name of the %p path will be different from + %f; do not expect them to be interchangeable. WAL segments that cannot be found in the archive will be sought in pg_xlog/; this allows use of recent un-archived segments. - However segments that are available from the archive will be used in + However, segments that are available from the archive will be used in preference to files in pg_xlog/. The system will not overwrite the existing contents of pg_xlog/ when retrieving archived files. @@ -919,154 +1070,51 @@ restore_command = 'cp /mnt/server/archivedir/%f %p' Normally, recovery will proceed through all available WAL segments, thereby restoring the database to the current point in time (or as - close as we can get given the available WAL segments). But 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 - stopping point in recovery.conf. You can specify the stop - point, known as the recovery target, either by date/time or - by completion of a specific transaction ID. As of this writing only - the date/time option is very usable, since there are no tools to help - you identify with any accuracy which transaction ID to use. + close as possible given the available WAL segments). Therefore, a normal + recovery will end with a file not found message, the exact text + of the error message depending upon your choice of + restore_command. You may also see an error message + at the start of recovery for a file named something like + 00000001.history. This is also normal and does not + indicate a problem in simple recovery situations; see + for discussion. + + + + 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 stopping point in recovery.conf. You can specify + the stop point, known as the recovery target, either by + date/time or by completion of a specific transaction ID. As of this + writing only the date/time option is very usable, since there are no tools + to help you identify with any accuracy which transaction ID to use. - The stop point must be after the ending time of the base backup (the - time of pg_stop_backup). You cannot use a base backup - to recover to a time when that backup was still going on. (To + The stop point must be after the ending time of the base backup, i.e., + the end time of pg_stop_backup. 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.) - If recovery finds a corruption in the WAL data then recovery will - complete at that point and the server will not start. The recovery - process could be re-run from the beginning, specifying a - recovery target so that recovery can complete normally. + 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 + recovery target before the point of corruption so that recovery + can complete normally. If recovery fails for an external reason, such as a system crash or - the WAL archive has become inaccessible, then the recovery can be - simply restarted and it will restart almost from where it failed. - Restartable recovery works by writing a restartpoint record to the control - file at the first safely usable checkpoint record found after - checkpoint_timeout seconds. + 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 pg_control file to indicate that the already-processed + WAL data need not be scanned again. - - - Recovery Settings - - - These settings can only be made in the recovery.conf - file, and apply only for the duration of the recovery. They must be - reset for any subsequent recovery you wish to perform. They cannot be - changed once recovery has begun. - - - - - - restore_command (string) - - - The shell command to execute to retrieve an archived segment of - the WAL file series. This parameter is required. - Any %f in the string is - replaced by the name of the file to retrieve from the archive, - and any %p is replaced by the absolute path to copy - it to on the server. - Write %% to embed an actual % character - in the command. - - - It is important for the command to return a zero exit status if and - only if it succeeds. The command will be asked for file - names that are not present in the archive; it must return nonzero - when so asked. Examples: - -restore_command = 'cp /mnt/server/archivedir/%f "%p"' -restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows - - - - - - - recovery_target_time - (timestamp) - - - - This parameter specifies the time stamp up to which recovery - will proceed. - At most one of recovery_target_time and - can be specified. - The default is to recover to the end of the WAL log. - The precise stopping point is also influenced by - . - - - - - - recovery_target_xid (string) - - - This parameter specifies the transaction ID up to which recovery - will proceed. Keep in mind - that while transaction IDs are assigned sequentially at transaction - start, transactions can complete in a different numeric order. - The transactions that will be recovered are those that committed - before (and optionally including) the specified one. - At most one of recovery_target_xid and - can be specified. - The default is to recover to the end of the WAL log. - The precise stopping point is also influenced by - . - - - - - - recovery_target_inclusive - (boolean) - - - - Specifies whether we stop just after the specified recovery target - (true), or just before the recovery target - (false). - Applies to both - and , whichever one is - specified for this recovery. This indicates whether transactions - having exactly the target commit time or ID, respectively, will - be included in the recovery. Default is true. - - - - - - recovery_target_timeline - (string) - - - - Specifies recovering into a particular timeline. The default is - to recover along the same timeline that was current when the - base backup was taken. You would only need to set this parameter - in complex re-recovery situations, where you need to return to - a state that itself was reached after a point-in-time recovery. - See for discussion. - - - - - - - - @@ -1079,28 +1127,28 @@ restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows 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. In the original history of the database, - perhaps you dropped a critical table at 5:15PM on Tuesday evening. + 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 this history of - the database universe, you never dropped the table at all. But suppose - you later realize this wasn't such a great idea after all, and would like - to return to some later point in the original history. You won't be able + 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 - sequence of WAL segment files that led up to the time you now wish you - could get back to. So you really want to distinguish the series of + 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. - To deal with these problems, PostgreSQL has a notion - of timelines. Each time you recover to a point-in-time - earlier than the end of the WAL sequence, a new timeline is created - to identify the series of WAL records generated after that recovery. - (If recovery proceeds all the way to the end of WAL, however, we do not - start a new timeline: we just extend the existing one.) The timeline - ID number is part of WAL segment file names, and so a new timeline does + To deal with this problem, PostgreSQL has a notion + of timelines. 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. 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 @@ -1109,11 +1157,11 @@ restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows 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 any prior state, including - states in timeline branches that you later abandoned. + states in timeline branches that you abandoned earlier. - Each time a new timeline is created, PostgreSQL creates + Every time a new timeline is created, PostgreSQL creates a timeline history 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 @@ -1121,15 +1169,15 @@ restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows 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 make your own notes about - how and why this particular timeline came to be. Such comments will be + 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. The default behavior of recovery is to recover along the same timeline - that was current when the base backup was taken. If you want to recover + that was current when the base backup was taken. If you wish to recover into some child timeline (that is, you want to return to some state that was itself generated after a recovery attempt), you need to specify the target timeline ID in recovery.conf. You cannot recover into @@ -1137,6 +1185,125 @@ restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows + + Tips and Examples + + + Some tips for configuring continuous archiving are given here. + + + + Standalone hot backups + + + It is possible to use PostgreSQL'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 pg_dump dumps. (They are also much larger + than pg_dump dumps, so in some cases the speed advantage + might be negated.) + + + + To prepare for standalone hot backups, set wal_level to + archive (or hot_standby), archive_mode to + on, and set up an archive_command that performs + archiving only when a switch file exists. For example: + +archive_command = 'test ! -f /var/lib/pgsql/backup_in_progress || cp -i %p /var/lib/pgsql/archive/%f < /dev/null' + + This command will perform archiving when + /var/lib/pgsql/backup_in_progress exists, and otherwise + silently return zero exit status (allowing PostgreSQL + to recycle the unwanted WAL file). + + + + With this preparation, a backup can be taken using a script like the + following: + +touch /var/lib/pgsql/backup_in_progress +psql -c "select pg_start_backup('hot_backup');" +tar -cf /var/lib/pgsql/backup.tar /var/lib/pgsql/data/ +psql -c "select pg_stop_backup();" +rm /var/lib/pgsql/backup_in_progress +tar -rf /var/lib/pgsql/backup.tar /var/lib/pgsql/archive/ + + The switch file /var/lib/pgsql/backup_in_progress is + created first, enabling archiving of completed WAL files to occur. + After the backup the switch file is removed. Archived WAL files are + then added to the backup so that both base backup and all required + WAL files are part of the same tar file. + Please remember to add error handling to your backup scripts. + + + + If archive storage size is a concern, use pg_compresslog, + , to + remove unnecessary and trailing + space from the WAL files. You can then use + gzip to further compress the output of + pg_compresslog: + +archive_command = 'pg_compresslog %p - | gzip > /var/lib/pgsql/archive/%f' + + You will then need to use gunzip and + pg_decompresslog during recovery: + +restore_command = 'gunzip < /mnt/server/archivedir/%f | pg_decompresslog - %p' + + + + + + <varname>archive_command</varname> scripts + + + Many people choose to use scripts to define their + archive_command, so that their + postgresql.conf entry looks very simple: + +archive_command = 'local_backup_script.sh' + + 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 + bash or perl. + Any messages written to stderr from the script will appear + in the database server log, allowing complex configurations to be + diagnosed easily if they fail. + + + + 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 + + + + + Interfacing with other backup and recovery software + + + + + Interfacing with monitoring software to report errors + + + + + + + Caveats @@ -1147,35 +1314,42 @@ restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows - Operations on hash indexes are - not presently WAL-logged, so replay will not update these indexes. - The recommended workaround is to manually REINDEX each - such index after completing a recovery operation. + Operations on hash indexes are not presently WAL-logged, so + replay will not update these indexes. This will mean that any new inserts + will be ignored by the index, updated rows will apparently disappear and + deleted rows will still retain pointers. In other words, if you modify a + table with a hash index on it then you will get incorrect query results + on a standby server. When recovery completes it is recommended that you + manually + each such index after completing a recovery operation. - If a CREATE DATABASE command is executed while a base - backup is being taken, and then the template database that the - CREATE DATABASE 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. + If a + command is executed while a base backup is being taken, and then + the template database that the CREATE DATABASE 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 TABLESPACE 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 log is - being replayed on a different machine. It can be dangerous even if - the log 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. + + 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 log is being + replayed on a different machine. It can be dangerous even if the + log 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. @@ -1184,411 +1358,178 @@ restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows It should also be noted that the default WAL format is fairly bulky since it includes many disk page snapshots. - These page snapshots are designed to support crash recovery, - since we may need to fix partially-written disk pages. Depending - on your system hardware and software, the risk of partial writes may - be small enough to ignore, in which case you can significantly reduce - the total volume of archived logs by turning off page snapshots - using the parameter. - (Read the notes and warnings in - before you do so.) - Turning off page snapshots does not prevent use of the logs for PITR - operations. - An area for future development is to compress archived WAL data by - removing unnecessary page copies even when full_page_writes - is on. In the meantime, administrators - may wish to reduce the number of page snapshots included in WAL by - increasing the checkpoint interval parameters as much as feasible. + 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 logs by turning off page + snapshots using the + parameter. (Read the notes and warnings in + before you do so.) Turning off page snapshots does not prevent + use of the logs for PITR operations. An area for future + development is to compress archived WAL data by removing + unnecessary page copies even when full_page_writes 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. - - Warm Standby Servers for High Availability - - - Warm Standby - - - - PITR Standby - - - - Standby Server - - - - Log Shipping - - - - Witness Server - + + Migration Between Releases - - STONITH + + upgrading - - High Availability + + version + compatibility - Continuous Archiving can be used to create a High Availability (HA) - cluster configuration with one or more Standby Servers ready to take - over operations in the case that the Primary Server fails. This - capability is more widely known as Warm Standby Log Shipping. - - - - The Primary and Standby Server work together to provide this capability, - though the servers are only loosely coupled. The Primary Server operates - in Continuous Archiving mode, while the Standby Server operates in a - continuous Recovery mode, reading the WAL files from the Primary. No - changes to the database tables are required to enable this capability, - so it offers a low administration overhead in comparison with other - replication approaches. This configuration also has a very low - performance impact on the Primary server. - - - - Directly moving WAL or "log" records from one database server to another - is typically described as Log Shipping. PostgreSQL implements file-based - Log Shipping, meaning WAL records are batched one file at a time. WAL - files can be shipped easily and cheaply over any distance, whether it be - to an adjacent system, another system on the same site or another system - on the far side of the globe. The bandwidth required for this technique - varies according to the transaction rate of the Primary Server. - Record-based Log Shipping is also possible with custom-developed - procedures, discussed in a later section. Future developments are likely - to include options for synchronous and/or integrated record-based log - shipping. - - - - It should be noted that the log shipping is asynchronous, i.e. the WAL - records are shipped after transaction commit. As a result there can be a - small window of data loss, should the Primary Server suffer a - catastrophic failure. The window of data loss is minimised by the use of - the archive_timeout parameter, which can be set as low as a few seconds - if required. A very low setting can increase the bandwidth requirements - for file shipping. + This section discusses how to migrate your database data from one + PostgreSQL release to a newer one. + The software installation procedure per se is not the + subject of this section; those details are in . - The Standby server is not available for access, since it is continually - performing recovery processing. Recovery performance is sufficiently - good that the Standby will typically be only minutes away from full - availability once it has been activated. As a result, we refer to this - capability as a Warm Standby configuration that offers High - Availability. Restoring a server from an archived base backup and - rollforward can take considerably longer and so that technique only - really offers a solution for Disaster Recovery, not HA. + PostgreSQL major versions are represented by the + first two digit groups of the version number, e.g., 8.4. + PostgreSQL minor versions are represented by the + third group of version digits, e.g., 8.4.2 is the second minor + release of 8.4. Minor releases never change the internal storage + format and are always compatible with earlier and later minor + releases of the same major version number, e.g., 8.4.2 is compatible + with 8.4, 8.4.1 and 8.4.6. To update between compatible versions, + you simply replace the executables while the server is down and + restart the server. The data directory remains unchanged — + minor upgrades are that simple. - Other mechanisms for High Availability replication are available, both - commercially and as open-source software. + For major releases of PostgreSQL, the + internal data storage format is subject to change, thus complicating + upgrades. The traditional method for moving data to a new major version + is to dump and reload the database. Other, less-well-tested possibilities + are available, as discussed below. - In general, log shipping between servers running different release - levels will not be possible. It is the policy of the PostgreSQL Worldwide - Development Group not to make changes to disk formats during minor release - upgrades, so it is likely that running different minor release levels - on Primary and Standby servers will work successfully. However, no - formal support for that is offered and you are advised not to allow this - to occur over long periods. + New major versions also typically introduce some user-visible + incompatibilities, so application programming changes may be required. + Cautious users will want to test their client applications on the new + version before switching over fully; therefore, it's often a good idea to + set up concurrent installations of old and new versions. When + testing a PostgreSQL major upgrade, consider the + following categories of possible changes: - - Planning - - - On the Standby server all tablespaces and paths will refer to similarly - named mount points, so it is important to create the Primary and Standby - servers so that they are as similar as possible, at least from the - perspective of the database server. Furthermore, any CREATE TABLESPACE - commands will be passed across as-is, so any new mount points must be - created on both servers before they are used on the Primary. Hardware - need not be the same, but experience shows that maintaining two - identical systems is easier than maintaining two dissimilar ones over - the whole lifetime of the application and system. - - - - There is no special mode required to enable a Standby server. The - operations that occur on both Primary and Standby servers are entirely - normal continuous archiving and recovery tasks. The primary point of - contact between the two database servers is the archive of WAL files - that both share: Primary writing to the archive, Standby reading from - the archive. Care must be taken to ensure that WAL archives for separate - servers do not become mixed together or confused. - - - - The magic that makes the two loosely coupled servers work together is - simply a restore_command that waits for the next WAL file to be archived - from the Primary. The restore_command is specified in the recovery.conf - file on the Standby Server. Normal recovery processing would request a - file from the WAL archive, causing an error if the file was unavailable. - For Standby processing it is normal for the next file to be unavailable, - so we must be patient and wait for it to appear. A waiting - restore_command can be written as a custom script that loops after - polling for the existence of the next WAL file. There must also be some - way to trigger failover, which should interrupt the restore_command, - break the loop and return a file not found error to the Standby Server. - This then ends recovery and the Standby will then come up as a normal - server. - - - - Sample code for the C version of the restore_command would be be: - -triggered = false; -while (!NextWALFileReady() && !triggered) -{ - sleep(100000L); // wait for ~0.1 sec - if (CheckForExternalTrigger()) - triggered = true; -} -if (!triggered) - CopyWALFileForRecovery(); - - - - - PostgreSQL does not provide the system software required to identify a - failure on the Primary and notify the Standby system and then the - Standby database server. Many such tools exist and are well integrated - with other aspects of a system failover, such as ip address migration. - - - - Triggering failover is an important part of planning and design. The - restore_command is executed in full once for each WAL file. The process - running the restore_command is therefore created and dies for each file, - so there is no daemon or server process and so we cannot use signals and - a signal handler. A more permanent notification is required to trigger - the failover. It is possible to use a simple timeout facility, - especially if used in conjunction with a known archive_timeout setting - on the Primary. This is somewhat error prone since a network or busy - Primary server might be sufficient to initiate failover. A notification - mechanism such as the explicit creation of a trigger file is less error - prone, if this can be arranged. - - - - - Implementation + - - The short procedure for configuring a Standby Server is as follows. For - full details of each step, refer to previous sections as noted. - - - - Set up Primary and Standby systems as near identically as possible, - including two identical copies of PostgreSQL at same release level. - - - - - Set up Continuous Archiving from the Primary to a WAL archive located - in a directory on the Standby Server. Ensure that both and - are set. (See ) - - - - - Make a Base Backup of the Primary Server. (See ) - - - - - Begin recovery on the Standby Server from the local WAL archive, - using a recovery.conf that specifies a restore_command that waits as - described previously. (See ) - - - - - - - Recovery treats the WAL Archive as read-only, so once a WAL file has - been copied to the Standby system it can be copied to tape at the same - time as it is being used by the Standby database server to recover. - Thus, running a Standby Server for High Availability can be performed at - the same time as files are stored for longer term Disaster Recovery - purposes. - - - - For testing purposes, it is possible to run both Primary and Standby - servers on the same system. This does not provide any worthwhile - improvement on server robustness, nor would it be described as HA. - - - - - Failover - - - If the Primary Server fails then the Standby Server should take begin - failover procedures. - - - - If the Standby Server fails then no failover need take place. If the - Standby Server can be restarted, then the recovery process can also be - immediately restarted, taking advantage of Restartable Recovery. - - - - If the Primary Server fails and then immediately restarts, you must have - a mechanism for informing it that it is no longer the Primary. This is - sometimes known as STONITH (Should the Other Node In The Head), which is - necessary to avoid situations where both systems think they are the - Primary, which can lead to confusion and ultimately data loss. - - - - Many failover systems use just two systems, the Primary and the Standby, - connected by some kind of heartbeat mechanism to continually verify the - connectivity between the two and the viability of the Primary. It is - also possible to use a third system, known as a Witness Server to avoid - some problems of inappropriate failover, but the additional complexity - may not be worthwhile unless it is set-up with sufficient care and - rigorous testing. - - - - At the instant that failover takes place to the Standby, we have only a - single server in operation. This is known as a degenerate state. - The former Standby is now the Primary, but the former Primary is down - and may stay down. We must now fully re-create a Standby server, - either on the former Primary system when it comes up, or on a third, - possibly new, system. Once complete the Primary and Standby can be - considered to have switched roles. Some people choose to use a third - server to provide additional protection across the failover interval, - though clearly this complicates the system configuration and - operational processes (and this can also act as a Witness Server). - - - - So, switching from Primary to Standby Server can be fast, but requires - some time to re-prepare the failover cluster. Regular switching from - Primary to Standby is encouraged, since it allows the regular downtime - one each system required to maintain HA. This also acts as a test of the - failover so that it definitely works when you really need it. Written - administration procedures are advised. - - - - - Implementing Record-based Log Shipping + + Administration + + + The capabilities available for administrators to monitor and control + the server often change and improve in each major release. + + + - - The main features for Log Shipping in this release are based around the - file-based Log Shipping described above. It is also possible to - implement record-based Log Shipping using the pg_xlogfile_name_offset() - function, though this requires custom development. - + + SQL + + + Typically this includes new SQL command capabilities and not changes + in behavior, unless specifically mentioned in the release notes. + + + - - An external program can call pg_xlogfile_name_offset() to find out the - filename and the exact byte offset within it of the latest WAL pointer. - If the external program regularly polls the server it can find out how - far forward the pointer has moved. It can then access the WAL file - directly and copy those bytes across to a less up-to-date copy on a - Standby Server. - - - + + Library API + + + Typically libraries like libpq only add new + functionality, again unless mentioned in the release notes. + + + - - Migration Between Releases + + System Catalogs + + + System catalog changes usually only affect database management tools. + + + - - upgrading - + + Server C-language API + + + This involves changes in the backend function API, which is written + in the C programming language. Such changes affect code that + references backend functions deep inside the server. + + + - - version - compatibility - + - - This section discusses how to migrate your database data from one - PostgreSQL release to a newer one. - The software installation procedure per se is not the - subject of this section; those details are in . - + + Migrating data via <application>pg_dump</> - As a general rule, the internal data storage format is subject to - change between major releases of PostgreSQL (where - the number after the first dot changes). This does not apply to - different minor releases under the same major release (where the - number after the second dot changes); these always have compatible - storage formats. For example, releases 7.2.1, 7.3.2, and 7.4 are - not compatible, whereas 7.2.1 and 7.2.2 are. When you update - between compatible versions, you can simply replace the executables - and reuse the data directory on disk. Otherwise you need to back - up your data and restore it on the new server. This has to be done - using pg_dump; file system level backup methods - obviously won't work. There are checks in place that prevent you - from using a data directory with an incompatible version of + To dump data from one major version of PostgreSQL and + reload it in another, you must use pg_dump; file system + level backup methods will not work. (There are checks in place that prevent + you from using a data directory with an incompatible version of PostgreSQL, so no great harm can be done by - trying to start the wrong server version on a data directory. + trying to start the wrong server version on a data directory.) It is recommended that you use the pg_dump and pg_dumpall programs from the newer version of - PostgreSQL, to take advantage of any enhancements - that may have been made in these programs. Current releases of the + PostgreSQL, to take advantage of enhancements + that might have been made in these programs. Current releases of the dump programs can read data from any server version back to 7.0. The least downtime can be achieved by installing the new server in a different directory and running both the old and the new servers - in parallel, on different ports. Then you can use something like + in parallel, on different ports. Then you can use something like: pg_dumpall -p 5432 | psql -d postgres -p 6543 - to transfer your data. Or use an intermediate file if you want. - Then you can shut down the old server and start the new server at - the port the old one was running at. You should make sure that the - old database is not updated after you run pg_dumpall, - otherwise you will obviously lose that data. See for information on how to prohibit + to transfer your data. Or you can use an intermediate file if you wish. + Then you can shut down the old server and start the new server using + the port the old one was running on. You should make sure that the + old database is not updated after you begin to run + pg_dumpall, otherwise you will lose those updates. See + for information on how to prohibit access. - In practice you probably want to test your client - applications on the new setup before switching over completely. - This is another reason for setting up concurrent installations - of old and new versions. - - - - If you cannot or do not want to run two servers in parallel you can + If you cannot or do not want to run two servers in parallel, you can do the backup step before installing the new version, bring down - the server, move the old version out of the way, install the new - version, start the new server, restore the data. For example: + the old server, move the old version out of the way, install the new + version, start the new server, and restore the data. For example: pg_dumpall > backup pg_ctl stop mv /usr/local/pgsql /usr/local/pgsql.old +# Rename any tablespace directories as well cd ~/postgresql-&version; gmake install initdb -D /usr/local/pgsql/data @@ -1604,14 +1545,47 @@ psql -f backup postgres When you move the old installation out of the way - it may no longer be perfectly usable. Some of the executable programs + it might no longer be perfectly usable. Some of the executable programs contain absolute paths to various installed programs and data files. - This is usually not a big problem but if you plan on using two + This is usually not a big problem, but if you plan on using two installations in parallel for a while you should assign them different installation directories at build time. (This problem - is rectified in PostgreSQL 8.0 and later, but you - need to be wary of moving older installations.) + is rectified in PostgreSQL version 8.0 and later, so long + as you move all subdirectories containing installed files together; + for example if /usr/local/postgres/bin/ goes to + /usr/local/postgres.old/bin/, then + /usr/local/postgres/share/ must go to + /usr/local/postgres.old/share/. In pre-8.0 releases + moving an installation like this will not work.) + + + + Other data migration methods + + + The contrib program + pg_upgrade + allows an installation to be migrated in-place from one major + PostgreSQL version to the next. Keep in mind that this + method does not provide any scope for running old and new versions + concurrently. Also, pg_upgrade is much less + battle-tested than pg_dump, so having an + up-to-date backup is strongly recommended in case something goes wrong. + + + + It is also possible to use certain replication methods, such as + Slony, to create a standby server with the updated version of + PostgreSQL. The standby can be on the same computer or + a different computer. Once it has synced up with the master server + (running the older version of PostgreSQL), you can + switch masters and make the standby the master and shut down the older + database instance. Such a switch-over results in only several seconds + of downtime for an upgrade. + + +