gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

881 lines
62KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>25.3. Continuous Archiving and Point-in-Time Recovery (PITR)</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="backup-file.html" title="25.2. File System Level Backup" /><link rel="next" href="high-availability.html" title="Chapter 26. High Availability, Load Balancing, and Replication" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">25.3. Continuous Archiving and Point-in-Time Recovery (PITR)</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="backup-file.html" title="25.2. File System Level Backup">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="backup.html" title="Chapter 25. Backup and Restore">Up</a></td><th width="60%" align="center">Chapter 25. Backup and Restore</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="high-availability.html" title="Chapter 26. High Availability, Load Balancing, and Replication">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="CONTINUOUS-ARCHIVING"><div class="titlepage"><div><div><h2 class="title" style="clear: both">25.3. Continuous Archiving and Point-in-Time Recovery (PITR)</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-ARCHIVING-WAL">25.3.1. Setting Up WAL Archiving</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-BASE-BACKUP">25.3.2. Making a Base Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP">25.3.3. Making a Base Backup Using the Low Level API</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-PITR-RECOVERY">25.3.4. Recovering Using a Continuous Archive Backup</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-TIMELINES">25.3.5. Timelines</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#BACKUP-TIPS">25.3.6. Tips and Examples</a></span></dt><dt><span class="sect2"><a href="continuous-archiving.html#CONTINUOUS-ARCHIVING-CAVEATS">25.3.7. Caveats</a></span></dt></dl></div><a id="id-1.6.12.7.2" class="indexterm"></a><a id="id-1.6.12.7.3" class="indexterm"></a><a id="id-1.6.12.7.4" class="indexterm"></a><p>
  3. At all times, <span class="productname">PostgreSQL</span> maintains a
  4. <em class="firstterm">write ahead log</em> (WAL) in the <code class="filename">pg_wal/</code>
  5. subdirectory of the cluster's data directory. The log records
  6. every change made to the database's data files. This log exists
  7. primarily for crash-safety purposes: if the system crashes, the
  8. database can be restored to consistency by <span class="quote">“<span class="quote">replaying</span>”</span> the
  9. log entries made since the last checkpoint. However, the existence
  10. of the log makes it possible to use a third strategy for backing up
  11. databases: we can combine a file-system-level backup with backup of
  12. the WAL files. If recovery is needed, we restore the file system backup and
  13. then replay from the backed-up WAL files to bring the system to a
  14. current state. This approach is more complex to administer than
  15. either of the previous approaches, but it has some significant
  16. benefits:
  17. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  18. We do not need a perfectly consistent file system backup as the starting point.
  19. Any internal inconsistency in the backup will be corrected by log
  20. replay (this is not significantly different from what happens during
  21. crash recovery). So we do not need a file system snapshot capability,
  22. just <span class="application">tar</span> or a similar archiving tool.
  23. </p></li><li class="listitem"><p>
  24. Since we can combine an indefinitely long sequence of WAL files
  25. for replay, continuous backup can be achieved simply by continuing to archive
  26. the WAL files. This is particularly valuable for large databases, where
  27. it might not be convenient to take a full backup frequently.
  28. </p></li><li class="listitem"><p>
  29. It is not necessary to replay the WAL entries all the
  30. way to the end. We could stop the replay at any point and have a
  31. consistent snapshot of the database as it was at that time. Thus,
  32. this technique supports <em class="firstterm">point-in-time recovery</em>: it is
  33. possible to restore the database to its state at any time since your base
  34. backup was taken.
  35. </p></li><li class="listitem"><p>
  36. If we continuously feed the series of WAL files to another
  37. machine that has been loaded with the same base backup file, we
  38. have a <em class="firstterm">warm standby</em> system: at any point we can bring up
  39. the second machine and it will have a nearly-current copy of the
  40. database.
  41. </p></li></ul></div><p>
  42. </p><div class="note"><h3 class="title">Note</h3><p>
  43. <span class="application">pg_dump</span> and
  44. <span class="application">pg_dumpall</span> do not produce file-system-level
  45. backups and cannot be used as part of a continuous-archiving solution.
  46. Such dumps are <span class="emphasis"><em>logical</em></span> and do not contain enough
  47. information to be used by WAL replay.
  48. </p></div><p>
  49. As with the plain file-system-backup technique, this method can only
  50. support restoration of an entire database cluster, not a subset.
  51. Also, it requires a lot of archival storage: the base backup might be bulky,
  52. and a busy system will generate many megabytes of WAL traffic that
  53. have to be archived. Still, it is the preferred backup technique in
  54. many situations where high reliability is needed.
  55. </p><p>
  56. To recover successfully using continuous archiving (also called
  57. <span class="quote">“<span class="quote">online backup</span>”</span> by many database vendors), you need a continuous
  58. sequence of archived WAL files that extends back at least as far as the
  59. start time of your backup. So to get started, you should set up and test
  60. your procedure for archiving WAL files <span class="emphasis"><em>before</em></span> you take your
  61. first base backup. Accordingly, we first discuss the mechanics of
  62. archiving WAL files.
  63. </p><div class="sect2" id="BACKUP-ARCHIVING-WAL"><div class="titlepage"><div><div><h3 class="title">25.3.1. Setting Up WAL Archiving</h3></div></div></div><p>
  64. In an abstract sense, a running <span class="productname">PostgreSQL</span> system
  65. produces an indefinitely long sequence of WAL records. The system
  66. physically divides this sequence into WAL <em class="firstterm">segment
  67. files</em>, which are normally 16MB apiece (although the segment size
  68. can be altered during <span class="application">initdb</span>). The segment
  69. files are given numeric names that reflect their position in the
  70. abstract WAL sequence. When not using WAL archiving, the system
  71. normally creates just a few segment files and then
  72. <span class="quote">“<span class="quote">recycles</span>”</span> them by renaming no-longer-needed segment files
  73. to higher segment numbers. It's assumed that segment files whose
  74. contents precede the last checkpoint are no longer of
  75. interest and can be recycled.
  76. </p><p>
  77. When archiving WAL data, we need to capture the contents of each segment
  78. file once it is filled, and save that data somewhere before the segment
  79. file is recycled for reuse. Depending on the application and the
  80. available hardware, there could be many different ways of <span class="quote">“<span class="quote">saving
  81. the data somewhere</span>”</span>: we could copy the segment files to an NFS-mounted
  82. directory on another machine, write them onto a tape drive (ensuring that
  83. you have a way of identifying the original name of each file), or batch
  84. them together and burn them onto CDs, or something else entirely. To
  85. provide the database administrator with flexibility,
  86. <span class="productname">PostgreSQL</span> tries not to make any assumptions about how
  87. the archiving will be done. Instead, <span class="productname">PostgreSQL</span> lets
  88. the administrator specify a shell command to be executed to copy a
  89. completed segment file to wherever it needs to go. The command could be
  90. as simple as a <code class="literal">cp</code>, or it could invoke a complex shell
  91. script — it's all up to you.
  92. </p><p>
  93. To enable WAL archiving, set the <a class="xref" href="runtime-config-wal.html#GUC-WAL-LEVEL">wal_level</a>
  94. configuration parameter to <code class="literal">replica</code> or higher,
  95. <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-MODE">archive_mode</a> to <code class="literal">on</code>,
  96. and specify the shell command to use in the <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-COMMAND">archive_command</a> configuration parameter. In practice
  97. these settings will always be placed in the
  98. <code class="filename">postgresql.conf</code> file.
  99. In <code class="varname">archive_command</code>,
  100. <code class="literal">%p</code> is replaced by the path name of the file to
  101. archive, while <code class="literal">%f</code> is replaced by only the file name.
  102. (The path name is relative to the current working directory,
  103. i.e., the cluster's data directory.)
  104. Use <code class="literal">%%</code> if you need to embed an actual <code class="literal">%</code>
  105. character in the command. The simplest useful command is something
  106. like:
  107. </p><pre class="programlisting">
  108. archive_command = 'test ! -f /mnt/server/archivedir/%f &amp;&amp; cp %p /mnt/server/archivedir/%f' # Unix
  109. archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"' # Windows
  110. </pre><p>
  111. which will copy archivable WAL segments to the directory
  112. <code class="filename">/mnt/server/archivedir</code>. (This is an example, not a
  113. recommendation, and might not work on all platforms.) After the
  114. <code class="literal">%p</code> and <code class="literal">%f</code> parameters have been replaced,
  115. the actual command executed might look like this:
  116. </p><pre class="programlisting">
  117. test ! -f /mnt/server/archivedir/00000001000000A900000065 &amp;&amp; cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065
  118. </pre><p>
  119. A similar command will be generated for each new file to be archived.
  120. </p><p>
  121. The archive command will be executed under the ownership of the same
  122. user that the <span class="productname">PostgreSQL</span> server is running as. Since
  123. the series of WAL files being archived contains effectively everything
  124. in your database, you will want to be sure that the archived data is
  125. protected from prying eyes; for example, archive into a directory that
  126. does not have group or world read access.
  127. </p><p>
  128. It is important that the archive command return zero exit status if and
  129. only if it succeeds. Upon getting a zero result,
  130. <span class="productname">PostgreSQL</span> will assume that the file has been
  131. successfully archived, and will remove or recycle it. However, a nonzero
  132. status tells <span class="productname">PostgreSQL</span> that the file was not archived;
  133. it will try again periodically until it succeeds.
  134. </p><p>
  135. The archive command should generally be designed to refuse to overwrite
  136. any pre-existing archive file. This is an important safety feature to
  137. preserve the integrity of your archive in case of administrator error
  138. (such as sending the output of two different servers to the same archive
  139. directory).
  140. </p><p>
  141. It is advisable to test your proposed archive command to ensure that it
  142. indeed does not overwrite an existing file, <span class="emphasis"><em>and that it returns
  143. nonzero status in this case</em></span>.
  144. The example command above for Unix ensures this by including a separate
  145. <code class="command">test</code> step. On some Unix platforms, <code class="command">cp</code> has
  146. switches such as <code class="option">-i</code> that can be used to do the same thing
  147. less verbosely, but you should not rely on these without verifying that
  148. the right exit status is returned. (In particular, GNU <code class="command">cp</code>
  149. will return status zero when <code class="option">-i</code> is used and the target file
  150. already exists, which is <span class="emphasis"><em>not</em></span> the desired behavior.)
  151. </p><p>
  152. While designing your archiving setup, consider what will happen if
  153. the archive command fails repeatedly because some aspect requires
  154. operator intervention or the archive runs out of space. For example, this
  155. could occur if you write to tape without an autochanger; when the tape
  156. fills, nothing further can be archived until the tape is swapped.
  157. You should ensure that any error condition or request to a human operator
  158. is reported appropriately so that the situation can be
  159. resolved reasonably quickly. The <code class="filename">pg_wal/</code> directory will
  160. continue to fill with WAL segment files until the situation is resolved.
  161. (If the file system containing <code class="filename">pg_wal/</code> fills up,
  162. <span class="productname">PostgreSQL</span> will do a PANIC shutdown. No committed
  163. transactions will be lost, but the database will remain offline until
  164. you free some space.)
  165. </p><p>
  166. The speed of the archiving command is unimportant as long as it can keep up
  167. with the average rate at which your server generates WAL data. Normal
  168. operation continues even if the archiving process falls a little behind.
  169. If archiving falls significantly behind, this will increase the amount of
  170. data that would be lost in the event of a disaster. It will also mean that
  171. the <code class="filename">pg_wal/</code> directory will contain large numbers of
  172. not-yet-archived segment files, which could eventually exceed available
  173. disk space. You are advised to monitor the archiving process to ensure that
  174. it is working as you intend.
  175. </p><p>
  176. In writing your archive command, you should assume that the file names to
  177. be archived can be up to 64 characters long and can contain any
  178. combination of ASCII letters, digits, and dots. It is not necessary to
  179. preserve the original relative path (<code class="literal">%p</code>) but it is necessary to
  180. preserve the file name (<code class="literal">%f</code>).
  181. </p><p>
  182. Note that although WAL archiving will allow you to restore any
  183. modifications made to the data in your <span class="productname">PostgreSQL</span> database,
  184. it will not restore changes made to configuration files (that is,
  185. <code class="filename">postgresql.conf</code>, <code class="filename">pg_hba.conf</code> and
  186. <code class="filename">pg_ident.conf</code>), since those are edited manually rather
  187. than through SQL operations.
  188. You might wish to keep the configuration files in a location that will
  189. be backed up by your regular file system backup procedures. See
  190. <a class="xref" href="runtime-config-file-locations.html" title="19.2. File Locations">Section 19.2</a> for how to relocate the
  191. configuration files.
  192. </p><p>
  193. The archive command is only invoked on completed WAL segments. Hence,
  194. if your server generates only little WAL traffic (or has slack periods
  195. where it does so), there could be a long delay between the completion
  196. of a transaction and its safe recording in archive storage. To put
  197. a limit on how old unarchived data can be, you can set
  198. <a class="xref" href="runtime-config-wal.html#GUC-ARCHIVE-TIMEOUT">archive_timeout</a> to force the server to switch
  199. to a new WAL segment file at least that often. Note that archived
  200. files that are archived early due to a forced switch are still the same
  201. length as completely full files. It is therefore unwise to set a very
  202. short <code class="varname">archive_timeout</code> — it will bloat your archive
  203. storage. <code class="varname">archive_timeout</code> settings of a minute or so are
  204. usually reasonable.
  205. </p><p>
  206. Also, you can force a segment switch manually with
  207. <code class="function">pg_switch_wal</code> if you want to ensure that a
  208. just-finished transaction is archived as soon as possible. Other utility
  209. functions related to WAL management are listed in <a class="xref" href="functions-admin.html#FUNCTIONS-ADMIN-BACKUP-TABLE" title="Table 9.84. Backup Control Functions">Table 9.84</a>.
  210. </p><p>
  211. When <code class="varname">wal_level</code> is <code class="literal">minimal</code> some SQL commands
  212. are optimized to avoid WAL logging, as described in <a class="xref" href="populate.html#POPULATE-PITR" title="14.4.7. Disable WAL Archival and Streaming Replication">Section 14.4.7</a>. If archiving or streaming replication were
  213. turned on during execution of one of these statements, WAL would not
  214. contain enough information for archive recovery. (Crash recovery is
  215. unaffected.) For this reason, <code class="varname">wal_level</code> can only be changed at
  216. server start. However, <code class="varname">archive_command</code> can be changed with a
  217. configuration file reload. If you wish to temporarily stop archiving,
  218. one way to do it is to set <code class="varname">archive_command</code> to the empty
  219. string (<code class="literal">''</code>).
  220. This will cause WAL files to accumulate in <code class="filename">pg_wal/</code> until a
  221. working <code class="varname">archive_command</code> is re-established.
  222. </p></div><div class="sect2" id="BACKUP-BASE-BACKUP"><div class="titlepage"><div><div><h3 class="title">25.3.2. Making a Base Backup</h3></div></div></div><p>
  223. The easiest way to perform a base backup is to use the
  224. <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle">pg_basebackup</span></a> tool. It can create
  225. a base backup either as regular files or as a tar archive. If more
  226. flexibility than <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle">pg_basebackup</span></a> can provide is
  227. required, you can also make a base backup using the low level API
  228. (see <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP" title="25.3.3. Making a Base Backup Using the Low Level API">Section 25.3.3</a>).
  229. </p><p>
  230. It is not necessary to be concerned about the amount of time it takes
  231. to make a base backup. However, if you normally run the
  232. server with <code class="varname">full_page_writes</code> disabled, you might notice a drop
  233. in performance while the backup runs since <code class="varname">full_page_writes</code> is
  234. effectively forced on during backup mode.
  235. </p><p>
  236. To make use of the backup, you will need to keep all the WAL
  237. segment files generated during and after the file system backup.
  238. To aid you in doing this, the base backup process
  239. creates a <em class="firstterm">backup history file</em> that is immediately
  240. stored into the WAL archive area. This file is named after the first
  241. WAL segment file that you need for the file system backup.
  242. For example, if the starting WAL file is
  243. <code class="literal">0000000100001234000055CD</code> the backup history file will be
  244. named something like
  245. <code class="literal">0000000100001234000055CD.007C9330.backup</code>. (The second
  246. part of the file name stands for an exact position within the WAL
  247. file, and can ordinarily be ignored.) Once you have safely archived
  248. the file system backup and the WAL segment files used during the
  249. backup (as specified in the backup history file), all archived WAL
  250. segments with names numerically less are no longer needed to recover
  251. the file system backup and can be deleted. However, you should
  252. consider keeping several backup sets to be absolutely certain that
  253. you can recover your data.
  254. </p><p>
  255. The backup history file is just a small text file. It contains the
  256. label string you gave to <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle">pg_basebackup</span></a>, as well as
  257. the starting and ending times and WAL segments of the backup.
  258. If you used the label to identify the associated dump file,
  259. then the archived history file is enough to tell you which dump file to
  260. restore.
  261. </p><p>
  262. Since you have to keep around all the archived WAL files back to your
  263. last base backup, the interval between base backups should usually be
  264. chosen based on how much storage you want to expend on archived WAL
  265. files. You should also consider how long you are prepared to spend
  266. recovering, if recovery should be necessary — the system will have to
  267. replay all those WAL segments, and that could take awhile if it has
  268. been a long time since the last base backup.
  269. </p></div><div class="sect2" id="BACKUP-LOWLEVEL-BASE-BACKUP"><div class="titlepage"><div><div><h3 class="title">25.3.3. Making a Base Backup Using the Low Level API</h3></div></div></div><p>
  270. The procedure for making a base backup using the low level
  271. APIs contains a few more steps than
  272. the <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle">pg_basebackup</span></a> method, but is relatively
  273. simple. It is very important that these steps are executed in
  274. sequence, and that the success of a step is verified before
  275. proceeding to the next step.
  276. </p><p>
  277. Low level base backups can be made in a non-exclusive or an exclusive
  278. way. The non-exclusive method is recommended and the exclusive one is
  279. deprecated and will eventually be removed.
  280. </p><div class="sect3" id="BACKUP-LOWLEVEL-BASE-BACKUP-NONEXCLUSIVE"><div class="titlepage"><div><div><h4 class="title">25.3.3.1. Making a Non-Exclusive Low-Level Backup</h4></div></div></div><p>
  281. A non-exclusive low level backup is one that allows other
  282. concurrent backups to be running (both those started using
  283. the same backup API and those started using
  284. <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle">pg_basebackup</span></a>).
  285. </p><p>
  286. </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
  287. Ensure that WAL archiving is enabled and working.
  288. </p></li><li class="listitem"><p>
  289. Connect to the server (it does not matter which database) as a user with
  290. rights to run pg_start_backup (superuser, or a user who has been granted
  291. EXECUTE on the function) and issue the command:
  292. </p><pre class="programlisting">
  293. SELECT pg_start_backup('label', false, false);
  294. </pre><p>
  295. where <code class="literal">label</code> is any string you want to use to uniquely
  296. identify this backup operation. The connection
  297. calling <code class="function">pg_start_backup</code> must be maintained until the end of
  298. the backup, or the backup will be automatically aborted.
  299. </p><p>
  300. By default, <code class="function">pg_start_backup</code> can take a long time to finish.
  301. This is because it performs a checkpoint, and the I/O
  302. required for the checkpoint will be spread out over a significant
  303. period of time, by default half your inter-checkpoint interval
  304. (see the configuration parameter
  305. <a class="xref" href="runtime-config-wal.html#GUC-CHECKPOINT-COMPLETION-TARGET">checkpoint_completion_target</a>). This is
  306. usually what you want, because it minimizes the impact on query
  307. processing. If you want to start the backup as soon as
  308. possible, change the second parameter to <code class="literal">true</code>, which will
  309. issue an immediate checkpoint using as much I/O as available.
  310. </p><p>
  311. The third parameter being <code class="literal">false</code> tells
  312. <code class="function">pg_start_backup</code> to initiate a non-exclusive base backup.
  313. </p></li><li class="listitem"><p>
  314. Perform the backup, using any convenient file-system-backup tool
  315. such as <span class="application">tar</span> or <span class="application">cpio</span> (not
  316. <span class="application">pg_dump</span> or
  317. <span class="application">pg_dumpall</span>). It is neither
  318. necessary nor desirable to stop normal operation of the database
  319. while you do this. See
  320. <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP-DATA" title="25.3.3.3. Backing Up the Data Directory">Section 25.3.3.3</a> for things to
  321. consider during this backup.
  322. </p></li><li class="listitem"><p>
  323. In the same connection as before, issue the command:
  324. </p><pre class="programlisting">
  325. SELECT * FROM pg_stop_backup(false, true);
  326. </pre><p>
  327. This terminates backup mode. On a primary, it also performs an automatic
  328. switch to the next WAL segment. On a standby, it is not possible to
  329. automatically switch WAL segments, so you may wish to run
  330. <code class="function">pg_switch_wal</code> on the primary to perform a manual
  331. switch. The reason for the switch is to arrange for
  332. the last WAL segment file written during the backup interval to be
  333. ready to archive.
  334. </p><p>
  335. The <code class="function">pg_stop_backup</code> will return one row with three
  336. values. The second of these fields should be written to a file named
  337. <code class="filename">backup_label</code> in the root directory of the backup. The
  338. third field should be written to a file named
  339. <code class="filename">tablespace_map</code> unless the field is empty. These files are
  340. vital to the backup working, and must be written without modification.
  341. </p></li><li class="listitem"><p>
  342. Once the WAL segment files active during the backup are archived, you are
  343. done. The file identified by <code class="function">pg_stop_backup</code>'s first return
  344. value is the last segment that is required to form a complete set of
  345. backup files. On a primary, if <code class="varname">archive_mode</code> is enabled and the
  346. <code class="literal">wait_for_archive</code> parameter is <code class="literal">true</code>,
  347. <code class="function">pg_stop_backup</code> does not return until the last segment has
  348. been archived.
  349. On a standby, <code class="varname">archive_mode</code> must be <code class="literal">always</code> in order
  350. for <code class="function">pg_stop_backup</code> to wait.
  351. Archiving of these files happens automatically since you have
  352. already configured <code class="varname">archive_command</code>. In most cases this
  353. happens quickly, but you are advised to monitor your archive
  354. system to ensure there are no delays.
  355. If the archive process has fallen behind
  356. because of failures of the archive command, it will keep retrying
  357. until the archive succeeds and the backup is complete.
  358. If you wish to place a time limit on the execution of
  359. <code class="function">pg_stop_backup</code>, set an appropriate
  360. <code class="varname">statement_timeout</code> value, but make note that if
  361. <code class="function">pg_stop_backup</code> terminates because of this your backup
  362. may not be valid.
  363. </p><p>
  364. If the backup process monitors and ensures that all WAL segment files
  365. required for the backup are successfully archived then the
  366. <code class="literal">wait_for_archive</code> parameter (which defaults to true) can be set
  367. to false to have
  368. <code class="function">pg_stop_backup</code> return as soon as the stop backup record is
  369. written to the WAL. By default, <code class="function">pg_stop_backup</code> will wait
  370. until all WAL has been archived, which can take some time. This option
  371. must be used with caution: if WAL archiving is not monitored correctly
  372. then the backup might not include all of the WAL files and will
  373. therefore be incomplete and not able to be restored.
  374. </p></li></ol></div><p>
  375. </p></div><div class="sect3" id="BACKUP-LOWLEVEL-BASE-BACKUP-EXCLUSIVE"><div class="titlepage"><div><div><h4 class="title">25.3.3.2. Making an Exclusive Low-Level Backup</h4></div></div></div><div class="note"><h3 class="title">Note</h3><p>
  376. The exclusive backup method is deprecated and should be avoided.
  377. Prior to <span class="productname">PostgreSQL</span> 9.6, this was the only
  378. low-level method available, but it is now recommended that all users
  379. upgrade their scripts to use non-exclusive backups.
  380. </p></div><p>
  381. The process for an exclusive backup is mostly the same as for a
  382. non-exclusive one, but it differs in a few key steps. This type of
  383. backup can only be taken on a primary and does not allow concurrent
  384. backups. Moreover, because it creates a backup label file, as
  385. described below, it can block automatic restart of the master server
  386. after a crash. On the other hand, the erroneous removal of this
  387. file from a backup or standby is a common mistake, which can result
  388. in serious data corruption. If it is necessary to use this method,
  389. the following steps may be used.
  390. </p><p>
  391. </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
  392. Ensure that WAL archiving is enabled and working.
  393. </p></li><li class="listitem"><p>
  394. Connect to the server (it does not matter which database) as a user with
  395. rights to run pg_start_backup (superuser, or a user who has been granted
  396. EXECUTE on the function) and issue the command:
  397. </p><pre class="programlisting">
  398. SELECT pg_start_backup('label');
  399. </pre><p>
  400. where <code class="literal">label</code> is any string you want to use to uniquely
  401. identify this backup operation.
  402. <code class="function">pg_start_backup</code> creates a <em class="firstterm">backup label</em> file,
  403. called <code class="filename">backup_label</code>, in the cluster directory with
  404. information about your backup, including the start time and label string.
  405. The function also creates a <em class="firstterm">tablespace map</em> file,
  406. called <code class="filename">tablespace_map</code>, in the cluster directory with
  407. information about tablespace symbolic links in <code class="filename">pg_tblspc/</code> if
  408. one or more such link is present. Both files are critical to the
  409. integrity of the backup, should you need to restore from it.
  410. </p><p>
  411. By default, <code class="function">pg_start_backup</code> can take a long time to finish.
  412. This is because it performs a checkpoint, and the I/O
  413. required for the checkpoint will be spread out over a significant
  414. period of time, by default half your inter-checkpoint interval
  415. (see the configuration parameter
  416. <a class="xref" href="runtime-config-wal.html#GUC-CHECKPOINT-COMPLETION-TARGET">checkpoint_completion_target</a>). This is
  417. usually what you want, because it minimizes the impact on query
  418. processing. If you want to start the backup as soon as
  419. possible, use:
  420. </p><pre class="programlisting">
  421. SELECT pg_start_backup('label', true);
  422. </pre><p>
  423. This forces the checkpoint to be done as quickly as possible.
  424. </p></li><li class="listitem"><p>
  425. Perform the backup, using any convenient file-system-backup tool
  426. such as <span class="application">tar</span> or <span class="application">cpio</span> (not
  427. <span class="application">pg_dump</span> or
  428. <span class="application">pg_dumpall</span>). It is neither
  429. necessary nor desirable to stop normal operation of the database
  430. while you do this. See
  431. <a class="xref" href="continuous-archiving.html#BACKUP-LOWLEVEL-BASE-BACKUP-DATA" title="25.3.3.3. Backing Up the Data Directory">Section 25.3.3.3</a> for things to
  432. consider during this backup.
  433. </p><p>
  434. As noted above, if the server crashes during the backup it may not be
  435. possible to restart until the <code class="filename">backup_label</code> file has
  436. been manually deleted from the <code class="envar">PGDATA</code> directory. Note
  437. that it is very important to never remove the
  438. <code class="filename">backup_label</code> file when restoring a backup, because
  439. this will result in corruption. Confusion about when it is appropriate
  440. to remove this file is a common cause of data corruption when using this
  441. method; be very certain that you remove the file only on an existing
  442. master and never when building a standby or restoring a backup, even if
  443. you are building a standby that will subsequently be promoted to a new
  444. master.
  445. </p></li><li class="listitem"><p>
  446. Again connect to the database as a user with rights to run
  447. pg_stop_backup (superuser, or a user who has been granted EXECUTE on
  448. the function), and issue the command:
  449. </p><pre class="programlisting">
  450. SELECT pg_stop_backup();
  451. </pre><p>
  452. This function terminates backup mode and
  453. performs an automatic switch to the next WAL segment. The reason for the
  454. switch is to arrange for the last WAL segment written during the backup
  455. interval to be ready to archive.
  456. </p></li><li class="listitem"><p>
  457. Once the WAL segment files active during the backup are archived, you are
  458. done. The file identified by <code class="function">pg_stop_backup</code>'s result is
  459. the last segment that is required to form a complete set of backup files.
  460. If <code class="varname">archive_mode</code> is enabled,
  461. <code class="function">pg_stop_backup</code> does not return until the last segment has
  462. been archived.
  463. Archiving of these files happens automatically since you have
  464. already configured <code class="varname">archive_command</code>. In most cases this
  465. happens quickly, but you are advised to monitor your archive
  466. system to ensure there are no delays.
  467. If the archive process has fallen behind
  468. because of failures of the archive command, it will keep retrying
  469. until the archive succeeds and the backup is complete.
  470. </p><p>
  471. When using exclusive backup mode, it is absolutely imperative to ensure
  472. that <code class="function">pg_stop_backup</code> completes successfully at the
  473. end of the backup. Even if the backup itself fails, for example due to
  474. lack of disk space, failure to call <code class="function">pg_stop_backup</code>
  475. will leave the server in backup mode indefinitely, causing future backups
  476. to fail and increasing the risk of a restart failure during the time that
  477. <code class="filename">backup_label</code> exists.
  478. </p></li></ol></div><p>
  479. </p></div><div class="sect3" id="BACKUP-LOWLEVEL-BASE-BACKUP-DATA"><div class="titlepage"><div><div><h4 class="title">25.3.3.3. Backing Up the Data Directory</h4></div></div></div><p>
  480. Some file system backup tools emit warnings or errors
  481. if the files they are trying to copy change while the copy proceeds.
  482. When taking a base backup of an active database, this situation is normal
  483. and not an error. However, you need to ensure that you can distinguish
  484. complaints of this sort from real errors. For example, some versions
  485. of <span class="application">rsync</span> return a separate exit code for
  486. <span class="quote">“<span class="quote">vanished source files</span>”</span>, and you can write a driver script to
  487. accept this exit code as a non-error case. Also, some versions of
  488. GNU <span class="application">tar</span> return an error code indistinguishable from
  489. a fatal error if a file was truncated while <span class="application">tar</span> was
  490. copying it. Fortunately, GNU <span class="application">tar</span> versions 1.16 and
  491. later exit with 1 if a file was changed during the backup,
  492. and 2 for other errors. With GNU <span class="application">tar</span> version 1.23 and
  493. later, you can use the warning options <code class="literal">--warning=no-file-changed
  494. --warning=no-file-removed</code> to hide the related warning messages.
  495. </p><p>
  496. Be certain that your backup includes all of the files under
  497. the database cluster directory (e.g., <code class="filename">/usr/local/pgsql/data</code>).
  498. If you are using tablespaces that do not reside underneath this directory,
  499. be careful to include them as well (and be sure that your backup
  500. archives symbolic links as links, otherwise the restore will corrupt
  501. your tablespaces).
  502. </p><p>
  503. You should, however, omit from the backup the files within the
  504. cluster's <code class="filename">pg_wal/</code> subdirectory. This
  505. slight adjustment is worthwhile because it reduces the risk
  506. of mistakes when restoring. This is easy to arrange if
  507. <code class="filename">pg_wal/</code> is a symbolic link pointing to someplace outside
  508. the cluster directory, which is a common setup anyway for performance
  509. reasons. You might also want to exclude <code class="filename">postmaster.pid</code>
  510. and <code class="filename">postmaster.opts</code>, which record information
  511. about the running <span class="application">postmaster</span>, not about the
  512. <span class="application">postmaster</span> which will eventually use this backup.
  513. (These files can confuse <span class="application">pg_ctl</span>.)
  514. </p><p>
  515. It is often a good idea to also omit from the backup the files
  516. within the cluster's <code class="filename">pg_replslot/</code> directory, so that
  517. replication slots that exist on the master do not become part of the
  518. backup. Otherwise, the subsequent use of the backup to create a standby
  519. may result in indefinite retention of WAL files on the standby, and
  520. possibly bloat on the master if hot standby feedback is enabled, because
  521. the clients that are using those replication slots will still be connecting
  522. to and updating the slots on the master, not the standby. Even if the
  523. backup is only intended for use in creating a new master, copying the
  524. replication slots isn't expected to be particularly useful, since the
  525. contents of those slots will likely be badly out of date by the time
  526. the new master comes on line.
  527. </p><p>
  528. The contents of the directories <code class="filename">pg_dynshmem/</code>,
  529. <code class="filename">pg_notify/</code>, <code class="filename">pg_serial/</code>,
  530. <code class="filename">pg_snapshots/</code>, <code class="filename">pg_stat_tmp/</code>,
  531. and <code class="filename">pg_subtrans/</code> (but not the directories themselves) can be
  532. omitted from the backup as they will be initialized on postmaster startup.
  533. If <a class="xref" href="runtime-config-statistics.html#GUC-STATS-TEMP-DIRECTORY">stats_temp_directory</a> is set and is under the data
  534. directory then the contents of that directory can also be omitted.
  535. </p><p>
  536. Any file or directory beginning with <code class="filename">pgsql_tmp</code> can be
  537. omitted from the backup. These files are removed on postmaster start and
  538. the directories will be recreated as needed.
  539. </p><p>
  540. <code class="filename">pg_internal.init</code> files can be omitted from the
  541. backup whenever a file of that name is found. These files contain
  542. relation cache data that is always rebuilt when recovering.
  543. </p><p>
  544. The backup label
  545. file includes the label string you gave to <code class="function">pg_start_backup</code>,
  546. as well as the time at which <code class="function">pg_start_backup</code> was run, and
  547. the name of the starting WAL file. In case of confusion it is therefore
  548. possible to look inside a backup file and determine exactly which
  549. backup session the dump file came from. The tablespace map file includes
  550. the symbolic link names as they exist in the directory
  551. <code class="filename">pg_tblspc/</code> and the full path of each symbolic link.
  552. These files are not merely for your information; their presence and
  553. contents are critical to the proper operation of the system's recovery
  554. process.
  555. </p><p>
  556. It is also possible to make a backup while the server is
  557. stopped. In this case, you obviously cannot use
  558. <code class="function">pg_start_backup</code> or <code class="function">pg_stop_backup</code>, and
  559. you will therefore be left to your own devices to keep track of which
  560. backup is which and how far back the associated WAL files go.
  561. It is generally better to follow the continuous archiving procedure above.
  562. </p></div></div><div class="sect2" id="BACKUP-PITR-RECOVERY"><div class="titlepage"><div><div><h3 class="title">25.3.4. Recovering Using a Continuous Archive Backup</h3></div></div></div><p>
  563. Okay, the worst has happened and you need to recover from your backup.
  564. Here is the procedure:
  565. </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
  566. Stop the server, if it's running.
  567. </p></li><li class="listitem"><p>
  568. If you have the space to do so,
  569. copy the whole cluster data directory and any tablespaces to a temporary
  570. location in case you need them later. Note that this precaution will
  571. require that you have enough free space on your system to hold two
  572. copies of your existing database. If you do not have enough space,
  573. you should at least save the contents of the cluster's <code class="filename">pg_wal</code>
  574. subdirectory, as it might contain logs which
  575. were not archived before the system went down.
  576. </p></li><li class="listitem"><p>
  577. Remove all existing files and subdirectories under the cluster data
  578. directory and under the root directories of any tablespaces you are using.
  579. </p></li><li class="listitem"><p>
  580. Restore the database files from your file system backup. Be sure that they
  581. are restored with the right ownership (the database system user, not
  582. <code class="literal">root</code>!) and with the right permissions. If you are using
  583. tablespaces,
  584. you should verify that the symbolic links in <code class="filename">pg_tblspc/</code>
  585. were correctly restored.
  586. </p></li><li class="listitem"><p>
  587. Remove any files present in <code class="filename">pg_wal/</code>; these came from the
  588. file system backup and are therefore probably obsolete rather than current.
  589. If you didn't archive <code class="filename">pg_wal/</code> at all, then recreate
  590. it with proper permissions,
  591. being careful to ensure that you re-establish it as a symbolic link
  592. if you had it set up that way before.
  593. </p></li><li class="listitem"><p>
  594. If you have unarchived WAL segment files that you saved in step 2,
  595. copy them into <code class="filename">pg_wal/</code>. (It is best to copy them,
  596. not move them, so you still have the unmodified files if a
  597. problem occurs and you have to start over.)
  598. </p></li><li class="listitem"><p>
  599. Set recovery configuration settings in
  600. <code class="filename">postgresql.conf</code> (see <a class="xref" href="runtime-config-wal.html#RUNTIME-CONFIG-WAL-ARCHIVE-RECOVERY" title="19.5.4. Archive Recovery">Section 19.5.4</a>) and create a file
  601. <code class="filename">recovery.signal</code> in the cluster
  602. data directory. You might
  603. also want to temporarily modify <code class="filename">pg_hba.conf</code> to prevent
  604. ordinary users from connecting until you are sure the recovery was successful.
  605. </p></li><li class="listitem"><p>
  606. Start the server. The server will go into recovery mode and
  607. proceed to read through the archived WAL files it needs. Should the
  608. recovery be terminated because of an external error, the server can
  609. simply be restarted and it will continue recovery. Upon completion
  610. of the recovery process, the server will remove
  611. <code class="filename">recovery.signal</code> (to prevent
  612. accidentally re-entering recovery mode later) and then
  613. commence normal database operations.
  614. </p></li><li class="listitem"><p>
  615. Inspect the contents of the database to ensure you have recovered to
  616. the desired state. If not, return to step 1. If all is well,
  617. allow your users to connect by restoring <code class="filename">pg_hba.conf</code> to normal.
  618. </p></li></ol></div><p>
  619. </p><p>
  620. The key part of all this is to set up a recovery configuration that
  621. describes how you want to recover and how far the recovery should
  622. run. The one thing that you absolutely must specify is the <code class="varname">restore_command</code>,
  623. which tells <span class="productname">PostgreSQL</span> how to retrieve archived
  624. WAL file segments. Like the <code class="varname">archive_command</code>, this is
  625. a shell command string. It can contain <code class="literal">%f</code>, which is
  626. replaced by the name of the desired log file, and <code class="literal">%p</code>,
  627. which is replaced by the path name to copy the log file to.
  628. (The path name is relative to the current working directory,
  629. i.e., the cluster's data directory.)
  630. Write <code class="literal">%%</code> if you need to embed an actual <code class="literal">%</code>
  631. character in the command. The simplest useful command is
  632. something like:
  633. </p><pre class="programlisting">
  634. restore_command = 'cp /mnt/server/archivedir/%f %p'
  635. </pre><p>
  636. which will copy previously archived WAL segments from the directory
  637. <code class="filename">/mnt/server/archivedir</code>. Of course, you can use something
  638. much more complicated, perhaps even a shell script that requests the
  639. operator to mount an appropriate tape.
  640. </p><p>
  641. It is important that the command return nonzero exit status on failure.
  642. The command <span class="emphasis"><em>will</em></span> be called requesting files that are not
  643. present in the archive; it must return nonzero when so asked. This is not
  644. an error condition. An exception is that if the command was terminated by
  645. a signal (other than <span class="systemitem">SIGTERM</span>, which is used as
  646. part of a database server shutdown) or an error by the shell (such as
  647. command not found), then recovery will abort and the server will not start
  648. up.
  649. </p><p>
  650. Not all of the requested files will be WAL segment
  651. files; you should also expect requests for files with a suffix of
  652. <code class="literal">.history</code>. Also be aware that
  653. the base name of the <code class="literal">%p</code> path will be different from
  654. <code class="literal">%f</code>; do not expect them to be interchangeable.
  655. </p><p>
  656. WAL segments that cannot be found in the archive will be sought in
  657. <code class="filename">pg_wal/</code>; this allows use of recent un-archived segments.
  658. However, segments that are available from the archive will be used in
  659. preference to files in <code class="filename">pg_wal/</code>.
  660. </p><p>
  661. Normally, recovery will proceed through all available WAL segments,
  662. thereby restoring the database to the current point in time (or as
  663. close as possible given the available WAL segments). Therefore, a normal
  664. recovery will end with a <span class="quote">“<span class="quote">file not found</span>”</span> message, the exact text
  665. of the error message depending upon your choice of
  666. <code class="varname">restore_command</code>. You may also see an error message
  667. at the start of recovery for a file named something like
  668. <code class="filename">00000001.history</code>. This is also normal and does not
  669. indicate a problem in simple recovery situations; see
  670. <a class="xref" href="continuous-archiving.html#BACKUP-TIMELINES" title="25.3.5. Timelines">Section 25.3.5</a> for discussion.
  671. </p><p>
  672. If you want to recover to some previous point in time (say, right before
  673. the junior DBA dropped your main transaction table), just specify the
  674. required <a class="link" href="runtime-config-wal.html#RUNTIME-CONFIG-WAL-RECOVERY-TARGET" title="19.5.5. Recovery Target">stopping point</a>. You can specify
  675. the stop point, known as the <span class="quote">“<span class="quote">recovery target</span>”</span>, either by
  676. date/time, named restore point or by completion of a specific transaction
  677. ID. As of this writing only the date/time and named restore point options
  678. are very usable, since there are no tools to help you identify with any
  679. accuracy which transaction ID to use.
  680. </p><div class="note"><h3 class="title">Note</h3><p>
  681. The stop point must be after the ending time of the base backup, i.e.,
  682. the end time of <code class="function">pg_stop_backup</code>. You cannot use a base backup
  683. to recover to a time when that backup was in progress. (To
  684. recover to such a time, you must go back to your previous base backup
  685. and roll forward from there.)
  686. </p></div><p>
  687. If recovery finds corrupted WAL data, recovery will
  688. halt at that point and the server will not start. In such a case the
  689. recovery process could be re-run from the beginning, specifying a
  690. <span class="quote">“<span class="quote">recovery target</span>”</span> before the point of corruption so that recovery
  691. can complete normally.
  692. If recovery fails for an external reason, such as a system crash or
  693. if the WAL archive has become inaccessible, then the recovery can simply
  694. be restarted and it will restart almost from where it failed.
  695. Recovery restart works much like checkpointing in normal operation:
  696. the server periodically forces all its state to disk, and then updates
  697. the <code class="filename">pg_control</code> file to indicate that the already-processed
  698. WAL data need not be scanned again.
  699. </p></div><div class="sect2" id="BACKUP-TIMELINES"><div class="titlepage"><div><div><h3 class="title">25.3.5. Timelines</h3></div></div></div><a id="id-1.6.12.7.13.2" class="indexterm"></a><p>
  700. The ability to restore the database to a previous point in time creates
  701. some complexities that are akin to science-fiction stories about time
  702. travel and parallel universes. For example, in the original history of the database,
  703. suppose you dropped a critical table at 5:15PM on Tuesday evening, but
  704. didn't realize your mistake until Wednesday noon.
  705. Unfazed, you get out your backup, restore to the point-in-time 5:14PM
  706. Tuesday evening, and are up and running. In <span class="emphasis"><em>this</em></span> history of
  707. the database universe, you never dropped the table. But suppose
  708. you later realize this wasn't such a great idea, and would like
  709. to return to sometime Wednesday morning in the original history.
  710. You won't be able
  711. to if, while your database was up-and-running, it overwrote some of the
  712. WAL segment files that led up to the time you now wish you
  713. could get back to. Thus, to avoid this, you need to distinguish the series of
  714. WAL records generated after you've done a point-in-time recovery from
  715. those that were generated in the original database history.
  716. </p><p>
  717. To deal with this problem, <span class="productname">PostgreSQL</span> has a notion
  718. of <em class="firstterm">timelines</em>. Whenever an archive recovery completes,
  719. a new timeline is created to identify the series of WAL records
  720. generated after that recovery. The timeline
  721. ID number is part of WAL segment file names so a new timeline does
  722. not overwrite the WAL data generated by previous timelines. It is
  723. in fact possible to archive many different timelines. While that might
  724. seem like a useless feature, it's often a lifesaver. Consider the
  725. situation where you aren't quite sure what point-in-time to recover to,
  726. and so have to do several point-in-time recoveries by trial and error
  727. until you find the best place to branch off from the old history. Without
  728. timelines this process would soon generate an unmanageable mess. With
  729. timelines, you can recover to <span class="emphasis"><em>any</em></span> prior state, including
  730. states in timeline branches that you abandoned earlier.
  731. </p><p>
  732. Every time a new timeline is created, <span class="productname">PostgreSQL</span> creates
  733. a <span class="quote">“<span class="quote">timeline history</span>”</span> file that shows which timeline it branched
  734. off from and when. These history files are necessary to allow the system
  735. to pick the right WAL segment files when recovering from an archive that
  736. contains multiple timelines. Therefore, they are archived into the WAL
  737. archive area just like WAL segment files. The history files are just
  738. small text files, so it's cheap and appropriate to keep them around
  739. indefinitely (unlike the segment files which are large). You can, if
  740. you like, add comments to a history file to record your own notes about
  741. how and why this particular timeline was created. Such comments will be
  742. especially valuable when you have a thicket of different timelines as
  743. a result of experimentation.
  744. </p><p>
  745. The default behavior of recovery is to recover along the same timeline
  746. that was current when the base backup was taken. If you wish to recover
  747. into some child timeline (that is, you want to return to some state that
  748. was itself generated after a recovery attempt), you need to specify the
  749. target timeline ID in <a class="xref" href="runtime-config-wal.html#GUC-RECOVERY-TARGET-TIMELINE">recovery_target_timeline</a>. You cannot recover into
  750. timelines that branched off earlier than the base backup.
  751. </p></div><div class="sect2" id="BACKUP-TIPS"><div class="titlepage"><div><div><h3 class="title">25.3.6. Tips and Examples</h3></div></div></div><p>
  752. Some tips for configuring continuous archiving are given here.
  753. </p><div class="sect3" id="BACKUP-STANDALONE"><div class="titlepage"><div><div><h4 class="title">25.3.6.1. Standalone Hot Backups</h4></div></div></div><p>
  754. It is possible to use <span class="productname">PostgreSQL</span>'s backup facilities to
  755. produce standalone hot backups. These are backups that cannot be used
  756. for point-in-time recovery, yet are typically much faster to backup and
  757. restore than <span class="application">pg_dump</span> dumps. (They are also much larger
  758. than <span class="application">pg_dump</span> dumps, so in some cases the speed advantage
  759. might be negated.)
  760. </p><p>
  761. As with base backups, the easiest way to produce a standalone
  762. hot backup is to use the <a class="xref" href="app-pgbasebackup.html" title="pg_basebackup"><span class="refentrytitle">pg_basebackup</span></a>
  763. tool. If you include the <code class="literal">-X</code> parameter when calling
  764. it, all the write-ahead log required to use the backup will be
  765. included in the backup automatically, and no special action is
  766. required to restore the backup.
  767. </p><p>
  768. If more flexibility in copying the backup files is needed, a lower
  769. level process can be used for standalone hot backups as well.
  770. To prepare for low level standalone hot backups, make sure
  771. <code class="varname">wal_level</code> is set to
  772. <code class="literal">replica</code> or higher, <code class="varname">archive_mode</code> to
  773. <code class="literal">on</code>, and set up an <code class="varname">archive_command</code> that performs
  774. archiving only when a <span class="emphasis"><em>switch file</em></span> exists. For example:
  775. </p><pre class="programlisting">
  776. archive_command = 'test ! -f /var/lib/pgsql/backup_in_progress || (test ! -f /var/lib/pgsql/archive/%f &amp;&amp; cp %p /var/lib/pgsql/archive/%f)'
  777. </pre><p>
  778. This command will perform archiving when
  779. <code class="filename">/var/lib/pgsql/backup_in_progress</code> exists, and otherwise
  780. silently return zero exit status (allowing <span class="productname">PostgreSQL</span>
  781. to recycle the unwanted WAL file).
  782. </p><p>
  783. With this preparation, a backup can be taken using a script like the
  784. following:
  785. </p><pre class="programlisting">
  786. touch /var/lib/pgsql/backup_in_progress
  787. psql -c "select pg_start_backup('hot_backup');"
  788. tar -cf /var/lib/pgsql/backup.tar /var/lib/pgsql/data/
  789. psql -c "select pg_stop_backup();"
  790. rm /var/lib/pgsql/backup_in_progress
  791. tar -rf /var/lib/pgsql/backup.tar /var/lib/pgsql/archive/
  792. </pre><p>
  793. The switch file <code class="filename">/var/lib/pgsql/backup_in_progress</code> is
  794. created first, enabling archiving of completed WAL files to occur.
  795. After the backup the switch file is removed. Archived WAL files are
  796. then added to the backup so that both base backup and all required
  797. WAL files are part of the same <span class="application">tar</span> file.
  798. Please remember to add error handling to your backup scripts.
  799. </p></div><div class="sect3" id="COMPRESSED-ARCHIVE-LOGS"><div class="titlepage"><div><div><h4 class="title">25.3.6.2. Compressed Archive Logs</h4></div></div></div><p>
  800. If archive storage size is a concern, you can use
  801. <span class="application">gzip</span> to compress the archive files:
  802. </p><pre class="programlisting">
  803. archive_command = 'gzip &lt; %p &gt; /var/lib/pgsql/archive/%f'
  804. </pre><p>
  805. You will then need to use <span class="application">gunzip</span> during recovery:
  806. </p><pre class="programlisting">
  807. restore_command = 'gunzip &lt; /mnt/server/archivedir/%f &gt; %p'
  808. </pre><p>
  809. </p></div><div class="sect3" id="BACKUP-SCRIPTS"><div class="titlepage"><div><div><h4 class="title">25.3.6.3. <code class="varname">archive_command</code> Scripts</h4></div></div></div><p>
  810. Many people choose to use scripts to define their
  811. <code class="varname">archive_command</code>, so that their
  812. <code class="filename">postgresql.conf</code> entry looks very simple:
  813. </p><pre class="programlisting">
  814. archive_command = 'local_backup_script.sh "%p" "%f"'
  815. </pre><p>
  816. Using a separate script file is advisable any time you want to use
  817. more than a single command in the archiving process.
  818. This allows all complexity to be managed within the script, which
  819. can be written in a popular scripting language such as
  820. <span class="application">bash</span> or <span class="application">perl</span>.
  821. </p><p>
  822. Examples of requirements that might be solved within a script include:
  823. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  824. Copying data to secure off-site data storage
  825. </p></li><li class="listitem"><p>
  826. Batching WAL files so that they are transferred every three hours,
  827. rather than one at a time
  828. </p></li><li class="listitem"><p>
  829. Interfacing with other backup and recovery software
  830. </p></li><li class="listitem"><p>
  831. Interfacing with monitoring software to report errors
  832. </p></li></ul></div><p>
  833. </p><div class="tip"><h3 class="title">Tip</h3><p>
  834. When using an <code class="varname">archive_command</code> script, it's desirable
  835. to enable <a class="xref" href="runtime-config-logging.html#GUC-LOGGING-COLLECTOR">logging_collector</a>.
  836. Any messages written to <span class="systemitem">stderr</span> from the script will then
  837. appear in the database server log, allowing complex configurations to
  838. be diagnosed easily if they fail.
  839. </p></div></div></div><div class="sect2" id="CONTINUOUS-ARCHIVING-CAVEATS"><div class="titlepage"><div><div><h3 class="title">25.3.7. Caveats</h3></div></div></div><p>
  840. At this writing, there are several limitations of the continuous archiving
  841. technique. These will probably be fixed in future releases:
  842. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  843. If a <a class="xref" href="sql-createdatabase.html" title="CREATE DATABASE"><span class="refentrytitle">CREATE DATABASE</span></a>
  844. command is executed while a base backup is being taken, and then
  845. the template database that the <code class="command">CREATE DATABASE</code> copied
  846. is modified while the base backup is still in progress, it is
  847. possible that recovery will cause those modifications to be
  848. propagated into the created database as well. This is of course
  849. undesirable. To avoid this risk, it is best not to modify any
  850. template databases while taking a base backup.
  851. </p></li><li class="listitem"><p>
  852. <a class="xref" href="sql-createtablespace.html" title="CREATE TABLESPACE"><span class="refentrytitle">CREATE TABLESPACE</span></a>
  853. commands are WAL-logged with the literal absolute path, and will
  854. therefore be replayed as tablespace creations with the same
  855. absolute path. This might be undesirable if the log is being
  856. replayed on a different machine. It can be dangerous even if the
  857. log is being replayed on the same machine, but into a new data
  858. directory: the replay will still overwrite the contents of the
  859. original tablespace. To avoid potential gotchas of this sort,
  860. the best practice is to take a new base backup after creating or
  861. dropping tablespaces.
  862. </p></li></ul></div><p>
  863. </p><p>
  864. It should also be noted that the default <acronym class="acronym">WAL</acronym>
  865. format is fairly bulky since it includes many disk page snapshots.
  866. These page snapshots are designed to support crash recovery, since
  867. we might need to fix partially-written disk pages. Depending on
  868. your system hardware and software, the risk of partial writes might
  869. be small enough to ignore, in which case you can significantly
  870. reduce the total volume of archived logs by turning off page
  871. snapshots using the <a class="xref" href="runtime-config-wal.html#GUC-FULL-PAGE-WRITES">full_page_writes</a>
  872. parameter. (Read the notes and warnings in <a class="xref" href="wal.html" title="Chapter 29. Reliability and the Write-Ahead Log">Chapter 29</a>
  873. before you do so.) Turning off page snapshots does not prevent
  874. use of the logs for PITR operations. An area for future
  875. development is to compress archived WAL data by removing
  876. unnecessary page copies even when <code class="varname">full_page_writes</code> is
  877. on. In the meantime, administrators might wish to reduce the number
  878. of page snapshots included in WAL by increasing the checkpoint
  879. interval parameters as much as feasible.
  880. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="backup-file.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="backup.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="high-availability.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">25.2. File System Level Backup </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> Chapter 26. High Availability, Load Balancing, and Replication</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1