]> granicus.if.org Git - postgresql/blob - doc/src/sgml/backup.sgml
Editorial improvements to backup and warm-standby documentation.
[postgresql] / doc / src / sgml / backup.sgml
1 <!-- $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.95 2006/12/01 03:29:15 tgl 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 may 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 may
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 may 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 may 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 may 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 may 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     The shell command to use is specified by the <xref
522     linkend="guc-archive-command"> configuration parameter, which in practice
523     will always be placed in the <filename>postgresql.conf</filename> file.
524     In this string,
525     any <literal>%p</> is replaced by the path name of the file to
526     archive, while any <literal>%f</> is replaced by the file name only.
527     (The path name is relative to the working directory of the server,
528     i.e., the cluster's data directory.)
529     Write <literal>%%</> if you need to embed an actual <literal>%</>
530     character in the command.  The simplest useful command is something
531     like
532 <programlisting>
533 archive_command = 'cp -i %p /mnt/server/archivedir/%f &lt;/dev/null'
534 </programlisting>
535     which will copy archivable WAL segments to the directory
536     <filename>/mnt/server/archivedir</>.  (This is an example, not a 
537     recommendation, and may not work on all platforms.)
538    </para>
539
540    <para>
541     The archive command will be executed under the ownership of the same
542     user that the <productname>PostgreSQL</> server is running as.  Since
543     the series of WAL files being archived contains effectively everything
544     in your database, you will want to be sure that the archived data is
545     protected from prying eyes; for example, archive into a directory that
546     does not have group or world read access.
547    </para>
548
549    <para>
550     It is important that the archive command return zero exit status if and
551     only if it succeeded.  Upon getting a zero result,
552     <productname>PostgreSQL</> will assume that the WAL segment file has been
553     successfully archived, and will remove or recycle it.
554     However, a nonzero status tells
555     <productname>PostgreSQL</> that the file was not archived; it will try
556     again periodically until it succeeds.
557    </para>
558
559    <para>
560     The archive command should generally be designed to refuse to overwrite
561     any pre-existing archive file.  This is an important safety feature to
562     preserve the integrity of your archive in case of administrator error
563     (such as sending the output of two different servers to the same archive
564     directory).
565     It is advisable to test your proposed archive command to ensure that it
566     indeed does not overwrite an existing file, <emphasis>and that it returns
567     nonzero status in this case</>.  We have found that <literal>cp -i</> does
568     this correctly on some platforms but not others.  If the chosen command
569     does not itself handle this case correctly, you should add a command
570     to test for pre-existence of the archive file.  For example, something
571     like
572 <programlisting>
573 archive_command = 'test ! -f .../%f &amp;&amp; cp %p .../%f'
574 </programlisting>
575     works correctly on most Unix variants.
576    </para>
577
578    <para>
579     While designing your archiving setup, consider what will happen if
580     the archive command fails repeatedly because some aspect requires 
581     operator intervention or the archive runs out of space. For example, this
582     could occur if you write to tape without an autochanger; when the tape 
583     fills, nothing further can be archived until the tape is swapped.
584     You should ensure that any error condition or request to a human operator
585     is reported appropriately so that the situation can be 
586     resolved relatively quickly. The <filename>pg_xlog/</> directory will
587     continue to fill with WAL segment files until the situation is resolved.
588    </para>
589
590    <para>
591     The speed of the archiving command is not important, so long as it can keep up
592     with the average rate at which your server generates WAL data.  Normal
593     operation continues even if the archiving process falls a little behind.
594     If archiving falls significantly behind, this will increase the amount of
595     data that would be lost in the event of a disaster. It will also mean that
596     the <filename>pg_xlog/</> directory will contain large numbers of
597     not-yet-archived segment files, which could eventually exceed available
598     disk space. You are advised to monitor the archiving process to ensure that
599     it is working as you intend.
600    </para>
601
602    <para>
603     In writing your archive command, you should assume that the file names to
604     be archived may be up to 64 characters long and may contain any
605     combination of ASCII letters, digits, and dots.  It is not necessary to
606     remember the original relative path (<literal>%p</>) but it is necessary to
607     remember the file name (<literal>%f</>).
608    </para>
609
610    <para>
611     Note that although WAL archiving will allow you to restore any
612     modifications made to the data in your <productname>PostgreSQL</> database,
613     it will not restore changes made to configuration files (that is,
614     <filename>postgresql.conf</>, <filename>pg_hba.conf</> and
615     <filename>pg_ident.conf</>), since those are edited manually rather
616     than through SQL operations.
617     You may wish to keep the configuration files in a location that will
618     be backed up by your regular file system backup procedures.  See
619     <xref linkend="runtime-config-file-locations"> for how to relocate the
620     configuration files.
621    </para>
622
623    <para>
624     The archive command is only invoked on completed WAL segments.  Hence,
625     if your server generates only little WAL traffic (or has slack periods 
626     where it does so), there could be a long delay between the completion
627     of a transaction and its safe recording in archive storage.  To put
628     a limit on how old unarchived data can be, you can set
629     <xref linkend="guc-archive-timeout"> to force the server to switch
630     to a new WAL segment file at least that often.  Note that archived
631     files that are ended early due to a forced switch are still the same
632     length as completely full files.  It is therefore unwise to set a very
633     short <varname>archive_timeout</> &mdash; it will bloat your archive
634     storage.  <varname>archive_timeout</> settings of a minute or so are
635     usually reasonable.
636    </para>
637
638    <para>
639     Also, you can force a segment switch manually with
640     <function>pg_switch_xlog</>, if you want to ensure that a
641     just-finished transaction is archived immediately.  Other utility
642     functions related to WAL management are listed in <xref
643     linkend="functions-admin-backup-table">.
644    </para>
645   </sect2>
646
647   <sect2 id="backup-base-backup">
648    <title>Making a Base Backup</title>
649
650    <para>
651     The procedure for making a base backup is relatively simple:
652   <orderedlist>
653    <listitem>
654     <para>
655      Ensure that WAL archiving is enabled and working.
656     </para>
657    </listitem>
658    <listitem>
659     <para>
660      Connect to the database as a superuser, and issue the command
661 <programlisting>
662 SELECT pg_start_backup('label');
663 </programlisting>
664      where <literal>label</> is any string you want to use to uniquely
665      identify this backup operation.  (One good practice is to use the
666      full path where you intend to put the backup dump file.)
667      <function>pg_start_backup</> creates a <firstterm>backup label</> file,
668      called <filename>backup_label</>, in the cluster directory with
669      information about your backup.
670     </para>
671
672     <para>
673      It does not matter which database within the cluster you connect to to 
674      issue this command.  You can ignore the result returned by the function;
675      but if it reports an error, deal with that before proceeding.
676     </para>
677    </listitem>
678    <listitem>
679     <para>
680      Perform the backup, using any convenient file-system-backup tool
681      such as <application>tar</> or <application>cpio</>.  It is neither
682      necessary nor desirable to stop normal operation of the database
683      while you do this.
684     </para>
685    </listitem>
686    <listitem>
687     <para>
688      Again connect to the database as a superuser, and issue the command
689 <programlisting>
690 SELECT pg_stop_backup();
691 </programlisting>
692      This terminates the backup mode and performs an automatic switch to
693      the next WAL segment.  The reason for the switch is to arrange that
694      the last WAL segment file written during the backup interval is
695      immediately ready to archive.
696     </para>
697    </listitem>
698    <listitem>
699     <para>
700      Once the WAL segment files used during the backup are archived, you are
701      done.  The file identified by <function>pg_stop_backup</>'s result is
702      the last segment that needs to be archived to complete the backup.  
703      Archival of these files will happen automatically, since you have
704      already configured <varname>archive_command</>. In many cases, this
705      happens fairly quickly, but you are advised to monitor your archival
706      system to ensure this has taken place so that you can be certain you
707      have a complete backup.  
708     </para>
709    </listitem>
710   </orderedlist>
711    </para>
712
713    <para>
714     Some backup tools that you might wish to use emit warnings or errors
715     if the files they are trying to copy change while the copy proceeds.
716     This situation is normal, and not an error, when taking a base backup of
717     an active database; so you need to ensure that you can distinguish
718     complaints of this sort from real errors.  For example, some versions
719     of <application>rsync</> return a separate exit code for <quote>vanished
720     source files</>, and you can write a driver script to accept this exit
721     code as a non-error case.  Also,
722     some versions of GNU <application>tar</> consider it an error if a file
723     is changed while <application>tar</> is copying it.  There does not seem
724     to be any very convenient way to distinguish this error from other types
725     of errors, other than manual inspection of <application>tar</>'s messages.
726     GNU <application>tar</> is therefore not the best tool for making base
727     backups.
728    </para>
729
730    <para>
731     It is not necessary to be very concerned about the amount of time elapsed
732     between <function>pg_start_backup</> and the start of the actual backup,
733     nor between the end of the backup and <function>pg_stop_backup</>; a
734     few minutes' delay won't hurt anything.  (However, if you normally run the
735     server with <varname>full_page_writes</> disabled, you may notice a drop
736     in performance between <function>pg_start_backup</> and 
737     <function>pg_stop_backup</>, since <varname>full_page_writes</> is
738     effectively forced on during backup mode.)  You must ensure that these
739     steps are carried out in sequence without any possible
740     overlap, or you will invalidate the backup.
741    </para>
742
743    <para>
744     Be certain that your backup dump includes all of the files underneath
745     the database cluster directory (e.g., <filename>/usr/local/pgsql/data</>).
746     If you are using tablespaces that do not reside underneath this directory,
747     be careful to include them as well (and be sure that your backup dump
748     archives symbolic links as links, otherwise the restore will mess up
749     your tablespaces).
750    </para>
751
752    <para>
753     You may, however, omit from the backup dump the files within the
754     <filename>pg_xlog/</> subdirectory of the cluster directory.  This
755     slight complication is worthwhile because it reduces the risk
756     of mistakes when restoring.  This is easy to arrange if
757     <filename>pg_xlog/</> is a symbolic link pointing to someplace outside
758     the cluster directory, which is a common setup anyway for performance
759     reasons.
760    </para>
761
762    <para>
763     To make use of the backup, you will need to keep around all the WAL
764     segment files generated during and after the file system backup.
765     To aid you in doing this, the <function>pg_stop_backup</> function
766     creates a <firstterm>backup history file</> that is immediately
767     stored into the WAL archive area. This file is named after the first
768     WAL segment file that you need to have to make use of the backup.
769     For example, if the starting WAL file is
770     <literal>0000000100001234000055CD</> the backup history file will be
771     named something like
772     <literal>0000000100001234000055CD.007C9330.backup</>. (The second
773     number in the file name stands for an exact position within the WAL
774     file, and can ordinarily be ignored.) Once you have safely archived
775     the file system backup and the WAL segment files used during the
776     backup (as specified in the backup history file), all archived WAL
777     segments with names numerically less are no longer needed to recover
778     the file system backup and may be deleted. However, you should
779     consider keeping several backup sets to be absolutely certain that
780     you can recover your data.
781    </para>
782
783    <para>
784     The backup history file is just a small text file. It contains the
785     label string you gave to <function>pg_start_backup</>, as well as
786     the starting and ending times and WAL segments of the backup.
787     If you used the label to identify where the associated dump file is kept, 
788     then the archived history file is enough to tell you which dump file to
789     restore, should you need to do so.
790    </para>
791
792    <para>
793     Since you have to keep around all the archived WAL files back to your
794     last base backup, the interval between base backups should usually be
795     chosen based on how much storage you want to expend on archived WAL
796     files.  You should also consider how long you are prepared to spend
797     recovering, if recovery should be necessary &mdash; the system will have to
798     replay all those WAL segments, and that could take awhile if it has
799     been a long time since the last base backup.
800    </para>
801
802    <para>
803     It's also worth noting that the <function>pg_start_backup</> function
804     makes a file named <filename>backup_label</> in the database cluster
805     directory, which is then removed again by <function>pg_stop_backup</>.
806     This file will of course be archived as a part of your backup dump file.
807     The backup label file includes the label string you gave to
808     <function>pg_start_backup</>, as well as the time at which
809     <function>pg_start_backup</> was run, and the name of the starting WAL
810     file.  In case of confusion it will
811     therefore be possible to look inside a backup dump file and determine
812     exactly which backup session the dump file came from.
813    </para>
814
815    <para>
816     It is also possible to make a backup dump while the server is
817     stopped.  In this case, you obviously cannot use
818     <function>pg_start_backup</> or <function>pg_stop_backup</>, and
819     you will therefore be left to your own devices to keep track of which
820     backup dump is which and how far back the associated WAL files go.
821     It is generally better to follow the continuous archiving procedure above.
822    </para>
823   </sect2>
824
825   <sect2 id="backup-pitr-recovery">
826    <title>Recovering using a Continuous Archive Backup</title>
827
828    <para>
829     Okay, the worst has happened and you need to recover from your backup.
830     Here is the procedure:
831   <orderedlist>
832    <listitem>
833     <para>
834      Stop the server, if it's running.
835     </para>
836    </listitem>
837    <listitem>
838     <para>
839      If you have the space to do so,
840      copy the whole cluster data directory and any tablespaces to a temporary 
841      location in case you need them later. Note that this precaution will
842      require that you have enough free space on your system to hold two
843      copies of your existing database. If you do not have enough space, 
844      you need at the least to copy the contents of the <filename>pg_xlog</>
845      subdirectory of the cluster data directory, as it may contain logs which
846      were not archived before the system went down.
847     </para>
848    </listitem>
849    <listitem>
850     <para>
851      Clean out all existing files and subdirectories under the cluster data
852      directory and under the root directories of any tablespaces you are using.
853     </para>
854    </listitem>
855    <listitem>
856     <para>
857      Restore the database files from your backup dump.  Be careful that they
858      are restored with the right ownership (the database system user, not
859      root!) and with the right permissions.  If you are using tablespaces,
860      you should verify that the symbolic links in <filename>pg_tblspc/</>
861      were correctly restored.
862     </para>
863    </listitem>
864    <listitem>
865     <para>
866      Remove any files present in <filename>pg_xlog/</>; these came from the
867      backup dump and are therefore probably obsolete rather than current.
868      If you didn't archive <filename>pg_xlog/</> at all, then recreate it,
869      and be sure to recreate the subdirectory
870     <filename>pg_xlog/archive_status/</> as well.
871     </para>
872    </listitem>
873    <listitem>
874     <para>
875      If you had unarchived WAL segment files that you saved in step 2,
876      copy them into <filename>pg_xlog/</>.  (It is best to copy them,
877      not move them, so that you still have the unmodified files if a
878      problem occurs and you have to start over.)
879     </para>
880    </listitem>
881    <listitem>
882     <para>
883      Create a recovery command file <filename>recovery.conf</> in the cluster
884      data directory (see <xref linkend="recovery-config-settings">). You may 
885      also want to temporarily modify <filename>pg_hba.conf</> to prevent 
886      ordinary users from connecting until you are sure the recovery has worked.
887     </para>
888    </listitem>
889    <listitem>
890     <para>
891      Start the server.  The server will go into recovery mode and
892      proceed to read through the archived WAL files it needs.  Should the
893      recovery be terminated because of an external error, the server can
894      simply be restarted and it will continue recovery.  Upon completion
895      of the recovery process, the server will rename
896      <filename>recovery.conf</> to <filename>recovery.done</> (to prevent
897      accidentally re-entering recovery mode in case of a crash later) and then
898      commence normal database operations.
899     </para>
900    </listitem>
901    <listitem>
902     <para>
903      Inspect the contents of the database to ensure you have recovered to
904      where you want to be.  If not, return to step 1.  If all is well,
905      let in your users by restoring <filename>pg_hba.conf</> to normal.
906     </para>
907    </listitem>
908   </orderedlist>
909    </para>
910
911    <para>
912     The key part of all this is to setup a recovery command file that
913     describes how you want to recover and how far the recovery should
914     run.  You can use <filename>recovery.conf.sample</> (normally
915     installed in the installation <filename>share/</> directory) as a
916     prototype.  The one thing that you absolutely must specify in
917     <filename>recovery.conf</> is the <varname>restore_command</>,
918     which tells <productname>PostgreSQL</> how to get back archived
919     WAL file segments.  Like the <varname>archive_command</>, this is
920     a shell command string.  It may contain <literal>%f</>, which is
921     replaced by the name of the desired log file, and <literal>%p</>,
922     which is replaced by the path name to copy the log file to.
923     (The path name is relative to the working directory of the server,
924     i.e., the cluster's data directory.)
925     Write <literal>%%</> if you need to embed an actual <literal>%</>
926     character in the command.  The simplest useful command is
927     something like
928 <programlisting>
929 restore_command = 'cp /mnt/server/archivedir/%f %p'
930 </programlisting>
931     which will copy previously archived WAL segments from the directory
932     <filename>/mnt/server/archivedir</>.  You could of course use something
933     much more complicated, perhaps even a shell script that requests the
934     operator to mount an appropriate tape.
935    </para>
936
937    <para>
938     It is important that the command return nonzero exit status on failure.
939     The command <emphasis>will</> be asked for log files that are not present
940     in the archive; it must return nonzero when so asked.  This is not an
941     error condition.  Be aware also that the base name of the <literal>%p</>
942     path will be different from <literal>%f</>; do not expect them to be
943     interchangeable.
944    </para>
945
946    <para>
947     WAL segments that cannot be found in the archive will be sought in
948     <filename>pg_xlog/</>; this allows use of recent un-archived segments.
949     However segments that are available from the archive will be used in
950     preference to files in <filename>pg_xlog/</>.  The system will not
951     overwrite the existing contents of <filename>pg_xlog/</> when retrieving
952     archived files.
953    </para>
954
955    <para>
956     Normally, recovery will proceed through all available WAL segments,
957     thereby restoring the database to the current point in time (or as
958     close as we can get given the available WAL segments).  But if you want
959     to recover to some previous point in time (say, right before the junior
960     DBA dropped your main transaction table), just specify the required
961     stopping point in <filename>recovery.conf</>.  You can specify the stop
962     point, known as the <quote>recovery target</>, either by date/time or
963     by completion of a specific transaction ID.  As of this writing only
964     the date/time option is very usable, since there are no tools to help
965     you identify with any accuracy which transaction ID to use.
966    </para>
967
968    <note>
969      <para>
970       The stop point must be after the ending time of the base backup (the
971       time of <function>pg_stop_backup</>).  You cannot use a base backup
972       to recover to a time when that backup was still going on.  (To
973       recover to such a time, you must go back to your previous base backup
974       and roll forward from there.)
975      </para>
976    </note>
977
978    <para>
979     If recovery finds a corruption in the WAL data then recovery will
980     complete at that point and the server will not start. In such a case the
981     recovery process could be re-run from the beginning, specifying a 
982     <quote>recovery target</> before the point of corruption so that recovery
983     can complete normally.
984     If recovery fails for an external reason, such as a system crash or
985     if the WAL archive has become inaccessible, then the recovery can simply
986     be restarted and it will restart almost from where it failed.
987     Recovery restart works much like checkpointing in normal operation:
988     the server periodically forces all its state to disk, and then updates
989     the <filename>pg_control</> file to indicate that the already-processed
990     WAL data need not be scanned again.
991    </para>
992
993
994     <sect3 id="recovery-config-settings" xreflabel="Recovery Settings">
995      <title>Recovery Settings</title>
996
997      <para>
998       These settings can only be made in the <filename>recovery.conf</>
999       file, and apply only for the duration of the recovery. They must be
1000       reset for any subsequent recovery you wish to perform. They cannot be
1001       changed once recovery has begun.
1002      </para>
1003
1004      <variablelist>
1005
1006      <varlistentry id="restore-command" xreflabel="restore_command">
1007       <term><varname>restore_command</varname> (<type>string</type>)</term>
1008       <listitem>
1009        <para>
1010         The shell command to execute to retrieve an archived segment of
1011         the WAL file series. This parameter is required.
1012         Any <literal>%f</> in the string is
1013         replaced by the name of the file to retrieve from the archive,
1014         and any <literal>%p</> is replaced by the path name to copy
1015         it to on the server.
1016         (The path name is relative to the working directory of the server,
1017         i.e., the cluster's data directory.)
1018         Write <literal>%%</> to embed an actual <literal>%</> character
1019         in the command. 
1020        </para>
1021        <para>
1022         It is important for the command to return a zero exit status if and
1023         only if it succeeds.  The command <emphasis>will</> be asked for file
1024         names that are not present in the archive; it must return nonzero
1025         when so asked.  Examples:
1026 <programlisting>
1027 restore_command = 'cp /mnt/server/archivedir/%f "%p"'
1028 restore_command = 'copy /mnt/server/archivedir/%f "%p"'  # Windows
1029 </programlisting>
1030        </para>
1031       </listitem>
1032      </varlistentry>
1033
1034      <varlistentry id="recovery-target-time" xreflabel="recovery_target_time">
1035       <term><varname>recovery_target_time</varname> 
1036            (<type>timestamp</type>)
1037       </term>
1038       <listitem>
1039        <para>
1040         This parameter specifies the time stamp up to which recovery
1041         will proceed.
1042         At most one of <varname>recovery_target_time</> and
1043         <xref linkend="recovery-target-xid"> can be specified.
1044         The default is to recover to the end of the WAL log.
1045         The precise stopping point is also influenced by 
1046         <xref linkend="recovery-target-inclusive">.
1047        </para>
1048       </listitem>
1049      </varlistentry>
1050
1051      <varlistentry id="recovery-target-xid" xreflabel="recovery_target_xid">
1052       <term><varname>recovery_target_xid</varname> (<type>string</type>)</term>
1053       <listitem>
1054        <para>
1055         This parameter specifies the transaction ID up to which recovery
1056         will proceed. Keep in mind 
1057         that while transaction IDs are assigned sequentially at transaction 
1058         start, transactions can complete in a different numeric order.
1059         The transactions that will be recovered are those that committed
1060         before (and optionally including) the specified one.
1061         At most one of <varname>recovery_target_xid</> and
1062         <xref linkend="recovery-target-time"> can be specified.
1063         The default is to recover to the end of the WAL log.
1064         The precise stopping point is also influenced by 
1065         <xref linkend="recovery-target-inclusive">.
1066        </para>
1067       </listitem>
1068      </varlistentry>
1069
1070      <varlistentry id="recovery-target-inclusive" 
1071                    xreflabel="recovery_target_inclusive">
1072       <term><varname>recovery_target_inclusive</varname> 
1073         (<type>boolean</type>)
1074       </term>
1075       <listitem>
1076        <para>
1077         Specifies whether we stop just after the specified recovery target
1078         (<literal>true</literal>), or just before the recovery target 
1079         (<literal>false</literal>).
1080         Applies to both <xref linkend="recovery-target-time">
1081         and <xref linkend="recovery-target-xid">, whichever one is
1082         specified for this recovery.  This indicates whether transactions
1083         having exactly the target commit time or ID, respectively, will
1084         be included in the recovery.  Default is <literal>true</>.
1085        </para>
1086       </listitem>
1087      </varlistentry>
1088
1089      <varlistentry id="recovery-target-timeline" 
1090                    xreflabel="recovery_target_timeline">
1091       <term><varname>recovery_target_timeline</varname> 
1092         (<type>string</type>)
1093       </term>
1094       <listitem>
1095        <para>
1096         Specifies recovering into a particular timeline.  The default is
1097         to recover along the same timeline that was current when the
1098         base backup was taken.  You would only need to set this parameter
1099         in complex re-recovery situations, where you need to return to
1100         a state that itself was reached after a point-in-time recovery.
1101         See <xref linkend="backup-timelines"> for discussion.
1102        </para>
1103       </listitem>
1104      </varlistentry>
1105
1106    </variablelist>
1107
1108    </sect3>
1109
1110   </sect2>
1111
1112   <sect2 id="backup-timelines">
1113    <title>Timelines</title>
1114
1115   <indexterm zone="backup">
1116    <primary>timelines</primary>
1117   </indexterm>
1118
1119    <para>
1120     The ability to restore the database to a previous point in time creates
1121     some complexities that are akin to science-fiction stories about time
1122     travel and parallel universes.  In the original history of the database,
1123     perhaps you dropped a critical table at 5:15PM on Tuesday evening.
1124     Unfazed, you get out your backup, restore to the point-in-time 5:14PM
1125     Tuesday evening, and are up and running.  In <emphasis>this</> history of
1126     the database universe, you never dropped the table at all.  But suppose
1127     you later realize this wasn't such a great idea after all, and would like
1128     to return to some later point in the original history.  You won't be able
1129     to if, while your database was up-and-running, it overwrote some of the
1130     sequence of WAL segment files that led up to the time you now wish you
1131     could get back to.  So you really want to distinguish the series of
1132     WAL records generated after you've done a point-in-time recovery from
1133     those that were generated in the original database history.
1134    </para>
1135
1136    <para>
1137     To deal with these problems, <productname>PostgreSQL</> has a notion
1138     of <firstterm>timelines</>.  Each time you recover to a point-in-time
1139     earlier than the end of the WAL sequence, a new timeline is created
1140     to identify the series of WAL records generated after that recovery.
1141     (If recovery proceeds all the way to the end of WAL, however, we do not
1142     start a new timeline: we just extend the existing one.)  The timeline
1143     ID number is part of WAL segment file names, and so a new timeline does
1144     not overwrite the WAL data generated by previous timelines.  It is
1145     in fact possible to archive many different timelines.  While that might
1146     seem like a useless feature, it's often a lifesaver.  Consider the
1147     situation where you aren't quite sure what point-in-time to recover to,
1148     and so have to do several point-in-time recoveries by trial and error
1149     until you find the best place to branch off from the old history.  Without
1150     timelines this process would soon generate an unmanageable mess.  With
1151     timelines, you can recover to <emphasis>any</> prior state, including
1152     states in timeline branches that you later abandoned.
1153    </para>
1154
1155    <para>
1156     Each time a new timeline is created, <productname>PostgreSQL</> creates
1157     a <quote>timeline history</> file that shows which timeline it branched
1158     off from and when.  These history files are necessary to allow the system
1159     to pick the right WAL segment files when recovering from an archive that
1160     contains multiple timelines.  Therefore, they are archived into the WAL
1161     archive area just like WAL segment files.  The history files are just
1162     small text files, so it's cheap and appropriate to keep them around
1163     indefinitely (unlike the segment files which are large).  You can, if
1164     you like, add comments to a history file to make your own notes about
1165     how and why this particular timeline came to be.  Such comments will be
1166     especially valuable when you have a thicket of different timelines as
1167     a result of experimentation.
1168    </para>
1169
1170    <para>
1171     The default behavior of recovery is to recover along the same timeline
1172     that was current when the base backup was taken.  If you want to recover
1173     into some child timeline (that is, you want to return to some state that
1174     was itself generated after a recovery attempt), you need to specify the
1175     target timeline ID in <filename>recovery.conf</>.  You cannot recover into
1176     timelines that branched off earlier than the base backup.
1177    </para>
1178   </sect2>
1179
1180   <sect2 id="continuous-archiving-caveats">
1181    <title>Caveats</title>
1182
1183    <para>
1184     At this writing, there are several limitations of the continuous archiving
1185     technique.  These will probably be fixed in future releases:
1186
1187   <itemizedlist>
1188    <listitem>
1189     <para>
1190      Operations on hash indexes are not presently WAL-logged, so
1191      replay will not update these indexes.  The recommended workaround
1192      is to manually <xref linkend="sql-reindex" endterm="sql-reindex-title">
1193      each such index after completing a recovery operation.
1194     </para>
1195    </listitem>
1196
1197    <listitem>
1198     <para>
1199      If a <xref linkend="sql-createdatabase" endterm="sql-createdatabase-title">
1200      command is executed while a base backup is being taken, and then
1201      the template database that the <command>CREATE DATABASE</> copied
1202      is modified while the base backup is still in progress, it is
1203      possible that recovery will cause those modifications to be
1204      propagated into the created database as well.  This is of course
1205      undesirable.  To avoid this risk, it is best not to modify any
1206      template databases while taking a base backup.
1207     </para>
1208    </listitem>
1209
1210    <listitem>
1211     <para>
1212      <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1213      commands are WAL-logged with the literal absolute path, and will
1214      therefore be replayed as tablespace creations with the same
1215      absolute path.  This might be undesirable if the log is being
1216      replayed on a different machine.  It can be dangerous even if the
1217      log is being replayed on the same machine, but into a new data
1218      directory: the replay will still overwrite the contents of the
1219      original tablespace.  To avoid potential gotchas of this sort,
1220      the best practice is to take a new base backup after creating or
1221      dropping tablespaces.
1222     </para>
1223    </listitem>
1224   </itemizedlist>
1225    </para>
1226
1227    <para>
1228     It should also be noted that the default <acronym>WAL</acronym>
1229     format is fairly bulky since it includes many disk page snapshots.
1230     These page snapshots are designed to support crash recovery, since
1231     we may need to fix partially-written disk pages.  Depending on
1232     your system hardware and software, the risk of partial writes may
1233     be small enough to ignore, in which case you can significantly
1234     reduce the total volume of archived logs by turning off page
1235     snapshots using the <xref linkend="guc-full-page-writes">
1236     parameter.  (Read the notes and warnings in <xref linkend="wal">
1237     before you do so.)  Turning off page snapshots does not prevent
1238     use of the logs for PITR operations.  An area for future
1239     development is to compress archived WAL data by removing
1240     unnecessary page copies even when <varname>full_page_writes</> is
1241     on.  In the meantime, administrators may wish to reduce the number
1242     of page snapshots included in WAL by increasing the checkpoint
1243     interval parameters as much as feasible.
1244    </para>
1245   </sect2>
1246  </sect1>
1247
1248  <sect1 id="warm-standby">
1249   <title>Warm Standby Servers for High Availability</title>
1250
1251   <indexterm zone="backup">
1252    <primary>warm standby</primary>
1253   </indexterm>
1254
1255   <indexterm zone="backup">
1256    <primary>PITR standby</primary>
1257   </indexterm>
1258
1259   <indexterm zone="backup">
1260    <primary>standby server</primary>
1261   </indexterm>
1262
1263   <indexterm zone="backup">
1264    <primary>log shipping</primary>
1265   </indexterm>
1266
1267   <indexterm zone="backup">
1268    <primary>witness server</primary>
1269   </indexterm>
1270
1271   <indexterm zone="backup">
1272    <primary>STONITH</primary>
1273   </indexterm>
1274
1275   <indexterm zone="backup">
1276    <primary>high availability</primary>
1277   </indexterm>
1278
1279   <para>
1280    Continuous archiving can be used to create a <firstterm>high
1281    availability</> (HA) cluster configuration with one or more
1282    <firstterm>standby servers</> ready to take 
1283    over operations if the primary server fails. This
1284    capability is widely referred to as <firstterm>warm standby</>
1285    or <firstterm>log shipping</>.
1286   </para>
1287
1288   <para>
1289    The primary and standby server work together to provide this capability,
1290    though the servers are only loosely coupled. The primary server operates
1291    in continuous archiving mode, while each standby server operates in
1292    continuous recovery mode, reading the WAL files from the primary. No
1293    changes to the database tables are required to enable this capability,
1294    so it offers low administration overhead in comparison with some other
1295    replication approaches. This configuration also has relatively low
1296    performance impact on the primary server.
1297   </para>
1298
1299   <para>
1300    Directly moving WAL or "log" records from one database server to another
1301    is typically described as log shipping. <productname>PostgreSQL</>
1302    implements file-based log shipping, which means that WAL records are
1303    transferred one file (WAL segment) at a time. WAL
1304    files can be shipped easily and cheaply over any distance, whether it be
1305    to an adjacent system, another system on the same site or another system
1306    on the far side of the globe. The bandwidth required for this technique
1307    varies according to the transaction rate of the primary server.
1308    Record-based log shipping is also possible with custom-developed
1309    procedures, as discussed in <xref linkend="warm-standby-record">.
1310   </para>
1311
1312   <para>
1313    It should be noted that the log shipping is asynchronous, i.e. the
1314    WAL records are shipped after transaction commit. As a result there
1315    is a window for data loss should the primary server
1316    suffer a catastrophic failure: transactions not yet shipped will be lost.
1317    The length of the window of data loss
1318    can be limited by use of the <varname>archive_timeout</varname> parameter,
1319    which can be set as low as a few seconds if required.  However such low
1320    settings will substantially increase the bandwidth requirements for file
1321    shipping.  If you need a window of less than a minute or so, it's probably
1322    better to look into record-based log shipping.
1323   </para>
1324
1325   <para>
1326    The standby server is not available for access, since it is continually
1327    performing recovery processing. Recovery performance is sufficiently
1328    good that the standby will typically be only moments away from full
1329    availability once it has been activated. As a result, we refer to this
1330    capability as a warm standby configuration that offers high
1331    availability. Restoring a server from an archived base backup and
1332    rollforward will take considerably longer, so that technique only
1333    really offers a solution for disaster recovery, not HA.
1334   </para>
1335
1336   <sect2 id="warm-standby-planning">
1337    <title>Planning</title>
1338
1339    <para>
1340     It is usually wise to create the primary and standby servers
1341     so that they are as similar as possible, at least from the
1342     perspective of the database server.  In particular, the path names
1343     associated with tablespaces will be passed across as-is, so both
1344     primary and standby servers must have the same mount paths for
1345     tablespaces if that feature is used.  Keep in mind that if
1346     <xref linkend="sql-createtablespace" endterm="sql-createtablespace-title">
1347     is executed on the primary, any new mount point needed for it must
1348     be created on both the primary and all standby servers before the command
1349     is executed. Hardware need not be exactly the same, but experience shows
1350     that maintaining two identical systems is easier than maintaining two
1351     dissimilar ones over the lifetime of the application and system.
1352     In any case the hardware architecture must be the same &mdash; shipping
1353     from, say, a 32-bit to a 64-bit system will not work.
1354    </para>
1355
1356    <para>
1357     In general, log shipping between servers running different major release
1358     levels will not be possible. It is the policy of the PostgreSQL Global
1359     Development Group not to make changes to disk formats during minor release
1360     upgrades, so it is likely that running different minor release levels 
1361     on primary and standby servers will work successfully. However, no
1362     formal support for that is offered and you are advised to keep primary
1363     and standby servers at the same release level as much as possible.
1364     When updating to a new minor release, the safest policy is to update
1365     the standby servers first &mdash; a new minor release is more likely
1366     to be able to read WAL files from a previous minor release than vice
1367     versa.
1368    </para>
1369
1370    <para>
1371     There is no special mode required to enable a standby server. The
1372     operations that occur on both primary and standby servers are entirely
1373     normal continuous archiving and recovery tasks. The only point of
1374     contact between the two database servers is the archive of WAL files
1375     that both share: primary writing to the archive, standby reading from
1376     the archive. Care must be taken to ensure that WAL archives for separate
1377     primary servers do not become mixed together or confused.
1378    </para>
1379
1380    <para>
1381     The magic that makes the two loosely coupled servers work together
1382     is simply a <varname>restore_command</> used on the standby that waits for
1383     the next WAL file to become available from the primary. The
1384     <varname>restore_command</> is specified in the <filename>recovery.conf</>
1385     file on the standby 
1386     server. Normal recovery processing would request a file from the
1387     WAL archive, reporting failure if the file was unavailable.  For
1388     standby processing it is normal for the next file to be
1389     unavailable, so we must be patient and wait for it to appear. A
1390     waiting <varname>restore_command</> can be written as a custom
1391     script that loops after polling for the existence of the next WAL
1392     file. There must also be some way to trigger failover, which
1393     should interrupt the <varname>restore_command</>, break the loop
1394     and return a file-not-found error to the standby server. This
1395     ends recovery and the standby will then come up as a normal
1396     server.
1397    </para>
1398
1399    <para>
1400     Pseudocode for a suitable <varname>restore_command</> is:
1401 <programlisting>
1402 triggered = false;
1403 while (!NextWALFileReady() && !triggered)
1404 {
1405     sleep(100000L);         /* wait for ~0.1 sec */
1406     if (CheckForExternalTrigger())
1407         triggered = true;
1408 }
1409 if (!triggered)
1410         CopyWALFileForRecovery();
1411 </programlisting>
1412    </para>
1413
1414    <para>
1415     <productname>PostgreSQL</productname> does not provide the system
1416     software required to identify a failure on the primary and notify
1417     the standby system and then the standby database server. Many such
1418     tools exist and are well integrated with other aspects required for
1419     successful failover, such as IP address migration.
1420    </para>
1421
1422    <para>
1423     The means for triggering failover is an important part of planning and
1424     design. The <varname>restore_command</> is executed in full once
1425     for each WAL file. The process running the <varname>restore_command</>
1426     is therefore created and dies for each file, so there is no daemon
1427     or server process and so we cannot use signals and a signal
1428     handler. A more permanent notification is required to trigger the
1429     failover. It is possible to use a simple timeout facility,
1430     especially if used in conjunction with a known
1431     <varname>archive_timeout</> setting on the primary. This is
1432     somewhat error prone since a network problem or busy primary server might
1433     be sufficient to initiate failover. A notification mechanism such
1434     as the explicit creation of a trigger file is less error prone, if
1435     this can be arranged.
1436    </para>
1437   </sect2>
1438
1439   <sect2 id="warm-standby-config">
1440    <title>Implementation</title>
1441
1442    <para>
1443     The short procedure for configuring a standby server is as follows. For
1444     full details of each step, refer to previous sections as noted.
1445     <orderedlist>
1446      <listitem>
1447       <para>
1448        Set up primary and standby systems as near identically as
1449        possible, including two identical copies of
1450        <productname>PostgreSQL</> at the same release level.
1451       </para>
1452      </listitem>
1453      <listitem>
1454       <para>
1455        Set up continuous archiving from the primary to a WAL archive located
1456        in a directory on the standby server. Ensure that <xref
1457        linkend="guc-archive-command"> and <xref linkend="guc-archive-timeout">
1458        are set appropriately on the primary
1459        (see <xref linkend="backup-archiving-wal">).
1460       </para>
1461      </listitem>
1462      <listitem>
1463       <para>
1464        Make a base backup of the primary server (see <xref
1465        linkend="backup-base-backup">), and load this data onto the standby.
1466       </para>
1467      </listitem>
1468      <listitem>
1469       <para>
1470        Begin recovery on the standby server from the local WAL
1471        archive, using a <filename>recovery.conf</> that specifies a
1472        <varname>restore_command</> that waits as described
1473        previously (see <xref linkend="backup-pitr-recovery">).
1474       </para>
1475      </listitem>
1476     </orderedlist>
1477    </para>
1478
1479    <para>
1480     Recovery treats the WAL archive as read-only, so once a WAL file has
1481     been copied to the standby system it can be copied to tape at the same
1482     time as it is being read by the standby database server.
1483     Thus, running a standby server for high availability can be performed at
1484     the same time as files are stored for longer term disaster recovery
1485     purposes. 
1486    </para>
1487
1488    <para>
1489     For testing purposes, it is possible to run both primary and standby
1490     servers on the same system. This does not provide any worthwhile
1491     improvement in server robustness, nor would it be described as HA.
1492    </para>
1493   </sect2>
1494
1495   <sect2 id="warm-standby-failover">
1496    <title>Failover</title>
1497
1498    <para>
1499     If the primary server fails then the standby server should begin
1500     failover procedures.
1501    </para>
1502
1503    <para>
1504     If the standby server fails then no failover need take place. If the
1505     standby server can be restarted, even some time later, then the recovery
1506     process can also be immediately restarted, taking advantage of 
1507     restartable recovery. If the standby server cannot be restarted, then a
1508     full new standby server should be created.
1509    </para>
1510
1511    <para>
1512     If the primary server fails and then immediately restarts, you must have
1513     a mechanism for informing it that it is no longer the primary. This is
1514     sometimes known as STONITH (Shoot the Other Node In The Head), which is
1515     necessary to avoid situations where both systems think they are the
1516     primary, which can lead to confusion and ultimately data loss.
1517    </para>
1518
1519    <para>
1520     Many failover systems use just two systems, the primary and the standby,
1521     connected by some kind of heartbeat mechanism to continually verify the
1522     connectivity between the two and the viability of the primary. It is
1523     also possible to use a third system (called a witness server) to avoid
1524     some problems of inappropriate failover, but the additional complexity
1525     may not be worthwhile unless it is set-up with sufficient care and
1526     rigorous testing.
1527    </para>
1528
1529    <para>
1530     Once failover to the standby occurs, we have only a
1531     single server in operation. This is known as a degenerate state.
1532     The former standby is now the primary, but the former primary is down 
1533     and may stay down.  To return to normal operation we must
1534     fully recreate a standby server, 
1535     either on the former primary system when it comes up, or on a third, 
1536     possibly new, system. Once complete the primary and standby can be 
1537     considered to have switched roles. Some people choose to use a third 
1538     server to provide backup to the new primary until the new standby
1539     server is recreated,
1540     though clearly this complicates the system configuration and 
1541     operational processes.
1542    </para>
1543
1544    <para>
1545     So, switching from primary to standby server can be fast but requires
1546     some time to re-prepare the failover cluster. Regular switching from
1547     primary to standby is encouraged, since it allows regular downtime on
1548     each system for maintenance. This also acts as a test of the
1549     failover mechanism to ensure that it will really work when you need it. 
1550     Written administration procedures are advised.
1551    </para>
1552   </sect2>
1553
1554   <sect2 id="warm-standby-record">
1555    <title>Record-based Log Shipping</title>
1556
1557    <para>
1558     <productname>PostgreSQL</productname> directly supports file-based
1559     log shipping as described above. It is also possible to implement
1560     record-based log shipping, though this requires custom development.
1561    </para>
1562
1563    <para>
1564     An external program can call the <function>pg_xlogfile_name_offset()</>
1565     function (see <xref linkend="functions-admin">)
1566     to find out the file name and the exact byte offset within it of
1567     the current end of WAL.  It can then access the WAL file directly
1568     and copy the data from the last known end of WAL through the current end
1569     over to the standby server(s).  With this approach, the window for data
1570     loss is the polling cycle time of the copying program, which can be very
1571     small, but there is no wasted bandwidth from forcing partially-used
1572     segment files to be archived.  Note that the standby servers' 
1573     <varname>restore_command</> scripts still deal in whole WAL files,
1574     so the incrementally copied data is not ordinarily made available to
1575     the standby servers.  It is of use only when the primary dies &mdash;
1576     then the last partial WAL file is fed to the standby before allowing
1577     it to come up.  So correct implementation of this process requires
1578     cooperation of the <varname>restore_command</> script with the data
1579     copying program.
1580    </para>
1581   </sect2>
1582
1583   <sect2 id="backup-incremental-updated">
1584    <title>Incrementally Updated Backups</title>
1585
1586   <indexterm zone="backup">
1587    <primary>incrementally updated backups</primary>
1588   </indexterm>
1589
1590   <indexterm zone="backup">
1591    <primary>change accumulation</primary>
1592   </indexterm>
1593
1594    <para>
1595     In a warm standby configuration, it is possible to offload the expense of
1596     taking periodic base backups from the primary server; instead base backups
1597     can be made by backing
1598     up a standby server's files.  This concept is generally known as 
1599     incrementally updated backups, log change accumulation or more simply,
1600     change accumulation.
1601    </para>
1602
1603    <para>
1604     If we take a backup of the standby server's files while it is following
1605     logs shipped from the primary, we will be able to reload that data and
1606     restart the standby's recovery process from the last restart point.
1607     We no longer need to keep WAL files from before the restart point.
1608     If we need to recover, it will be faster to recover from the incrementally
1609     updated backup than from the original base backup.
1610    </para>
1611
1612    <para>
1613     Since the standby server is not <quote>live</>, it is not possible to
1614     use <function>pg_start_backup()</> and <function>pg_stop_backup()</>
1615     to manage the backup process; it will be up to you to determine how
1616     far back you need to keep WAL segment files to have a recoverable
1617     backup.  You can do this by running <application>pg_controldata</>
1618     on the standby server to inspect the control file and determine the
1619     current checkpoint WAL location.
1620    </para>
1621   </sect2>
1622  </sect1>
1623
1624  <sect1 id="migration">
1625   <title>Migration Between Releases</title>
1626
1627   <indexterm zone="migration">
1628    <primary>upgrading</primary>
1629   </indexterm>
1630
1631   <indexterm zone="migration">
1632    <primary>version</primary>
1633    <secondary>compatibility</secondary>
1634   </indexterm>
1635
1636   <para>
1637    This section discusses how to migrate your database data from one
1638    <productname>PostgreSQL</> release to a newer one.
1639    The software installation procedure <foreignphrase>per se</> is not the
1640    subject of this section; those details are in <xref linkend="installation">.
1641   </para>
1642
1643   <para>
1644    As a general rule, the internal data storage format is subject to
1645    change between major releases of <productname>PostgreSQL</> (where
1646    the number after the first dot changes). This does not apply to
1647    different minor releases under the same major release (where the
1648    number after the second dot changes); these always have compatible
1649    storage formats. For example, releases 7.2.1, 7.3.2, and 7.4 are
1650    not compatible, whereas 7.2.1 and 7.2.2 are. When you update
1651    between compatible versions, you can simply replace the executables
1652    and reuse the data directory on disk. Otherwise you need to back
1653    up your data and restore it on the new server.  This has to be done
1654    using <application>pg_dump</>; file system level backup methods
1655    obviously won't work. There are checks in place that prevent you
1656    from using a data directory with an incompatible version of
1657    <productname>PostgreSQL</productname>, so no great harm can be done by
1658    trying to start the wrong server version on a data directory.
1659   </para>
1660
1661   <para>
1662    It is recommended that you use the <application>pg_dump</> and
1663    <application>pg_dumpall</> programs from the newer version of
1664    <productname>PostgreSQL</>, to take advantage of any enhancements
1665    that may have been made in these programs.  Current releases of the
1666    dump programs can read data from any server version back to 7.0.
1667   </para>
1668
1669   <para>
1670    The least downtime can be achieved by installing the new server in
1671    a different directory and running both the old and the new servers
1672    in parallel, on different ports. Then you can use something like
1673
1674 <programlisting>
1675 pg_dumpall -p 5432 | psql -d postgres -p 6543
1676 </programlisting>
1677
1678    to transfer your data.  Or use an intermediate file if you want.
1679    Then you can shut down the old server and start the new server at
1680    the port the old one was running at. You should make sure that the
1681    old database is not updated after you run <application>pg_dumpall</>,
1682    otherwise you will obviously lose that data. See <xref
1683    linkend="client-authentication"> for information on how to prohibit
1684    access.
1685   </para>
1686
1687   <para>
1688    In practice you probably want to test your client
1689    applications on the new setup before switching over completely.
1690    This is another reason for setting up concurrent installations
1691    of old and new versions.
1692   </para>
1693
1694   <para>
1695    If you cannot or do not want to run two servers in parallel you can
1696    do the backup step before installing the new version, bring down
1697    the server, move the old version out of the way, install the new
1698    version, start the new server, restore the data. For example:
1699
1700 <programlisting>
1701 pg_dumpall &gt; backup
1702 pg_ctl stop
1703 mv /usr/local/pgsql /usr/local/pgsql.old
1704 cd ~/postgresql-&version;
1705 gmake install
1706 initdb -D /usr/local/pgsql/data
1707 postgres -D /usr/local/pgsql/data
1708 psql -f backup postgres
1709 </programlisting>
1710
1711    See <xref linkend="runtime"> about ways to start and stop the
1712    server and other details. The installation instructions will advise
1713    you of strategic places to perform these steps.
1714   </para>
1715
1716   <note>
1717    <para>
1718     When you <quote>move the old installation out of the way</quote>
1719     it may no longer be perfectly usable. Some of the executable programs
1720     contain absolute paths to various installed programs and data files.
1721     This is usually not a big problem but if you plan on using two
1722     installations in parallel for a while you should assign them
1723     different installation directories at build time.  (This problem
1724     is rectified in <productname>PostgreSQL</> 8.0 and later, but you
1725     need to be wary of moving older installations.)
1726    </para>
1727   </note>
1728  </sect1>
1729 </chapter>