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