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