]> granicus.if.org Git - postgresql/blob - doc/src/sgml/backup.sgml
spell checker run
[postgresql] / doc / src / sgml / backup.sgml
1 <!-- $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.108 2007/11/28 15:42:30 petere Exp $ -->
2
3 <chapter id="backup">
4  <title>Backup and Restore</title>
5
6  <indexterm zone="backup"><primary>backup</></>
7
8  <para>
9   As with everything that contains valuable data, <productname>PostgreSQL</>
10   databases should be backed up regularly. While the procedure is
11   essentially simple, it is important to have a basic understanding of
12   the underlying techniques and assumptions.
13  </para>
14
15  <para>
16   There are three fundamentally different approaches to backing up
17   <productname>PostgreSQL</> data:
18   <itemizedlist>
19    <listitem><para><acronym>SQL</> dump</para></listitem>
20    <listitem><para>File system level backup</para></listitem>
21    <listitem><para>Continuous archiving</para></listitem>
22   </itemizedlist>
23   Each has its own strengths and weaknesses.
24  </para>
25
26  <sect1 id="backup-dump">
27   <title><acronym>SQL</> Dump</title>
28
29   <para>
30    The idea behind this dump method is to generate a text file with SQL
31    commands that, when fed back to the server, will recreate the
32    database in the same state as it was at the time of the dump.
33    <productname>PostgreSQL</> provides the utility program
34    <xref linkend="app-pgdump"> for this purpose. The basic usage of this
35    command is:
36 <synopsis>
37 pg_dump <replaceable class="parameter">dbname</replaceable> &gt; <replaceable class="parameter">outfile</replaceable>
38 </synopsis>
39    As you see, <application>pg_dump</> writes its results to the
40    standard output. We will see below how this can be useful.
41   </para>
42
43   <para>
44    <application>pg_dump</> is a regular <productname>PostgreSQL</>
45    client application (albeit a particularly clever one). This means
46    that you can do this backup procedure from any remote host that has
47    access to the database. But remember that <application>pg_dump</>
48    does not operate with special permissions. In particular, it must
49    have read access to all tables that you want to back up, so in
50    practice you almost always have to run it as a database superuser.
51   </para>
52
53   <para>
54    To specify which database server <application>pg_dump</> should
55    contact, use the command line options <option>-h
56    <replaceable>host</></> and <option>-p <replaceable>port</></>. The
57    default host is the local host or whatever your
58    <envar>PGHOST</envar> environment variable specifies. Similarly,
59    the default port is indicated by the <envar>PGPORT</envar>
60    environment variable or, failing that, by the compiled-in default.
61    (Conveniently, the server will normally have the same compiled-in
62    default.)
63   </para>
64
65   <para>
66    As any other <productname>PostgreSQL</> client application,
67    <application>pg_dump</> will by default connect with the database
68    user name that is equal to the current operating system user name. To override
69    this, either specify the <option>-U</option> option or set the
70    environment variable <envar>PGUSER</envar>. Remember that
71    <application>pg_dump</> connections are subject to the normal
72    client authentication mechanisms (which are described in <xref
73    linkend="client-authentication">).
74   </para>
75
76   <para>
77    Dumps created by <application>pg_dump</> are internally consistent,
78    that is, updates to the database while <application>pg_dump</> is
79    running will not be in the dump. <application>pg_dump</> does not
80    block other operations on the database while it is working.
81    (Exceptions are those operations that need to operate with an
82    exclusive lock, such as <command>VACUUM FULL</command>.)
83   </para>
84
85   <important>
86    <para>
87     If your database schema relies on OIDs (for instance as foreign
88     keys) you must instruct <application>pg_dump</> to dump the OIDs
89     as well. To do this, use the <option>-o</option> command line
90     option.
91    </para>
92   </important>
93
94   <sect2 id="backup-dump-restore">
95    <title>Restoring the dump</title>
96
97    <para>
98     The text files created by <application>pg_dump</> are intended to
99     be read in by the <application>psql</application> program. The
100     general command form to restore a dump is
101 <synopsis>
102 psql <replaceable class="parameter">dbname</replaceable> &lt; <replaceable class="parameter">infile</replaceable>
103 </synopsis>
104     where <replaceable class="parameter">infile</replaceable> is what
105     you used as <replaceable class="parameter">outfile</replaceable>
106     for the <application>pg_dump</> command. The database <replaceable
107     class="parameter">dbname</replaceable> will not be created by this
108     command, so you must create it yourself from <literal>template0</>
109     before executing <application>psql</> (e.g., with
110     <literal>createdb -T template0 <replaceable
111     class="parameter">dbname</></literal>).  <application>psql</>
112     supports similar options to <application>pg_dump</> for specifying
113     the database server to connect to and the user name to use. See
114     the <xref linkend="app-psql"> reference page for more information.
115    </para>
116
117    <para>
118     Before restoring a SQL dump, all the users who own objects or were
119     granted permissions on objects in the dumped database must already
120     exist. If they do not, then the restore will fail to recreate the
121     objects with the original ownership and/or permissions.
122     (Sometimes this is what you want, but usually it is not.)
123    </para>
124
125    <para>
126     By default, the <application>psql</> script will continue to
127     execute after an SQL error is encountered. You might wish to use the
128     following command at the top of the script to alter that
129     behaviour and have <application>psql</application> exit with an
130     exit status of 3 if an SQL error occurs:
131 <programlisting>
132 \set ON_ERROR_STOP
133 </programlisting>
134     Either way, you will only have a partially restored
135     dump. Alternatively, you can specify that the whole dump should be
136     restored as a single transaction, so the restore is either fully
137     completed or fully rolled back. This mode can be specified by
138     passing the <option>-1</> or <option>--single-transaction</>
139     command-line options to <application>psql</>. When using this
140     mode, be aware that even the smallest of errors can rollback a
141     restore that has already run for many hours. However, that might
142     still be preferable to manually cleaning up a complex database
143     after a partially restored dump.
144    </para>
145
146    <para>
147     The ability of <application>pg_dump</> and <application>psql</> to
148     write to or read from pipes makes it possible to dump a database
149     directly from one server to another; for example:
150 <programlisting>
151 pg_dump -h <replaceable>host1</> <replaceable>dbname</> | psql -h <replaceable>host2</> <replaceable>dbname</>
152 </programlisting>
153    </para>
154
155    <important>
156     <para>
157      The dumps produced by <application>pg_dump</> are relative to
158      <literal>template0</>. This means that any languages, procedures,
159      etc. added to <literal>template1</> will also be dumped by
160      <application>pg_dump</>. As a result, when restoring, if you are
161      using a customized <literal>template1</>, you must create the
162      empty database from <literal>template0</>, as in the example
163      above.
164     </para>
165    </important>
166
167    <para>
168     After restoring a backup, it is wise to run <xref
169     linkend="sql-analyze" endterm="sql-analyze-title"> on each
170     database so the query optimizer has useful statistics. An easy way
171     to do this is to run <command>vacuumdb -a -z</>; this is
172     equivalent to running <command>VACUUM ANALYZE</> on each database
173     manually.  For more advice on how to load large amounts of data
174     into <productname>PostgreSQL</> efficiently, refer to <xref
175     linkend="populate">.
176    </para>
177   </sect2>
178
179   <sect2 id="backup-dump-all">
180    <title>Using <application>pg_dumpall</></title>
181
182    <para>
183     <application>pg_dump</> dumps only a single database at a time,
184     and it does not dump information about roles or tablespaces
185     (because those are cluster-wide rather than per-database).
186     To support convenient dumping of the entire contents of a database
187     cluster, the <xref linkend="app-pg-dumpall"> program is provided.
188     <application>pg_dumpall</> backs up each database in a given
189     cluster, and also preserves cluster-wide data such as role and
190     tablespace definitions. The basic usage of this command is:
191 <synopsis>
192 pg_dumpall &gt; <replaceable>outfile</>
193 </synopsis>
194     The resulting dump can be restored with <application>psql</>:
195 <synopsis>
196 psql -f <replaceable class="parameter">infile</replaceable> postgres
197 </synopsis>
198     (Actually, you can specify any existing database name to start from,
199     but if you are reloading in an empty cluster then <literal>postgres</>
200     should generally be used.)  It is always necessary to have
201     database superuser access when restoring a <application>pg_dumpall</>
202     dump, as that is required to restore the role and tablespace information.
203     If you use tablespaces, be careful that the tablespace paths in the
204     dump are appropriate for the new installation.
205    </para>
206   </sect2>
207
208   <sect2 id="backup-dump-large">
209    <title>Handling large databases</title>
210
211    <para>
212     Since <productname>PostgreSQL</productname> allows tables larger
213     than the maximum file size on your system, it can be problematic
214     to dump such a table to a file, since the resulting file will likely
215     be larger than the maximum size allowed by your system. Since
216     <application>pg_dump</> can write to the standard output, you can
217     use standard Unix tools to work around this possible problem.
218    </para>
219
220    <formalpara>
221     <title>Use compressed dumps.</title>
222     <para>
223      You can use your favorite compression program, for example
224      <application>gzip</application>:
225
226 <programlisting>
227 pg_dump <replaceable class="parameter">dbname</replaceable> | gzip &gt; <replaceable class="parameter">filename</replaceable>.gz
228 </programlisting>
229
230      Reload with:
231
232 <programlisting>
233 createdb <replaceable class="parameter">dbname</replaceable>
234 gunzip -c <replaceable class="parameter">filename</replaceable>.gz | psql <replaceable class="parameter">dbname</replaceable>
235 </programlisting>
236
237      or:
238
239 <programlisting>
240 cat <replaceable class="parameter">filename</replaceable>.gz | gunzip | psql <replaceable class="parameter">dbname</replaceable>
241 </programlisting>
242     </para>
243    </formalpara>
244
245    <formalpara>
246     <title>Use <command>split</>.</title>
247     <para>
248      The <command>split</command> command
249      allows you to split the output into pieces that are
250      acceptable in size to the underlying file system. For example, to
251      make chunks of 1 megabyte:
252
253 <programlisting>
254 pg_dump <replaceable class="parameter">dbname</replaceable> | split -b 1m - <replaceable class="parameter">filename</replaceable>
255 </programlisting>
256
257      Reload with:
258
259 <programlisting>
260 createdb <replaceable class="parameter">dbname</replaceable>
261 cat <replaceable class="parameter">filename</replaceable>* | psql <replaceable class="parameter">dbname</replaceable>
262 </programlisting>
263     </para>
264    </formalpara>
265
266    <formalpara>
267     <title>Use the custom dump format.</title>
268     <para>
269      If <productname>PostgreSQL</productname> was built on a system with the
270      <application>zlib</> compression library installed, the custom dump
271      format will compress data as it writes it to the output file. This will
272      produce dump file sizes similar to using <command>gzip</command>, but it
273      has the added advantage that tables can be restored selectively. The
274      following command dumps a database using the custom dump format:
275
276 <programlisting>
277 pg_dump -Fc <replaceable class="parameter">dbname</replaceable> &gt; <replaceable class="parameter">filename</replaceable>
278 </programlisting>
279
280      A custom-format dump is not a script for <application>psql</>, but
281      instead must be restored with <application>pg_restore</>.
282      See the <xref linkend="app-pgdump"> and <xref
283      linkend="app-pgrestore"> reference pages for details.
284     </para>
285    </formalpara>
286
287   </sect2>
288  </sect1>
289
290  <sect1 id="backup-file">
291   <title>File System Level Backup</title>
292
293   <para>
294    An alternative backup strategy is to directly copy the files that
295    <productname>PostgreSQL</> uses to store the data in the database. In
296    <xref linkend="creating-cluster"> it is explained where these files
297    are located, but you have probably found them already if you are
298    interested in this method. You can use whatever method you prefer
299    for doing usual file system backups, for example:
300
301 <programlisting>
302 tar -cf backup.tar /usr/local/pgsql/data
303 </programlisting>
304   </para>
305
306   <para>
307    There are two restrictions, however, which make this method
308    impractical, or at least inferior to the <application>pg_dump</>
309    method:
310
311    <orderedlist>
312     <listitem>
313      <para>
314       The database server <emphasis>must</> be shut down in order to
315       get a usable backup. Half-way measures such as disallowing all
316       connections will <emphasis>not</emphasis> work
317       (mainly because <command>tar</command> and similar tools do not take an
318       atomic snapshot of the state of the file system at a point in
319       time). Information about stopping the server can be found in
320       <xref linkend="server-shutdown">.  Needless to say that you
321       also need to shut down the server before restoring the data.
322      </para>
323     </listitem>
324
325     <listitem>
326      <para>
327       If you have dug into the details of the file system layout of the
328       database, you might be tempted to try to back up or restore only certain
329       individual tables or databases from their respective files or
330       directories. This will <emphasis>not</> work because the
331       information contained in these files contains only half the
332       truth. The other half is in the commit log files
333       <filename>pg_clog/*</filename>, which contain the commit status of
334       all transactions. A table file is only usable with this
335       information. Of course it is also impossible to restore only a
336       table and the associated <filename>pg_clog</filename> data
337       because that would render all other tables in the database
338       cluster useless.  So file system backups only work for complete
339       restoration of an entire database cluster.
340      </para>
341     </listitem>
342    </orderedlist>
343   </para>
344
345   <para>
346    An alternative file-system backup approach is to make a
347    <quote>consistent snapshot</quote> of the data directory, if the
348    file system supports that functionality (and you are willing to
349    trust that it is implemented correctly).  The typical procedure is
350    to make a <quote>frozen snapshot</> of the volume containing the
351    database, then copy the whole data directory (not just parts, see
352    above) from the snapshot to a backup device, then release the frozen
353    snapshot.  This will work even while the database server is running.
354    However, a backup created in this way saves
355    the database files in a state where the database server was not
356    properly shut down; therefore, when you start the database server
357    on the backed-up data, it will think the server had crashed
358    and replay the WAL log.  This is not a problem, just be aware of
359    it (and be sure to include the WAL files in your backup).
360   </para>
361
362   <para>
363    If your database is spread across multiple file systems, there might not 
364    be any way to obtain exactly-simultaneous frozen snapshots of all 
365    the volumes.  For example, if your data files and WAL log are on different
366    disks, or if tablespaces are on different file systems, it might
367    not be possible to use snapshot backup because the snapshots must be
368    simultaneous.
369    Read your file system documentation very carefully before trusting
370    to the consistent-snapshot technique in such situations.  The safest
371    approach is to shut down the database server for long enough to
372    establish all the frozen snapshots.
373   </para>
374
375   <para>
376    Another option is to use <application>rsync</> to perform a file
377    system backup.  This is done by first running <application>rsync</>
378    while the database server is running, then shutting down the database
379    server just long enough to do a second <application>rsync</>.  The
380    second <application>rsync</> will be much quicker than the first,
381    because it has relatively little data to transfer, and the end result
382    will be consistent because the server was down.  This method
383    allows a file system backup to be performed with minimal downtime.
384   </para>
385
386   <para>
387    Note that a file system backup will not necessarily be
388    smaller than an SQL dump. On the contrary, it will most likely be
389    larger. (<application>pg_dump</application> does not need to dump
390    the contents of indexes for example, just the commands to recreate
391    them.)
392   </para>
393  </sect1>
394
395  <sect1 id="continuous-archiving">
396   <title>Continuous Archiving and Point-In-Time Recovery (PITR)</title>
397
398   <indexterm zone="backup">
399    <primary>continuous archiving</primary>
400   </indexterm>
401
402   <indexterm zone="backup">
403    <primary>point-in-time recovery</primary>
404   </indexterm>
405
406   <indexterm zone="backup">
407    <primary>PITR</primary>
408   </indexterm>
409
410   <para>
411    At all times, <productname>PostgreSQL</> maintains a
412    <firstterm>write ahead log</> (WAL) in the <filename>pg_xlog/</>
413    subdirectory of the cluster's data directory. The log describes
414    every change made to the database's data files.  This log exists
415    primarily for crash-safety purposes: if the system crashes, the
416    database can be restored to consistency by <quote>replaying</> the
417    log entries made since the last checkpoint.  However, the existence
418    of the log makes it possible to use a third strategy for backing up
419    databases: we can combine a file-system-level backup with backup of
420    the WAL files.  If recovery is needed, we restore the backup and
421    then replay from the backed-up WAL files to bring the backup up to
422    current time.  This approach is more complex to administer than
423    either of the previous approaches, but it has some significant
424    benefits:
425   <itemizedlist>
426    <listitem>
427     <para>
428      We do not need a perfectly consistent backup as the starting point.
429      Any internal inconsistency in the backup will be corrected by log
430      replay (this is not significantly different from what happens during
431      crash recovery).  So we don't need file system snapshot capability,
432      just <application>tar</> or a similar archiving tool.
433     </para>
434    </listitem>
435    <listitem>
436     <para>
437      Since we can string together an indefinitely long sequence of WAL files
438      for replay, continuous backup can be achieved simply by continuing to archive
439      the WAL files.  This is particularly valuable for large databases, where
440      it might not be convenient to take a full backup frequently.
441     </para>
442    </listitem>
443    <listitem>
444     <para>
445      There is nothing that says we have to replay the WAL entries all the
446      way to the end.  We could stop the replay at any point and have a
447      consistent snapshot of the database as it was at that time.  Thus,
448      this technique supports <firstterm>point-in-time recovery</>: it is
449      possible to restore the database to its state at any time since your base
450      backup was taken.
451     </para>
452    </listitem>
453    <listitem>
454     <para>
455      If we continuously feed the series of WAL files to another
456      machine that has been loaded with the same base backup file, we
457      have a <firstterm>warm standby</> system: at any point we can bring up
458      the second machine and it will have a nearly-current copy of the
459      database.
460     </para>
461    </listitem>
462   </itemizedlist>
463   </para>
464
465   <para>
466    As with the plain file-system-backup technique, this method can only
467    support restoration of an entire database cluster, not a subset.
468    Also, it requires a lot of archival storage: the base backup might be bulky,
469    and a busy system will generate many megabytes of WAL traffic that
470    have to be archived.  Still, it is the preferred backup technique in
471    many situations where high reliability is needed.
472   </para>
473
474   <para>
475    To recover successfully using continuous archiving (also called "online
476    backup" by many database vendors), you need a continuous
477    sequence of archived WAL files that extends back at least as far as the
478    start time of your backup.  So to get started, you should setup and test
479    your procedure for archiving WAL files <emphasis>before</> you take your
480    first base backup.  Accordingly, we first discuss the mechanics of
481    archiving WAL files.
482   </para>
483
484   <sect2 id="backup-archiving-wal">
485    <title>Setting up WAL archiving</title>
486
487    <para>
488     In an abstract sense, a running <productname>PostgreSQL</> system
489     produces an indefinitely long sequence of WAL records.  The system
490     physically divides this sequence into WAL <firstterm>segment
491     files</>, which are normally 16MB apiece (although the size can be
492     altered when building <productname>PostgreSQL</>).  The segment
493     files are given numeric names that reflect their position in the
494     abstract WAL sequence.  When not using WAL archiving, the system
495     normally creates just a few segment files and then
496     <quote>recycles</> them by renaming no-longer-needed segment files
497     to higher segment numbers.  It's assumed that a segment file whose
498     contents precede the checkpoint-before-last is no longer of
499     interest and can be recycled.
500    </para>
501
502    <para>
503     When archiving WAL data, we want to capture the contents of each segment
504     file once it is filled, and save that data somewhere before the segment
505     file is recycled for reuse.  Depending on the application and the
506     available hardware, there could be many different ways of <quote>saving
507     the data somewhere</>: we could copy the segment files to an NFS-mounted
508     directory on another machine, write them onto a tape drive (ensuring that
509     you have a way of identifying the original name of each file), or batch
510     them together and burn them onto CDs, or something else entirely.  To
511     provide the database administrator with as much flexibility as possible,
512     <productname>PostgreSQL</> tries not to make any assumptions about how 
513     the archiving will be done.  Instead, <productname>PostgreSQL</> lets
514     the administrator specify a shell command to be executed to copy a
515     completed segment file to wherever it needs to go.  The command could be
516     as simple as a <literal>cp</>, or it could invoke a complex shell
517     script &mdash; it's all up to you.
518    </para>
519
520    <para>
521     To enable WAL archiving, set the <xref
522     linkend="guc-archive-mode"> configuration parameter to <literal>on</>,
523     and specify the shell command to use in the <xref
524     linkend="guc-archive-command"> configuration parameter.  In practice
525     these settings will always be placed in the
526     <filename>postgresql.conf</filename> file.
527     In <varname>archive_command</>,
528     any <literal>%p</> is replaced by the path name of the file to
529     archive, while any <literal>%f</> is replaced by the file name only.
530     (The path name is relative to the working directory of the server,
531     i.e., the cluster's data directory.)
532     Write <literal>%%</> if you need to embed an actual <literal>%</>
533     character in the command.  The simplest useful command is something
534     like:
535 <programlisting>
536 archive_command = 'cp -i %p /mnt/server/archivedir/%f &lt;/dev/null'
537 </programlisting>
538     which will copy archivable WAL segments to the directory
539     <filename>/mnt/server/archivedir</>.  (This is an example, not a 
540     recommendation, and might not work on all platforms.)
541    </para>
542
543    <para>
544     The archive command will be executed under the ownership of the same
545     user that the <productname>PostgreSQL</> server is running as.  Since
546     the series of WAL files being archived contains effectively everything
547     in your database, you will want to be sure that the archived data is
548     protected from prying eyes; for example, archive into a directory that
549     does not have group or world read access.
550    </para>
551
552    <para>
553     It is important that the archive command return zero exit status if and
554     only if it succeeded.  Upon getting a zero result,
555     <productname>PostgreSQL</> will assume that the WAL segment file has been
556     successfully archived, and will remove or recycle it.
557     However, a nonzero status tells
558     <productname>PostgreSQL</> that the file was not archived; it will try
559     again periodically until it succeeds.
560    </para>
561
562    <para>
563     The archive command should generally be designed to refuse to overwrite
564     any pre-existing archive file.  This is an important safety feature to
565     preserve the integrity of your archive in case of administrator error
566     (such as sending the output of two different servers to the same archive
567     directory).
568     It is advisable to test your proposed archive command to ensure that it
569     indeed does not overwrite an existing file, <emphasis>and that it returns
570     nonzero status in this case</>.  We have found that <literal>cp -i</> does
571     this correctly on some platforms but not others.  If the chosen command
572     does not itself handle this case correctly, you should add a command
573     to test for pre-existence of the archive file.  For example, something
574     like:
575 <programlisting>
576 archive_command = 'test ! -f .../%f &amp;&amp; cp %p .../%f'
577 </programlisting>
578     works correctly on most Unix variants.
579    </para>
580
581    <para>
582     While designing your archiving setup, consider what will happen if
583     the archive command fails repeatedly because some aspect requires 
584     operator intervention or the archive runs out of space. For example, this
585     could occur if you write to tape without an autochanger; when the tape 
586     fills, nothing further can be archived until the tape is swapped.
587     You should ensure that any error condition or request to a human operator
588     is reported appropriately so that the situation can be 
589     resolved relatively quickly. The <filename>pg_xlog/</> directory will
590     continue to fill with WAL segment files until the situation is resolved.
591    </para>
592
593    <para>
594     The speed of the archiving command is not important, so long as it can keep up
595     with the average rate at which your server generates WAL data.  Normal
596     operation continues even if the archiving process falls a little behind.
597     If archiving falls significantly behind, this will increase the amount of
598     data that would be lost in the event of a disaster. It will also mean that
599     the <filename>pg_xlog/</> directory will contain large numbers of
600     not-yet-archived segment files, which could eventually exceed available
601     disk space. You are advised to monitor the archiving process to ensure that
602     it is working as you intend.
603    </para>
604
605    <para>
606     In writing your archive command, you should assume that the file names to
607     be archived can be up to 64 characters long and can contain any
608     combination of ASCII letters, digits, and dots.  It is not necessary to
609     remember the original relative path (<literal>%p</>) but it is necessary to
610     remember the file name (<literal>%f</>).
611    </para>
612
613    <para>
614     Note that although WAL archiving will allow you to restore any
615     modifications made to the data in your <productname>PostgreSQL</> database,
616     it will not restore changes made to configuration files (that is,
617     <filename>postgresql.conf</>, <filename>pg_hba.conf</> and
618     <filename>pg_ident.conf</>), since those are edited manually rather
619     than through SQL operations.
620     You might wish to keep the configuration files in a location that will
621     be backed up by your regular file system backup procedures.  See
622     <xref linkend="runtime-config-file-locations"> for how to relocate the
623     configuration files.
624    </para>
625
626    <para>
627     The archive command is only invoked on completed WAL segments.  Hence,
628     if your server generates only little WAL traffic (or has slack periods 
629     where it does so), there could be a long delay between the completion
630     of a transaction and its safe recording in archive storage.  To put
631     a limit on how old unarchived data can be, you can set
632     <xref linkend="guc-archive-timeout"> to force the server to switch
633     to a new WAL segment file at least that often.  Note that archived
634     files that are ended early due to a forced switch are still the same
635     length as completely full files.  It is therefore unwise to set a very
636     short <varname>archive_timeout</> &mdash; it will bloat your archive
637     storage.  <varname>archive_timeout</> settings of a minute or so are
638     usually reasonable.
639    </para>
640
641    <para>
642     Also, you can force a segment switch manually with
643     <function>pg_switch_xlog</>, if you want to ensure that a
644     just-finished transaction is archived immediately.  Other utility
645     functions related to WAL management are listed in <xref
646     linkend="functions-admin-backup-table">.
647    </para>
648   </sect2>
649
650   <sect2 id="backup-base-backup">
651    <title>Making a Base Backup</title>
652
653    <para>
654     The procedure for making a base backup is relatively simple:
655   <orderedlist>
656    <listitem>
657     <para>
658      Ensure that WAL archiving is enabled and working.
659     </para>
660    </listitem>
661    <listitem>
662     <para>
663      Connect to the database as a superuser, and issue the command:
664 <programlisting>
665 SELECT pg_start_backup('label');
666 </programlisting>
667      where <literal>label</> is any string you want to use to uniquely
668      identify this backup operation.  (One good practice is to use the
669      full path where you intend to put the backup dump file.)
670      <function>pg_start_backup</> creates a <firstterm>backup label</> file,
671      called <filename>backup_label</>, in the cluster directory with
672      information about your backup.
673     </para>
674
675     <para>
676      It does not matter which database within the cluster you connect to to 
677      issue this command.  You can ignore the result returned by the function;
678      but if it reports an error, deal with that before proceeding.
679     </para>
680
681     <para>
682      <function>pg_start_backup</> can take a long time to finish.
683      This is because it performs a checkpoint, and the I/O
684      required for a checkpoint will be spread out over a significant
685      period of time, by default half your inter-checkpoint interval
686      (see the configuration parameter
687      <xref linkend="guc-checkpoint-completion-target">).  Usually
688      this is what you want because it minimizes the impact on query
689      processing.  If you just want to start the backup as soon as
690      possible, execute a <command>CHECKPOINT</> command
691      (which performs a checkpoint as quickly as possible) and then
692      immediately execute <function>pg_start_backup</>.  Then there
693      will be very little for <function>pg_start_backup</>'s checkpoint
694      to do, and it won't take long.
695     </para>
696    </listitem>
697    <listitem>
698     <para>
699      Perform the backup, using any convenient file-system-backup tool
700      such as <application>tar</> or <application>cpio</>.  It is neither
701      necessary nor desirable to stop normal operation of the database
702      while you do this.
703     </para>
704    </listitem>
705    <listitem>
706     <para>
707      Again connect to the database as a superuser, and issue the command:
708 <programlisting>
709 SELECT pg_stop_backup();
710 </programlisting>
711      This terminates the backup mode and performs an automatic switch to
712      the next WAL segment.  The reason for the switch is to arrange that
713      the last WAL segment file written during the backup interval is
714      immediately ready to archive.
715     </para>
716    </listitem>
717    <listitem>
718     <para>
719      Once the WAL segment files used during the backup are archived, you are
720      done.  The file identified by <function>pg_stop_backup</>'s result is
721      the last segment that needs to be archived to complete the backup.  
722      Archival of these files will happen automatically, since you have
723      already configured <varname>archive_command</>. In many cases, this
724      happens fairly quickly, but you are advised to monitor your archival
725      system to ensure this has taken place so that you can be certain you
726      have a complete backup.  
727     </para>
728    </listitem>
729   </orderedlist>
730    </para>
731
732    <para>
733     Some backup tools that you might wish to use emit warnings or errors
734     if the files they are trying to copy change while the copy proceeds.
735     This situation is normal, and not an error, when taking a base backup
736     of an active database; so you need to ensure that you can distinguish
737     complaints of this sort from real errors.  For example, some versions
738     of <application>rsync</> return a separate exit code for
739     <quote>vanished source files</>, and you can write a driver script to
740     accept this exit code as a non-error case.  Also, some versions of
741     GNU <application>tar</> return an error code indistinguishable from
742     a fatal error if a file was truncated while <application>tar</> was
743     copying it.  Fortunately, GNU <application>tar</> versions 1.16 and
744     later exits with <literal>1</> if a file was changed during the backup,
745     and <literal>2</> for other errors.
746    </para>
747
748    <para>
749     It is not necessary to be very concerned about the amount of time elapsed
750     between <function>pg_start_backup</> and the start of the actual backup,
751     nor between the end of the backup and <function>pg_stop_backup</>; a
752     few minutes' delay won't hurt anything.  (However, if you normally run the
753     server with <varname>full_page_writes</> disabled, you might notice a drop
754     in performance between <function>pg_start_backup</> and 
755     <function>pg_stop_backup</>, since <varname>full_page_writes</> is
756     effectively forced on during backup mode.)  You must ensure that these
757     steps are carried out in sequence without any possible
758     overlap, or you will invalidate the backup.
759    </para>
760
761    <para>
762     Be certain that your backup dump includes all of the files underneath
763     the database cluster directory (e.g., <filename>/usr/local/pgsql/data</>).
764     If you are using tablespaces that do not reside underneath this directory,
765     be careful to include them as well (and be sure that your backup dump
766     archives symbolic links as links, otherwise the restore will mess up
767     your tablespaces).
768    </para>
769
770    <para>
771     You can, however, omit from the backup dump the files within the
772     <filename>pg_xlog/</> subdirectory of the cluster directory.  This
773     slight complication is worthwhile because it reduces the risk
774     of mistakes when restoring.  This is easy to arrange if
775     <filename>pg_xlog/</> is a symbolic link pointing to someplace outside
776     the cluster directory, which is a common setup anyway for performance
777     reasons.
778    </para>
779
780    <para>
781     To make use of the backup, you will need to keep around all the WAL
782     segment files generated during and after the file system backup.
783     To aid you in doing this, the <function>pg_stop_backup</> function
784     creates a <firstterm>backup history file</> that is immediately
785     stored into the WAL archive area. This file is named after the first
786     WAL segment file that you need to have to make use of the backup.
787     For example, if the starting WAL file is
788     <literal>0000000100001234000055CD</> the backup history file will be
789     named something like
790     <literal>0000000100001234000055CD.007C9330.backup</>. (The second
791     number in the file name stands for an exact position within the WAL
792     file, and can ordinarily be ignored.) Once you have safely archived
793     the file system backup and the WAL segment files used during the
794     backup (as specified in the backup history file), all archived WAL
795     segments with names numerically less are no longer needed to recover
796     the file system backup and can be deleted. However, you should
797     consider keeping several backup sets to be absolutely certain that
798     you can recover your data.
799    </para>
800
801    <para>
802     The backup history file is just a small text file. It contains the
803     label string you gave to <function>pg_start_backup</>, as well as
804     the starting and ending times and WAL segments of the backup.
805     If you used the label to identify where the associated dump file is kept, 
806     then the archived history file is enough to tell you which dump file to
807     restore, should you need to do so.
808    </para>
809
810    <para>
811     Since you have to keep around all the archived WAL files back to your
812     last base backup, the interval between base backups should usually be
813     chosen based on how much storage you want to expend on archived WAL
814     files.  You should also consider how long you are prepared to spend
815     recovering, if recovery should be necessary &mdash; the system will have to
816     replay all those WAL segments, and that could take awhile if it has
817     been a long time since the last base backup.
818    </para>
819
820    <para>
821     It's also worth noting that the <function>pg_start_backup</> function
822     makes a file named <filename>backup_label</> in the database cluster
823     directory, which is then removed again by <function>pg_stop_backup</>.
824     This file will of course be archived as a part of your backup dump file.
825     The backup label file includes the label string you gave to
826     <function>pg_start_backup</>, as well as the time at which
827     <function>pg_start_backup</> was run, and the name of the starting WAL
828     file.  In case of confusion it will
829     therefore be possible to look inside a backup dump file and determine
830     exactly which backup session the dump file came from.
831    </para>
832
833    <para>
834     It is also possible to make a backup dump while the server is
835     stopped.  In this case, you obviously cannot use
836     <function>pg_start_backup</> or <function>pg_stop_backup</>, and
837     you will therefore be left to your own devices to keep track of which
838     backup dump is which and how far back the associated WAL files go.
839     It is generally better to follow the continuous archiving procedure above.
840    </para>
841   </sect2>
842
843   <sect2 id="backup-pitr-recovery">
844    <title>Recovering using a Continuous Archive Backup</title>
845
846    <para>
847     Okay, the worst has happened and you need to recover from your backup.
848     Here is the procedure:
849   <orderedlist>
850    <listitem>
851     <para>
852      Stop the server, if it's running.
853     </para>
854    </listitem>
855    <listitem>
856     <para>
857      If you have the space to do so,
858      copy the whole cluster data directory and any tablespaces to a temporary 
859      location in case you need them later. Note that this precaution will
860      require that you have enough free space on your system to hold two
861      copies of your existing database. If you do not have enough space, 
862      you need at the least to copy the contents of the <filename>pg_xlog</>
863      subdirectory of the cluster data directory, as it might contain logs which
864      were not archived before the system went down.
865     </para>
866    </listitem>
867    <listitem>
868     <para>
869      Clean out all existing files and subdirectories under the cluster data
870      directory and under the root directories of any tablespaces you are using.
871     </para>
872    </listitem>
873    <listitem>
874     <para>
875      Restore the database files from your backup dump.  Be careful that they
876      are restored with the right ownership (the database system user, not
877      root!) and with the right permissions.  If you are using tablespaces,
878      you should verify that the symbolic links in <filename>pg_tblspc/</>
879      were correctly restored.
880     </para>
881    </listitem>
882    <listitem>
883     <para>
884      Remove any files present in <filename>pg_xlog/</>; these came from the
885      backup dump and are therefore probably obsolete rather than current.
886      If you didn't archive <filename>pg_xlog/</> at all, then recreate it,
887      and be sure to recreate the subdirectory
888     <filename>pg_xlog/archive_status/</> as well.
889     </para>
890    </listitem>
891    <listitem>
892     <para>
893      If you had unarchived WAL segment files that you saved in step 2,
894      copy them into <filename>pg_xlog/</>.  (It is best to copy them,
895      not move them, so that you still have the unmodified files if a
896      problem occurs and you have to start over.)
897     </para>
898    </listitem>
899    <listitem>
900     <para>
901      Create a recovery command file <filename>recovery.conf</> in the cluster
902      data directory (see <xref linkend="recovery-config-settings">). You might
903      also want to temporarily modify <filename>pg_hba.conf</> to prevent 
904      ordinary users from connecting until you are sure the recovery has worked.
905     </para>
906    </listitem>
907    <listitem>
908     <para>
909      Start the server.  The server will go into recovery mode and
910      proceed to read through the archived WAL files it needs.  Should the
911      recovery be terminated because of an external error, the server can
912      simply be restarted and it will continue recovery.  Upon completion
913      of the recovery process, the server will rename
914      <filename>recovery.conf</> to <filename>recovery.done</> (to prevent
915      accidentally re-entering recovery mode in case of a crash later) and then
916      commence normal database operations.
917     </para>
918    </listitem>
919    <listitem>
920     <para>
921      Inspect the contents of the database to ensure you have recovered to
922      where you want to be.  If not, return to step 1.  If all is well,
923      let in your users by restoring <filename>pg_hba.conf</> to normal.
924     </para>
925    </listitem>
926   </orderedlist>
927    </para>
928
929    <para>
930     The key part of all this is to setup a recovery command file that
931     describes how you want to recover and how far the recovery should
932     run.  You can use <filename>recovery.conf.sample</> (normally
933     installed in the installation <filename>share/</> directory) as a
934     prototype.  The one thing that you absolutely must specify in
935     <filename>recovery.conf</> is the <varname>restore_command</>,
936     which tells <productname>PostgreSQL</> how to get back archived
937     WAL file segments.  Like the <varname>archive_command</>, this is
938     a shell command string.  It can contain <literal>%f</>, which is
939     replaced by the name of the desired log file, and <literal>%p</>,
940     which is replaced by the path name to copy the log file to.
941     (The path name is relative to the working directory of the server,
942     i.e., the cluster's data directory.)
943     Write <literal>%%</> if you need to embed an actual <literal>%</>
944     character in the command.  The simplest useful command is
945     something like:
946 <programlisting>
947 restore_command = 'cp /mnt/server/archivedir/%f %p'
948 </programlisting>
949     which will copy previously archived WAL segments from the directory
950     <filename>/mnt/server/archivedir</>.  You could of course use something
951     much more complicated, perhaps even a shell script that requests the
952     operator to mount an appropriate tape.
953    </para>
954
955    <para>
956     It is important that the command return nonzero exit status on failure.
957     The command <emphasis>will</> be asked for log files that are not present
958     in the archive; it must return nonzero when so asked.  This is not an
959     error condition.  Be aware also that the base name of the <literal>%p</>
960     path will be different from <literal>%f</>; do not expect them to be
961     interchangeable.
962    </para>
963
964    <para>
965     WAL segments that cannot be found in the archive will be sought in
966     <filename>pg_xlog/</>; this allows use of recent un-archived segments.
967     However segments that are available from the archive will be used in
968     preference to files in <filename>pg_xlog/</>.  The system will not
969     overwrite the existing contents of <filename>pg_xlog/</> when retrieving
970     archived files.
971    </para>
972
973    <para>
974     Normally, recovery will proceed through all available WAL segments,
975     thereby restoring the database to the current point in time (or as
976     close as we can get given the available WAL segments).  But if you want
977     to recover to some previous point in time (say, right before the junior
978     DBA dropped your main transaction table), just specify the required
979     stopping point in <filename>recovery.conf</>.  You can specify the stop
980     point, known as the <quote>recovery target</>, either by date/time or
981     by completion of a specific transaction ID.  As of this writing only
982     the date/time option is very usable, since there are no tools to help
983     you identify with any accuracy which transaction ID to use.
984    </para>
985
986    <note>
987      <para>
988       The stop point must be after the ending time of the base backup (the
989       time of <function>pg_stop_backup</>).  You cannot use a base backup
990       to recover to a time when that backup was still going on.  (To
991       recover to such a time, you must go back to your previous base backup
992       and roll forward from there.)
993      </para>
994    </note>
995
996    <para>
997     If recovery finds a corruption in the WAL data then recovery will
998     complete at that point and the server will not start. In such a case the
999     recovery process could be re-run from the beginning, specifying a 
1000     <quote>recovery target</> before the point of corruption so that recovery
1001     can complete normally.
1002     If recovery fails for an external reason, such as a system crash or
1003     if the WAL archive has become inaccessible, then the recovery can simply
1004     be restarted and it will restart almost from where it failed.
1005     Recovery restart works much like checkpointing in normal operation:
1006     the server periodically forces all its state to disk, and then updates
1007     the <filename>pg_control</> file to indicate that the already-processed
1008     WAL data need not be scanned again.
1009    </para>
1010
1011
1012     <sect3 id="recovery-config-settings" xreflabel="Recovery Settings">
1013      <title>Recovery Settings</title>
1014
1015      <para>
1016       These settings can only be made in the <filename>recovery.conf</>
1017       file, and apply only for the duration of the recovery. They must be
1018       reset for any subsequent recovery you wish to perform. They cannot be
1019       changed once recovery has begun.
1020      </para>
1021
1022      <variablelist>
1023
1024      <varlistentry id="restore-command" xreflabel="restore_command">
1025       <term><varname>restore_command</varname> (<type>string</type>)</term>
1026       <listitem>
1027        <para>
1028         The shell command to execute to retrieve an archived segment of
1029         the WAL file series. This parameter is required.
1030         Any <literal>%f</> in the string is
1031         replaced by the name of the file to retrieve from the archive,
1032         and any <literal>%p</> is replaced by the path name to copy
1033         it to on the server.
1034         (The path name is relative to the working directory of the server,
1035         i.e., the cluster's data directory.)
1036         Any <literal>%r</> is replaced by the name of the file containing the
1037         last valid restart point. That is the earliest file that must be kept
1038         to allow a restore to be restartable, so this information can be used
1039         to truncate the archive to just the minimum required to support
1040         restart of the current restore. <literal>%r</> would only be used in a
1041         warm-standby configuration (see <xref
1042         linkend="warm-standby-planning">).
1043         Write <literal>%%</> to embed an actual <literal>%</> character
1044         in the command.
1045        </para>
1046        <para>
1047         It is important for the command to return a zero exit status if and
1048         only if it succeeds.  The command <emphasis>will</> be asked for file
1049         names that are not present in the archive; it must return nonzero
1050         when so asked.  Examples:
1051 <programlisting>
1052 restore_command = 'cp /mnt/server/archivedir/%f "%p"'
1053 restore_command = 'copy /mnt/server/archivedir/%f "%p"'  # Windows
1054 </programlisting>
1055        </para>
1056       </listitem>
1057      </varlistentry>
1058
1059      <varlistentry id="recovery-target-time" xreflabel="recovery_target_time">
1060       <term><varname>recovery_target_time</varname> 
1061            (<type>timestamp</type>)
1062       </term>
1063       <listitem>
1064        <para>
1065         This parameter specifies the time stamp up to which recovery
1066         will proceed.
1067         At most one of <varname>recovery_target_time</> and
1068         <xref linkend="recovery-target-xid"> can be specified.
1069         The default is to recover to the end of the WAL log.
1070         The precise stopping point is also influenced by 
1071         <xref linkend="recovery-target-inclusive">.
1072        </para>
1073       </listitem>
1074      </varlistentry>
1075
1076      <varlistentry id="recovery-target-xid" xreflabel="recovery_target_xid">
1077       <term><varname>recovery_target_xid</varname> (<type>string</type>)</term>
1078       <listitem>
1079        <para>
1080         This parameter specifies the transaction ID up to which recovery
1081         will proceed. Keep in mind 
1082         that while transaction IDs are assigned sequentially at transaction 
1083         start, transactions can complete in a different numeric order.
1084         The transactions that will be recovered are those that committed
1085         before (and optionally including) the specified one.
1086         At most one of <varname>recovery_target_xid</> and
1087         <xref linkend="recovery-target-time"> can be specified.
1088         The default is to recover to the end of the WAL log.
1089         The precise stopping point is also influenced by 
1090         <xref linkend="recovery-target-inclusive">.
1091        </para>
1092       </listitem>
1093      </varlistentry>
1094
1095      <varlistentry id="recovery-target-inclusive" 
1096                    xreflabel="recovery_target_inclusive">
1097       <term><varname>recovery_target_inclusive</varname> 
1098         (<type>boolean</type>)
1099       </term>
1100       <listitem>
1101        <para>
1102         Specifies whether we stop just after the specified recovery target
1103         (<literal>true</literal>), or just before the recovery target 
1104         (<literal>false</literal>).
1105         Applies to both <xref linkend="recovery-target-time">
1106         and <xref linkend="recovery-target-xid">, whichever one is
1107         specified for this recovery.  This indicates whether transactions
1108         having exactly the target commit time or ID, respectively, will
1109         be included in the recovery.  Default is <literal>true</>.
1110        </para>
1111       </listitem>
1112      </varlistentry>
1113
1114      <varlistentry id="recovery-target-timeline" 
1115                    xreflabel="recovery_target_timeline">
1116       <term><varname>recovery_target_timeline</varname> 
1117         (<type>string</type>)
1118       </term>
1119       <listitem>
1120        <para>
1121         Specifies recovering into a particular timeline.  The default is
1122         to recover along the same timeline that was current when the
1123         base backup was taken.  You would only need to set this parameter
1124         in complex re-recovery situations, where you need to return to
1125         a state that itself was reached after a point-in-time recovery.
1126         See <xref linkend="backup-timelines"> for discussion.
1127        </para>
1128       </listitem>
1129      </varlistentry>
1130
1131      <varlistentry id="log-restartpoints" 
1132                    xreflabel="log_restartpoints">
1133       <term><varname>log_restartpoints</varname> 
1134         (<type>boolean</type>)
1135       </term>
1136       <listitem>
1137        <para>
1138         Specifies whether to log each restart point as it occurs. This 
1139         can be helpful to track the progress of a long recovery.
1140         Default is <literal>false</>.
1141        </para>
1142       </listitem>
1143      </varlistentry>
1144
1145    </variablelist>
1146
1147    </sect3>
1148
1149   </sect2>
1150
1151   <sect2 id="backup-timelines">
1152    <title>Timelines</title>
1153
1154   <indexterm zone="backup">
1155    <primary>timelines</primary>
1156   </indexterm>
1157
1158    <para>
1159     The ability to restore the database to a previous point in time creates
1160     some complexities that are akin to science-fiction stories about time
1161     travel and parallel universes.  In the original history of the database,
1162     perhaps you dropped a critical table at 5:15PM on Tuesday evening.
1163     Unfazed, you get out your backup, restore to the point-in-time 5:14PM
1164     Tuesday evening, and are up and running.  In <emphasis>this</> history of
1165     the database universe, you never dropped the table at all.  But suppose
1166     you later realize this wasn't such a great idea after all, and would like
1167     to return to some later point in the original history.  You won't be able
1168     to if, while your database was up-and-running, it overwrote some of the
1169     sequence of WAL segment files that led up to the time you now wish you
1170     could get back to.  So you really want to distinguish the series of
1171     WAL records generated after you've done a point-in-time recovery from
1172     those that were generated in the original database history.
1173    </para>
1174
1175    <para>
1176     To deal with these problems, <productname>PostgreSQL</> has a notion
1177     of <firstterm>timelines</>.  Whenever an archive recovery is completed,
1178     a new timeline is created to identify the series of WAL records
1179     generated after that recovery.  The timeline
1180     ID number is part of WAL segment file names, and so a new timeline does
1181     not overwrite the WAL data generated by previous timelines.  It is
1182     in fact possible to archive many different timelines.  While that might
1183     seem like a useless feature, it's often a lifesaver.  Consider the
1184     situation where you aren't quite sure what point-in-time to recover to,
1185     and so have to do several point-in-time recoveries by trial and error
1186     until you find the best place to branch off from the old history.  Without
1187     timelines this process would soon generate an unmanageable mess.  With
1188     timelines, you can recover to <emphasis>any</> prior state, including
1189     states in timeline branches that you later abandoned.
1190    </para>
1191
1192    <para>
1193     Each time a new timeline is created, <productname>PostgreSQL</> creates
1194     a <quote>timeline history</> file that shows which timeline it branched
1195     off from and when.  These history files are necessary to allow the system
1196     to pick the right WAL segment files when recovering from an archive that
1197     contains multiple timelines.  Therefore, they are archived into the WAL
1198     archive area just like WAL segment files.  The history files are just
1199     small text files, so it's cheap and appropriate to keep them around
1200     indefinitely (unlike the segment files which are large).  You can, if
1201     you like, add comments to a history file to make your own notes about
1202     how and why this particular timeline came to be.  Such comments will be
1203     especially valuable when you have a thicket of different timelines as
1204     a result of experimentation.
1205    </para>
1206
1207    <para>
1208     The default behavior of recovery is to recover along the same timeline
1209     that was current when the base backup was taken.  If you want to recover
1210     into some child timeline (that is, you want to return to some state that
1211     was itself generated after a recovery attempt), you need to specify the
1212     target timeline ID in <filename>recovery.conf</>.  You cannot recover into
1213     timelines that branched off earlier than the base backup.
1214    </para>
1215   </sect2>
1216
1217   <sect2 id="continuous-archiving-caveats">
1218    <title>Caveats</title>
1219
1220    <para>
1221     At this writing, there are several limitations of the continuous archiving
1222     technique.  These will probably be fixed in future releases:
1223
1224   <itemizedlist>
1225    <listitem>
1226     <para>
1227      Operations on hash indexes are not presently WAL-logged, so
1228      replay will not update these indexes.  The recommended workaround
1229      is to manually <xref linkend="sql-reindex" endterm="sql-reindex-title">
1230      each such index after completing a recovery operation.
1231     </para>
1232    </listitem>
1233
1234    <listitem>
1235     <para>
1236      If a <xref linkend="sql-createdatabase" endterm="sql-createdatabase-title">
1237      command is executed while a base backup is being taken, and then
1238      the template database that the <command>CREATE DATABASE</> copied
1239      is modified while the base backup is still in progress, it is
1240      possible that recovery will cause those modifications to be
1241      propagated into the created database as well.  This is of course
1242      undesirable.  To avoid this risk, it is best not to modify any
1243      template databases while taking a base backup.
1244     </para>
1245    </listitem>
1246
1247    <listitem>
1248     <para>
1249      <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1250      commands are WAL-logged with the literal absolute path, and will
1251      therefore be replayed as tablespace creations with the same
1252      absolute path.  This might be undesirable if the log is being
1253      replayed on a different machine.  It can be dangerous even if the
1254      log is being replayed on the same machine, but into a new data
1255      directory: the replay will still overwrite the contents of the
1256      original tablespace.  To avoid potential gotchas of this sort,
1257      the best practice is to take a new base backup after creating or
1258      dropping tablespaces.
1259     </para>
1260    </listitem>
1261   </itemizedlist>
1262    </para>
1263
1264    <para>
1265     It should also be noted that the default <acronym>WAL</acronym>
1266     format is fairly bulky since it includes many disk page snapshots.
1267     These page snapshots are designed to support crash recovery, since
1268     we might need to fix partially-written disk pages.  Depending on
1269     your system hardware and software, the risk of partial writes might
1270     be small enough to ignore, in which case you can significantly
1271     reduce the total volume of archived logs by turning off page
1272     snapshots using the <xref linkend="guc-full-page-writes">
1273     parameter.  (Read the notes and warnings in <xref linkend="wal">
1274     before you do so.)  Turning off page snapshots does not prevent
1275     use of the logs for PITR operations.  An area for future
1276     development is to compress archived WAL data by removing
1277     unnecessary page copies even when <varname>full_page_writes</> is
1278     on.  In the meantime, administrators might wish to reduce the number
1279     of page snapshots included in WAL by increasing the checkpoint
1280     interval parameters as much as feasible.
1281    </para>
1282   </sect2>
1283  </sect1>
1284
1285  <sect1 id="warm-standby">
1286   <title>Warm Standby Servers for High Availability</title>
1287
1288   <indexterm zone="backup">
1289    <primary>warm standby</primary>
1290   </indexterm>
1291
1292   <indexterm zone="backup">
1293    <primary>PITR standby</primary>
1294   </indexterm>
1295
1296   <indexterm zone="backup">
1297    <primary>standby server</primary>
1298   </indexterm>
1299
1300   <indexterm zone="backup">
1301    <primary>log shipping</primary>
1302   </indexterm>
1303
1304   <indexterm zone="backup">
1305    <primary>witness server</primary>
1306   </indexterm>
1307
1308   <indexterm zone="backup">
1309    <primary>STONITH</primary>
1310   </indexterm>
1311
1312   <indexterm zone="backup">
1313    <primary>high availability</primary>
1314   </indexterm>
1315
1316   <para>
1317    Continuous archiving can be used to create a <firstterm>high
1318    availability</> (HA) cluster configuration with one or more
1319    <firstterm>standby servers</> ready to take over operations if the
1320    primary server fails. This capability is widely referred to as
1321    <firstterm>warm standby</> or <firstterm>log shipping</>.
1322   </para>
1323
1324   <para>
1325    The primary and standby server work together to provide this capability,
1326    though the servers are only loosely coupled. The primary server operates
1327    in continuous archiving mode, while each standby server operates in
1328    continuous recovery mode, reading the WAL files from the primary. No
1329    changes to the database tables are required to enable this capability,
1330    so it offers low administration overhead in comparison with some other
1331    replication approaches. This configuration also has relatively low
1332    performance impact on the primary server.
1333   </para>
1334
1335   <para>
1336    Directly moving WAL or "log" records from one database server to another
1337    is typically described as log shipping. <productname>PostgreSQL</>
1338    implements file-based log shipping, which means that WAL records are
1339    transferred one file (WAL segment) at a time. WAL files (16MB) can be
1340    shipped easily and cheaply over any distance, whether it be to an
1341    adjacent system, another system on the same site or another system on
1342    the far side of the globe. The bandwidth required for this technique
1343    varies according to the transaction rate of the primary server.
1344    Record-based log shipping is also possible with custom-developed
1345    procedures, as discussed in <xref linkend="warm-standby-record">.
1346   </para>
1347
1348   <para>
1349    It should be noted that the log shipping is asynchronous, i.e. the WAL
1350    records are shipped after transaction commit. As a result there is a
1351    window for data loss should the primary server suffer a catastrophic
1352    failure: transactions not yet shipped will be lost.  The length of the
1353    window of data loss can be limited by use of the
1354    <varname>archive_timeout</varname> parameter, which can be set as low
1355    as a few seconds if required.  However such low settings will
1356    substantially increase the bandwidth requirements for file shipping.
1357    If you need a window of less than a minute or so, it's probably better
1358    to look into record-based log shipping.
1359   </para>
1360
1361   <para>
1362    The standby server is not available for access, since it is continually
1363    performing recovery processing. Recovery performance is sufficiently
1364    good that the standby will typically be only moments away from full
1365    availability once it has been activated. As a result, we refer to this
1366    capability as a warm standby configuration that offers high
1367    availability. Restoring a server from an archived base backup and
1368    rollforward will take considerably longer, so that technique only
1369    really offers a solution for disaster recovery, not high availability.
1370   </para>
1371
1372   <sect2 id="warm-standby-planning">
1373    <title>Planning</title>
1374
1375    <para>
1376     It is usually wise to create the primary and standby servers
1377     so that they are as similar as possible, at least from the
1378     perspective of the database server.  In particular, the path names
1379     associated with tablespaces will be passed across as-is, so both
1380     primary and standby servers must have the same mount paths for
1381     tablespaces if that feature is used.  Keep in mind that if
1382     <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1383     is executed on the primary, any new mount point needed for it must
1384     be created on both the primary and all standby servers before the command
1385     is executed. Hardware need not be exactly the same, but experience shows
1386     that maintaining two identical systems is easier than maintaining two
1387     dissimilar ones over the lifetime of the application and system.
1388     In any case the hardware architecture must be the same &mdash; shipping
1389     from, say, a 32-bit to a 64-bit system will not work.
1390    </para>
1391
1392    <para>
1393     In general, log shipping between servers running different major release
1394     levels will not be possible. It is the policy of the PostgreSQL Global
1395     Development Group not to make changes to disk formats during minor release
1396     upgrades, so it is likely that running different minor release levels 
1397     on primary and standby servers will work successfully. However, no
1398     formal support for that is offered and you are advised to keep primary
1399     and standby servers at the same release level as much as possible.
1400     When updating to a new minor release, the safest policy is to update
1401     the standby servers first &mdash; a new minor release is more likely
1402     to be able to read WAL files from a previous minor release than vice
1403     versa.
1404    </para>
1405
1406    <para>
1407     There is no special mode required to enable a standby server. The
1408     operations that occur on both primary and standby servers are entirely
1409     normal continuous archiving and recovery tasks. The only point of
1410     contact between the two database servers is the archive of WAL files
1411     that both share: primary writing to the archive, standby reading from
1412     the archive. Care must be taken to ensure that WAL archives for separate
1413     primary servers do not become mixed together or confused. The archive
1414     need not be large, if it is only required for the standby operation.
1415    </para>
1416
1417    <para>
1418     The magic that makes the two loosely coupled servers work together is
1419     simply a <varname>restore_command</> used on the standby that waits
1420     for the next WAL file to become available from the primary. The
1421     <varname>restore_command</> is specified in the
1422     <filename>recovery.conf</> file on the standby server. Normal recovery
1423     processing would request a file from the WAL archive, reporting failure
1424     if the file was unavailable.  For standby processing it is normal for
1425     the next file to be unavailable, so we must be patient and wait for
1426     it to appear. A waiting <varname>restore_command</> can be written as
1427     a custom script that loops after polling for the existence of the next
1428     WAL file. There must also be some way to trigger failover, which should
1429     interrupt the <varname>restore_command</>, break the loop and return
1430     a file-not-found error to the standby server. This ends recovery and
1431     the standby will then come up as a normal server.
1432    </para>
1433
1434    <para>
1435     Pseudocode for a suitable <varname>restore_command</> is:
1436 <programlisting>
1437 triggered = false;
1438 while (!NextWALFileReady() && !triggered)
1439 {
1440     sleep(100000L);         /* wait for ~0.1 sec */
1441     if (CheckForExternalTrigger())
1442         triggered = true;
1443 }
1444 if (!triggered)
1445         CopyWALFileForRecovery();
1446 </programlisting>
1447    </para>
1448
1449    <para>
1450     A working example of a waiting <varname>restore_command</> is provided
1451     as a contrib module, named <application>pg_standby</>. This can be
1452     extended as needed to support specific configurations or environments.
1453    </para>
1454
1455    <para>
1456     <productname>PostgreSQL</productname> does not provide the system
1457     software required to identify a failure on the primary and notify
1458     the standby system and then the standby database server. Many such
1459     tools exist and are well integrated with other aspects required for
1460     successful failover, such as IP address migration.
1461    </para>
1462
1463    <para>
1464     The means for triggering failover is an important part of planning and
1465     design. The <varname>restore_command</> is executed in full once
1466     for each WAL file. The process running the <varname>restore_command</>
1467     is therefore created and dies for each file, so there is no daemon
1468     or server process and so we cannot use signals and a signal
1469     handler. A more permanent notification is required to trigger the
1470     failover. It is possible to use a simple timeout facility,
1471     especially if used in conjunction with a known
1472     <varname>archive_timeout</> setting on the primary. This is
1473     somewhat error prone since a network problem or busy primary server might
1474     be sufficient to initiate failover. A notification mechanism such
1475     as the explicit creation of a trigger file is less error prone, if
1476     this can be arranged.
1477    </para>
1478
1479    <para>
1480     The size of the WAL archive can be minimized by using the <literal>%r</>
1481     option of the <varname>restore_command</>. This option specifies the
1482     last archive file name that needs to be kept to allow the recovery to
1483     restart correctly. This can be used to truncate the archive once
1484     files are no longer required, if the archive is writable from the
1485     standby server.
1486    </para>
1487   </sect2>
1488
1489   <sect2 id="warm-standby-config">
1490    <title>Implementation</title>
1491
1492    <para>
1493     The short procedure for configuring a standby server is as follows. For
1494     full details of each step, refer to previous sections as noted.
1495     <orderedlist>
1496      <listitem>
1497       <para>
1498        Set up primary and standby systems as near identically as
1499        possible, including two identical copies of
1500        <productname>PostgreSQL</> at the same release level.
1501       </para>
1502      </listitem>
1503      <listitem>
1504       <para>
1505        Set up continuous archiving from the primary to a WAL archive located
1506        in a directory on the standby server. Ensure that
1507        <xref linkend="guc-archive-mode">,
1508        <xref linkend="guc-archive-command"> and
1509        <xref linkend="guc-archive-timeout">
1510        are set appropriately on the primary
1511        (see <xref linkend="backup-archiving-wal">).
1512       </para>
1513      </listitem>
1514      <listitem>
1515       <para>
1516        Make a base backup of the primary server (see <xref
1517        linkend="backup-base-backup">), and load this data onto the standby.
1518       </para>
1519      </listitem>
1520      <listitem>
1521       <para>
1522        Begin recovery on the standby server from the local WAL
1523        archive, using a <filename>recovery.conf</> that specifies a
1524        <varname>restore_command</> that waits as described
1525        previously (see <xref linkend="backup-pitr-recovery">).
1526       </para>
1527      </listitem>
1528     </orderedlist>
1529    </para>
1530
1531    <para>
1532     Recovery treats the WAL archive as read-only, so once a WAL file has
1533     been copied to the standby system it can be copied to tape at the same
1534     time as it is being read by the standby database server.
1535     Thus, running a standby server for high availability can be performed at
1536     the same time as files are stored for longer term disaster recovery
1537     purposes. 
1538    </para>
1539
1540    <para>
1541     For testing purposes, it is possible to run both primary and standby
1542     servers on the same system. This does not provide any worthwhile
1543     improvement in server robustness, nor would it be described as HA.
1544    </para>
1545   </sect2>
1546
1547   <sect2 id="warm-standby-failover">
1548    <title>Failover</title>
1549
1550    <para>
1551     If the primary server fails then the standby server should begin
1552     failover procedures.
1553    </para>
1554
1555    <para>
1556     If the standby server fails then no failover need take place. If the
1557     standby server can be restarted, even some time later, then the recovery
1558     process can also be immediately restarted, taking advantage of 
1559     restartable recovery. If the standby server cannot be restarted, then a
1560     full new standby server should be created.
1561    </para>
1562
1563    <para>
1564     If the primary server fails and then immediately restarts, you must have
1565     a mechanism for informing it that it is no longer the primary. This is
1566     sometimes known as STONITH (Shoot the Other Node In The Head), which is
1567     necessary to avoid situations where both systems think they are the
1568     primary, which can lead to confusion and ultimately data loss.
1569    </para>
1570
1571    <para>
1572     Many failover systems use just two systems, the primary and the standby,
1573     connected by some kind of heartbeat mechanism to continually verify the
1574     connectivity between the two and the viability of the primary. It is
1575     also possible to use a third system (called a witness server) to avoid
1576     some problems of inappropriate failover, but the additional complexity
1577     might not be worthwhile unless it is set-up with sufficient care and
1578     rigorous testing.
1579    </para>
1580
1581    <para>
1582     Once failover to the standby occurs, we have only a
1583     single server in operation. This is known as a degenerate state.
1584     The former standby is now the primary, but the former primary is down 
1585     and might stay down.  To return to normal operation we must
1586     fully recreate a standby server, 
1587     either on the former primary system when it comes up, or on a third, 
1588     possibly new, system. Once complete the primary and standby can be 
1589     considered to have switched roles. Some people choose to use a third 
1590     server to provide backup to the new primary until the new standby
1591     server is recreated,
1592     though clearly this complicates the system configuration and 
1593     operational processes.
1594    </para>
1595
1596    <para>
1597     So, switching from primary to standby server can be fast but requires
1598     some time to re-prepare the failover cluster. Regular switching from
1599     primary to standby is encouraged, since it allows regular downtime on
1600     each system for maintenance. This also acts as a test of the
1601     failover mechanism to ensure that it will really work when you need it. 
1602     Written administration procedures are advised.
1603    </para>
1604   </sect2>
1605
1606   <sect2 id="warm-standby-record">
1607    <title>Record-based Log Shipping</title>
1608
1609    <para>
1610     <productname>PostgreSQL</productname> directly supports file-based
1611     log shipping as described above. It is also possible to implement
1612     record-based log shipping, though this requires custom development.
1613    </para>
1614
1615    <para>
1616     An external program can call the <function>pg_xlogfile_name_offset()</>
1617     function (see <xref linkend="functions-admin">)
1618     to find out the file name and the exact byte offset within it of
1619     the current end of WAL.  It can then access the WAL file directly
1620     and copy the data from the last known end of WAL through the current end
1621     over to the standby server(s).  With this approach, the window for data
1622     loss is the polling cycle time of the copying program, which can be very
1623     small, but there is no wasted bandwidth from forcing partially-used
1624     segment files to be archived.  Note that the standby servers' 
1625     <varname>restore_command</> scripts still deal in whole WAL files,
1626     so the incrementally copied data is not ordinarily made available to
1627     the standby servers.  It is of use only when the primary dies &mdash;
1628     then the last partial WAL file is fed to the standby before allowing
1629     it to come up.  So correct implementation of this process requires
1630     cooperation of the <varname>restore_command</> script with the data
1631     copying program.
1632    </para>
1633   </sect2>
1634
1635   <sect2 id="backup-incremental-updated">
1636    <title>Incrementally Updated Backups</title>
1637
1638   <indexterm zone="backup">
1639    <primary>incrementally updated backups</primary>
1640   </indexterm>
1641
1642   <indexterm zone="backup">
1643    <primary>change accumulation</primary>
1644   </indexterm>
1645
1646    <para>
1647     In a warm standby configuration, it is possible to offload the expense of
1648     taking periodic base backups from the primary server; instead base backups
1649     can be made by backing
1650     up a standby server's files.  This concept is generally known as 
1651     incrementally updated backups, log change accumulation or more simply,
1652     change accumulation.
1653    </para>
1654
1655    <para>
1656     If we take a backup of the standby server's files while it is following
1657     logs shipped from the primary, we will be able to reload that data and
1658     restart the standby's recovery process from the last restart point.
1659     We no longer need to keep WAL files from before the restart point.
1660     If we need to recover, it will be faster to recover from the incrementally
1661     updated backup than from the original base backup.
1662    </para>
1663
1664    <para>
1665     Since the standby server is not <quote>live</>, it is not possible to
1666     use <function>pg_start_backup()</> and <function>pg_stop_backup()</>
1667     to manage the backup process; it will be up to you to determine how
1668     far back you need to keep WAL segment files to have a recoverable
1669     backup.  You can do this by running <application>pg_controldata</>
1670     on the standby server to inspect the control file and determine the
1671     current checkpoint WAL location, or by using the 
1672     <varname>log_restartpoints</> option to print values to the server log.
1673    </para>
1674   </sect2>
1675  </sect1>
1676
1677  <sect1 id="migration">
1678   <title>Migration Between Releases</title>
1679
1680   <indexterm zone="migration">
1681    <primary>upgrading</primary>
1682   </indexterm>
1683
1684   <indexterm zone="migration">
1685    <primary>version</primary>
1686    <secondary>compatibility</secondary>
1687   </indexterm>
1688
1689   <para>
1690    This section discusses how to migrate your database data from one
1691    <productname>PostgreSQL</> release to a newer one.
1692    The software installation procedure <foreignphrase>per se</> is not the
1693    subject of this section; those details are in <xref linkend="installation">.
1694   </para>
1695
1696   <para>
1697    As a general rule, the internal data storage format is subject to
1698    change between major releases of <productname>PostgreSQL</> (where
1699    the number after the first dot changes). This does not apply to
1700    different minor releases under the same major release (where the
1701    number after the second dot changes); these always have compatible
1702    storage formats. For example, releases 7.2.1, 7.3.2, and 7.4 are
1703    not compatible, whereas 7.2.1 and 7.2.2 are. When you update
1704    between compatible versions, you can simply replace the executables
1705    and reuse the data directory on disk. Otherwise you need to back
1706    up your data and restore it on the new server.  This has to be done
1707    using <application>pg_dump</>; file system level backup methods
1708    obviously won't work. There are checks in place that prevent you
1709    from using a data directory with an incompatible version of
1710    <productname>PostgreSQL</productname>, so no great harm can be done by
1711    trying to start the wrong server version on a data directory.
1712   </para>
1713
1714   <para>
1715    It is recommended that you use the <application>pg_dump</> and
1716    <application>pg_dumpall</> programs from the newer version of
1717    <productname>PostgreSQL</>, to take advantage of any enhancements
1718    that might have been made in these programs.  Current releases of the
1719    dump programs can read data from any server version back to 7.0.
1720   </para>
1721
1722   <para>
1723    The least downtime can be achieved by installing the new server in
1724    a different directory and running both the old and the new servers
1725    in parallel, on different ports. Then you can use something like:
1726
1727 <programlisting>
1728 pg_dumpall -p 5432 | psql -d postgres -p 6543
1729 </programlisting>
1730
1731    to transfer your data.  Or use an intermediate file if you want.
1732    Then you can shut down the old server and start the new server at
1733    the port the old one was running at. You should make sure that the
1734    old database is not updated after you run <application>pg_dumpall</>,
1735    otherwise you will obviously lose that data. See <xref
1736    linkend="client-authentication"> for information on how to prohibit
1737    access.
1738   </para>
1739
1740   <para>
1741    It is also possible to use replication like <productname>Slony</> to
1742    create a slave server with the updated version of
1743    <productname>PostgreSQL</>.  The slave can be on the same computer or
1744    a different computer.  Once it has synced up with the master server
1745    (running the older version of <productname>PostgreSQL</>), you can
1746    switch masters and make the slave the master and shut down the older
1747    database instance.  Such a switch-over results in only several seconds
1748    of downtime for an upgrade.
1749   </para>
1750
1751   <para>
1752    In practice you probably want to test your client
1753    applications on the new setup before switching over completely.
1754    This is another reason for setting up concurrent installations
1755    of old and new versions.
1756   </para>
1757
1758   <para>
1759    If you cannot or do not want to run two servers in parallel you can
1760    do the backup step before installing the new version, bring down
1761    the server, move the old version out of the way, install the new
1762    version, start the new server, restore the data. For example:
1763
1764 <programlisting>
1765 pg_dumpall &gt; backup
1766 pg_ctl stop
1767 mv /usr/local/pgsql /usr/local/pgsql.old
1768 cd ~/postgresql-&version;
1769 gmake install
1770 initdb -D /usr/local/pgsql/data
1771 postgres -D /usr/local/pgsql/data
1772 psql -f backup postgres
1773 </programlisting>
1774
1775    See <xref linkend="runtime"> about ways to start and stop the
1776    server and other details. The installation instructions will advise
1777    you of strategic places to perform these steps.
1778   </para>
1779
1780   <note>
1781    <para>
1782     When you <quote>move the old installation out of the way</quote>
1783     it might no longer be perfectly usable. Some of the executable programs
1784     contain absolute paths to various installed programs and data files.
1785     This is usually not a big problem but if you plan on using two
1786     installations in parallel for a while you should assign them
1787     different installation directories at build time.  (This problem
1788     is rectified in <productname>PostgreSQL</> 8.0 and later, but you
1789     need to be wary of moving older installations.)
1790    </para>
1791   </note>
1792  </sect1>
1793 </chapter>