PostgreSQL增量备份是怎么做到的呢?

一个数据页的框架如下

数据页头部的数据结构

  1. {
  2. /* XXX LSN is member of *any* block, not only page-organized ones */
  3. PageXLogRecPtr pd_lsn; /* LSN: next byte after last byte of xlog
  4. * record for last change to this page */
  5. uint16 pd_checksum; /* checksum */
  6. uint16 pd_flags; /* flag bits, see below */
  7. LocationIndex pd_lower; /* offset to start of free space */
  8. LocationIndex pd_upper; /* offset to end of free space */
  9. LocationIndex pd_special; /* offset to start of special space */
  10. uint16 pd_pagesize_version;
  11. TransactionId pd_prune_xid; /* oldest prunable XID, or zero if none */
  12. ItemIdData pd_linp[FLEXIBLE_ARRAY_MEMBER]; /* line pointer array */
  13. } PageHeaderData;

因为如果对象是持久化的,那么它的所有变更都会记录REDO,数据页头部的pd_lsn表示该数据页最后一次变化时,变化产生的REDO在xlog file中的结束位置.
即如果xlog flush的xlog地址位 大于或等于 此页pd_lsn,那么这个页的更改就可以认为是可靠的。

  1. * pd_lsn - identifies xlog record for last change to this page.
  2. * pd_checksum - page checksum, if set.
  3. * pd_flags - flag bits.
  4. * pd_lower - offset to start of free space.
  5. * pd_upper - offset to end of free space.
  6. * pd_special - offset to start of special space.
  7. * pd_pagesize_version - size in bytes and page layout version number.
  8. * pd_prune_xid - oldest XID among potentially prunable tuples on page.

好了,既然每次块的变化都包含了LSN的修改,那么也即是说,我们可以通过第一次备份开始时的全局LSN,以及当前需要备份的数据的page LSN来判断此页是否发生过修改。

如果修改了就备份,没修改,就不需要备份, 从而实现数据库的块级增量备份。

pg_rman 介绍

pg_rman是一个,类似Oracle的RMAN。
documentation见

pg_rman使用的是pg_start_backup(), copy, pg_stop_backup()的备份模式。
pg_rman跑的不是流复制协议,而是文件拷贝,所以pg_rman必须和数据库节点跑在一起。
如果在standby节点跑pg_rman,pg_rman则需要通过网络连接到主节点执行pg_start_backup和pg_stop_backup。
pg_rman的用法非常简单,支持以下几种运行模式。

使用pg_rman的前提

开启归档
配置csvlog
建议的配置

  1. postgres=# show log_destination ;
  2. log_destination
  3. -----------------
  4. csvlog
  5. (1 row)
  6. postgres=# SHOW log_directory ;
  7. log_directory
  8. ---------------
  9. pg_log
  10. (1 row)
  11. postgres=# SHOW archive_command ;
  12. archive_command
  13. --------------------------------------------
  14. cp %p /data04/digoal/arc_log/%f
  15. (1 row)

初始化pg_rman backup catalog

首先需要初始化一个backup catalog,实际上就是需要一个目录,这个目录将用于存放备份的文件。
同时这个目录也会存放一些元数据,例如备份的配置文件,数据库的systemid,时间线文件历史等等。
初始化命令需要两个参数,分别为备份目标目录,以及数据库的$PGDATA

  1. $ mkdir /data05/digoal/pgbbk
  2. $ /home/digoal/pgsql9.5/bin/pg_rman init -B /data05/digoal/pgbbk -D /data04/digoal/pg_root
  3. INFO: ARCLOG_PATH is set to '/data04/digoal/arc_log'
  4. INFO: SRVLOG_PATH is set to '/data04/digoal/pg_root/pg_log'

生成备份元数据如下

  1. [digoal@iZ28tqoemgtZ ~]$ cd /data05/digoal/pgbbk/
  2. [digoal@iZ28tqoemgtZ pgbbk]$ ll
  3. total 16
  4. drwx------ 4 digoal digoal 4096 Aug 26 19:29 backup
  5. -rw-rw-r-- 1 digoal digoal 82 Aug 26 19:29 pg_rman.ini
  6. -rw-rw-r-- 1 digoal digoal 40 Aug 26 19:29 system_identifier
  7. drwx------ 2 digoal digoal 4096 Aug 26 19:29 timeline_history

生成的配置文件

  1. $ cat pg_rman.ini
  2. ARCLOG_PATH='/data04/digoal/arc_log'
  3. SRVLOG_PATH='/data04/digoal/pg_root/pg_log'

你可以把将来要使用的配置写在这个配置文件中,或者写在pg_rman的命令行中。
我后面的测试会直接使用命令行参数。
生成的数据库system id,用于区分备份的数据库是不是一个数据库,防止被冲。

  1. $ cat system_identifier
  2. SYSTEM_IDENTIFIER='6318621837015461309'

与控制文件中存储的system id一致。

注意
pg_rman只从postgresql.conf取log_directory和archive_command参数的值。
如果你的PostgreSQL的配置文件是include的或者配置在postgresql.auto.conf中,这两个值将不准确。
所以建议你仅仅把参数配置在postgresql.conf中,而不要使用其他配置文件。

pg_rman 命令行用法

  1. pg_rman manage backup/recovery of PostgreSQL database.
  2. Usage:
  3. pg_rman OPTION init
  4. pg_rman OPTION backup
  5. pg_rman OPTION restore
  6. pg_rman OPTION show [DATE]
  7. pg_rman OPTION show detail [DATE]
  8. pg_rman OPTION validate [DATE]
  9. pg_rman OPTION delete DATE
  10. pg_rman OPTION purge
  11. Common Options:
  12. -D, --pgdata=PATH location of the database storage area
  13. -A, --arclog-path=PATH location of archive WAL storage area
  14. -S, --srvlog-path=PATH location of server log storage area
  15. -B, --backup-path=PATH location of the backup storage area
  16. -c, --check show what would have been done
  17. -v, --verbose show what detail messages
  18. -P, --progress show progress of processed files
  19. Backup options:
  20. -b, --backup-mode=MODE full, incremental, or archive
  21. -s, --with-serverlog also backup server log files
  22. -Z, --compress-data compress data backup with zlib
  23. -C, --smooth-checkpoint do smooth checkpoint before backup
  24. -F, --full-backup-on-error switch to full backup mode
  25. if pg_rman cannot find validate full backup
  26. on current timeline
  27. NOTE: this option is only used in --backup-mode=incremental or archive.
  28. --keep-data-generations=NUM keep NUM generations of full data backup
  29. --keep-data-days=NUM keep enough data backup to recover to N days ago
  30. --keep-arclog-files=NUM keep NUM of archived WAL
  31. --keep-arclog-days=DAY keep archived WAL modified in DAY days
  32. --keep-srvlog-files=NUM keep NUM of serverlogs
  33. --keep-srvlog-days=DAY keep serverlog modified in DAY days
  34. --standby-host=HOSTNAME standby host when taking backup from standby
  35. --standby-port=PORT standby port when taking backup from standby
  36. Restore options:
  37. --recovery-target-time time stamp up to which recovery will proceed
  38. --recovery-target-xid transaction ID up to which recovery will proceed
  39. --recovery-target-inclusive whether we stop just after the recovery target
  40. --recovery-target-timeline recovering into a particular timeline
  41. --hard-copy copying archivelog not symbolic link
  42. Catalog options:
  43. -a, --show-all show deleted backup too
  44. Delete options:
  45. -f, --force forcibly delete backup older than given DATE
  46. Connection options:
  47. -d, --dbname=DBNAME database to connect
  48. -h, --host=HOSTNAME database server host or socket directory
  49. -p, --port=PORT database server port
  50. -U, --username=USERNAME user name to connect as
  51. -w, --no-password never prompt for password
  52. -W, --password force password prompt
  53. Generic options:
  54. -q, --quiet don't show any INFO or DEBUG messages
  55. --debug show DEBUG messages
  56. --help show this help, then exit
  57. --version output version information, then exit
  58. Read the website for details. <http://github.com/ossc-db/pg_rman>
  59. Report bugs to <http://github.com/ossc-db/pg_rman/issues>.

输入必要的参数或option

  1. $ export PGPASSWORD=postgres
  2. $ /home/digoal/pgsql9.5/bin/pg_rman backup \
  3. -B /data05/digoal/pgbbk \
  4. -D /data04/digoal/pg_root \
  5. -b full \
  6. -s \
  7. -Z \
  8. -C \
  9. --keep-data-days=10 \
  10. --keep-arclog-files=15 \
  11. --keep-arclog-days=10 \
  12. --keep-srvlog-files=10 \
  13. --keep-srvlog-days=15 \
  14. -h 127.0.0.1 -p 1921 -U postgres -d postgres

结果

  1. INFO: copying database files
  2. NOTICE: pg_stop_backup complete, all required WAL segments have been archived
  3. INFO: copying archived WAL files
  4. INFO: copying server log files
  5. INFO: backup complete
  6. HINT: Please execute 'pg_rman validate' to verify the files are correctly copied.
  7. INFO: start deleting old archived WAL files from ARCLOG_PATH (keep files = 15, keep days = 10)
  8. INFO: the threshold timestamp calculated by keep days is "2016-08-16 00:00:00"
  9. INFO: start deleting old server files from SRVLOG_PATH (keep files = 10, keep days = 15)
  10. INFO: the threshold timestamp calculated by keep days is "2016-08-11 00:00:00"
  11. INFO: start deleting old backup (keep after = 2016-08-16 00:00:00)
  12. INFO: does not include the backup just taken
  13. WARNING: backup "2016-08-26 19:39:32" is not taken int account
  14. DETAIL: This is not valid backup.

校验备份集

备份时pg_rman会记录每个备份文件的crc,以便validate进行校验。
例如某个备份集

  1. $ less /data05/digoal/pgbbk/20160826/195809/file_database.txt
  2. .s.PGSQL.1921 ? 0 0 0777 2016-08-26 19:27:05
  3. .s.PGSQL.1921.lock f 55 590164837 0600 2016-08-26 19:27:05
  4. PG_VERSION f 12 3872055064 0600 2016-07-28 10:03:42
  5. backup_label f 167 2985542389 0600 2016-08-26 19:58:42
  6. backup_label.old f 155 4273989468 0600 2016-08-23 19:43:32
  7. base d 0 0 0700 2016-08-23 10:28:32
  8. base/1 d 0 0 0700 2016-08-24 16:17:02
  9. base/1/112 f 57 1147028285 0600 2016-07-28 10:03:42
  10. base/1/113 f 57 1147028285 0600 2016-07-28 10:03:42
  11. base/1/1247 F 8178 1875285513 0600 2016-07-29 13:51:29
  12. base/1/1247_fsm f 139 3668812536 0600 2016-07-28 10:03:43

解释: 路径,文件类型,大小,CRC校验值,权限,时间,第四列即crc校验值
每次备份完,必须要做一次校验,否则备份集不可用用来恢复,增量备份时也不会用它来做增量比较。

  1. $ /home/digoal/pgsql9.5/bin/pg_rman validate -B /data05/digoal/pgbbk
  2. INFO: validate: "2016-08-26 19:39:50" backup, archive log files and server log files by CRC
  3. INFO: backup "2016-08-26 19:39:50" is valid

每个备份集都包含了一个备份状态文件,如下

  1. cat /data05/digoal/pgbbk/20160826/201955/backup.ini
  2. # configuration
  3. BACKUP_MODE=INCREMENTAL
  4. FULL_BACKUP_ON_ERROR=false
  5. WITH_SERVERLOG=true
  6. COMPRESS_DATA=true
  7. # result
  8. TIMELINEID=1
  9. START_LSN=46/df000108
  10. STOP_LSN=46/df000210
  11. START_TIME='2016-08-26 20:19:55'
  12. END_TIME='2016-08-26 20:20:48'
  13. RECOVERY_XID=3896508593
  14. RECOVERY_TIME='2016-08-26 20:20:47'
  15. TOTAL_DATA_BYTES=6196524307
  16. READ_DATA_BYTES=3199287520
  17. READ_ARCLOG_BYTES=33554754
  18. READ_SRVLOG_BYTES=0
  19. WRITE_BYTES=125955
  20. BLOCK_SIZE=8192
  21. XLOG_BLOCK_SIZE=8192
  22. STATUS=OK

这个文件中包含了很重要的信息,比如LSN,后面LSN将用于比对增量备份时对比数据块的LSN是否发生了变化,是否需要备份。

增量备份

  1. $ export PGPASSWORD=postgres
  2. $ /home/digoal/pgsql9.5/bin/pg_rman backup \
  3. -B /data05/digoal/pgbbk \
  4. -D /data04/digoal/pg_root \
  5. -b incremental \
  6. -s \
  7. -Z \
  8. -C \
  9. --keep-data-days=10 \
  10. --keep-arclog-files=15 \
  11. --keep-arclog-days=10 \
  12. --keep-srvlog-files=10 \
  13. --keep-srvlog-days=15 \
  14. -h 127.0.0.1 -p 1921 -U postgres -d postgres

增量备份输出

校验备份集

  1. $ /home/digoal/pgsql9.5/bin/pg_rman validate -B /data05/digoal/pgbbk
  2. INFO: validate: "2016-08-26 19:43:20" backup, archive log files and server log files by CRC
  3. INFO: backup "2016-08-26 19:43:20" is valid

列出备份集

  1. $ /home/digoal/pgsql9.5/bin/pg_rman show -B /data05/digoal/pgbbk
  2. ==========================================================
  3. StartTime Mode Duration Size TLI Status
  4. ==========================================================
  5. 2016-08-26 19:43:20 INCR 0m 54kB 1 OK
  6. 2016-08-26 19:39:50 FULL 1m 245MB 1 OK

可以看到增量非常小,因为很少变化的块。
接下来更新一张大表的某一条记录,再看看。

  1. List of relations
  2. Schema | Name | Type | Owner | Size | Description
  3. --------+----------+-------+----------+---------+-------------
  4. public | hll_test | table | postgres | 208 kB |
  5. public | t | table | postgres | 3050 MB |
  6. public | tbl2 | table | postgres | 63 MB |
  7. public | test | table | postgres | 120 MB |
  8. (5 rows)
  9. postgres=# with t1 as (select id from t where id between 1 and 1000 limit 10) update t set info='new' where id in (select * from t1);
  10. UPDATE 10

更新后做一个增量备份

  1. $ /home/digoal/pgsql9.5/bin/pg_rman backup -B /data05/digoal/pgbbk -D /data04/digoal/pg_root -b incremental -s -Z -C --keep-data-days=10 --keep-arclog-files=15 --keep-arclog-days=10 --keep-srvlog-files=10 --keep-srvlog-days=15 -h 127.0.0.1 -p 1921 -U postgres -d postgres
  2. INFO: copying database files
  3. NOTICE: pg_stop_backup complete, all required WAL segments have been archived
  4. INFO: copying archived WAL files
  5. INFO: copying server log files
  6. INFO: backup complete
  7. HINT: Please execute 'pg_rman validate' to verify the files are correctly copied.
  8. INFO: start deleting old archived WAL files from ARCLOG_PATH (keep files = 15, keep days = 10)
  9. INFO: the threshold timestamp calculated by keep days is "2016-08-16 00:00:00"
  10. INFO: start deleting old server files from SRVLOG_PATH (keep files = 10, keep days = 15)
  11. INFO: the threshold timestamp calculated by keep days is "2016-08-11 00:00:00"
  12. INFO: start deleting old backup (keep after = 2016-08-16 00:00:00)
  13. INFO: does not include the backup just taken
  14. INFO: backup "2016-08-26 19:58:09" should be kept
  15. DETAIL: This is taken after "2016-08-16 00:00:00".
  16. WARNING: backup "2016-08-26 19:56:54" is not taken int account
  17. DETAIL: This is not valid backup.
  18. INFO: backup "2016-08-26 19:43:20" should be kept
  19. DETAIL: This is taken after "2016-08-16 00:00:00".
  20. INFO: backup "2016-08-26 19:39:50" should be kept
  21. DETAIL: This is taken after "2016-08-16 00:00:00".
  22. WARNING: backup "2016-08-26 19:39:32" is not taken int account
  23. DETAIL: This is not valid backup.

校验备份集

  1. [digoal@iZ28tqoemgtZ pg_rman]$ /home/digoal/pgsql9.5/bin/pg_rman validate -B /data05/digoal/pgbbk
  2. INFO: validate: "2016-08-26 20:19:55" backup, archive log files and server log files by CRC
  3. INFO: backup "2016-08-26 20:19:55" is valid

输出当前备份

  1. [digoal@iZ28tqoemgtZ pg_rman]$ /home/digoal/pgsql9.5/bin/pg_rman show -B /data05/digoal/pgbbk
  2. ==========================================================
  3. StartTime Mode Duration Size TLI Status
  4. ==========================================================
  5. 2016-08-26 20:19:55 INCR 0m 125kB 1 OK
  6. 2016-08-26 19:58:09 FULL 11m 3094MB 1 OK
  7. 2016-08-26 19:56:54 FULL 1m 0B 0 ERROR
  8. 2016-08-26 19:43:20 INCR 0m 54kB 1 OK
  9. 2016-08-26 19:39:50 FULL 1m 245MB 1 OK
  10. 2016-08-26 19:39:32 FULL 0m 0B 0 ERROR

按指定时间从catalog删除备份集

例如我只需要我的备份集能恢复到2016-08-26 19:59:00,在这个时间点以前,不需要用来恢复到这个时间点的备份全删掉。

  1. $ /home/digoal/pgsql9.5/bin/pg_rman delete "2016-08-26 19:59:00" -B /data05/digoal/pgbbk
  2. WARNING: cannot delete backup with start time "2016-08-26 19:58:09"
  3. DETAIL: This is the latest full backup necessary for successful recovery.
  4. INFO: delete the backup with start time: "2016-08-26 19:56:54"
  5. INFO: delete the backup with start time: "2016-08-26 19:43:20"
  6. INFO: delete the backup with start time: "2016-08-26 19:39:50"
  7. INFO: delete the backup with start time: "2016-08-26 19:39:32"

保留的备份集合可以将数据库恢复到2016-08-26 19:59:00

  1. $ /home/digoal/pgsql9.5/bin/pg_rman show -B /data05/digoal/pgbbk
  2. ==========================================================
  3. StartTime Mode Duration Size TLI Status
  4. ==========================================================
  5. 2016-08-26 20:19:55 INCR 0m 125kB 1 OK
  6. 2016-08-26 19:58:09 FULL 11m 3094MB 1 OK
  1. $ /home/digoal/pgsql9.5/bin/pg_rman purge -B /data05/digoal/pgbbk
  2. INFO: DELETED backup "2016-08-26 19:56:54" is purged
  3. INFO: DELETED backup "2016-08-26 19:43:20" is purged
  4. INFO: DELETED backup "2016-08-26 19:39:50" is purged
  5. INFO: DELETED backup "2016-08-26 19:39:32" is purged

恢复

pg_rman数据恢复时的两个必要要素

  1. 新的$PGDATA
  2. 备份目录
    命令的选项也很简单,甚至可以不指定任何option
  1. Restore options:
  2. The parameters which are started with recovery are same as parameters in recovery.conf. See also Recovery Configuration for details.

接下来的几个配置,与recovery.conf的意思对齐。

如果不指定时间线,则使用$PGDATA/global/pg_control,如果没有$PGDATA/global/pg_control,则使用最新的全量备份集的时间线。

  1. --recovery-target-timeline TIMELINE
  2. Specifies recovering into a particular timeline. If not specified, the current timeline from ($PGDATA/global/pg_control) is used.

如果不指定,则恢复到最新时间

  1. --recovery-target-time TIMESTAMP
  2. This parameter specifies the time stamp up to which recovery will proceed. If not specified, continue recovery to the latest time.

如果不指定,则恢复到最新xid

  1. --recovery-target-xid XID
  2. This parameter specifies the transaction ID up to which recovery will proceed. If not specified, continue recovery to the latest xid.

如果不指定,则默认使用true,即恢复到包含恢复目标XID的commit record为止,或者第一笔commit record ts>指定ts的 commit redo record为止;
如果是false则不apply恢复目标XID的commit record,或者不apply第一笔commit record ts>=指定ts的 commit redo record。

  1. --recovery-target-inclusive
  2. Specifies whether we stop just after the specified recovery target (true), or just before the recovery target (false). Default is true.

是否使用硬链接复制archive log,而不需要拷贝文件

例子

恢复时,需要注意,你可以选择原地恢复(覆盖式),或者使用新的$PGDATA作为恢复目标。

但是请注意,不管是哪种恢复方式,如果在本机恢复的话,pg_rman可能会覆盖原有的数据文件,arch, pg_xlog目录中的文件,所以,如果你要保留原数据,建议先将原数据目录重命名。

  1. 原地恢复
  2. 使用新的$PGDATA恢复

在本机恢复的例子
1. 停库

  1. pg_ctl stop -m fast -D /data04/digoal/pg_root_1922

2. 重命名原数据相关目录

  1. $PGDATA
  2. mv /data04/digoal/pg_root_1922 /data04/digoal/old_pg_root_1922
  3. PG_XLOG
  4. mv /data05/digoal/pg_xlog_1922 /data05/digoal/old_pg_xlog_1922
  5. 表空间
  6. mv /data02/digoal/tbs1_1922 /data02/digoal/old_tbs1_1922
  7. 归档目录,除了要重命名,还需要新建一个原目录
  8. mv /data04/digoal/arc_log1922 /data04/digoal/old_arc_log1922
  9. mkdir /data04/digoal/arc_log1922
  10. ...

3. pg_rman restore

  1. pg_rman restore -B /data05/digoal/pgstdbak -D /data04/digoal/pg_restore_root
  2. WARNING: could not open pg_controldata file "/data04/digoal/pg_restore_root/global/pg_control": No such file or directory
  3. WARNING: could not open pg_controldata file "/data04/digoal/pg_restore_root/global/pg_control": No such file or directory
  4. INFO: the recovery target timeline ID is not given
  5. INFO: use timeline ID of latest full backup as recovery target: 1
  6. INFO: calculating timeline branches to be used to recovery target point
  7. INFO: searching latest full backup which can be used as restore start point
  8. INFO: found the full backup can be used as base in recovery: "2016-08-29 15:05:32"
  9. INFO: copying online WAL files and server log files
  10. INFO: clearing restore destination
  11. INFO: validate: "2016-08-29 15:05:32" backup, archive log files and server log files by SIZE
  12. INFO: backup "2016-08-29 15:05:32" is valid
  13. INFO: restoring database files from the full mode backup "2016-08-29 15:05:32"
  14. INFO: searching incremental backup to be restored
  15. INFO: validate: "2016-08-29 15:13:10" backup, archive log files and server log files by SIZE
  16. INFO: backup "2016-08-29 15:13:10" is valid
  17. INFO: restoring database files from the incremental mode backup "2016-08-29 15:13:10"
  18. INFO: searching backup which contained archived WAL files to be restored
  19. INFO: backup "2016-08-29 15:13:10" is valid
  20. INFO: restoring WAL files from backup "2016-08-29 15:13:10"
  21. INFO: restoring online WAL files and server log files
  22. INFO: generating recovery.conf
  23. INFO: restore complete
  24. HINT: Recovery will start automatically when the PostgreSQL server is started.

4. 修改postgresql.conf, recovery.conf
根据实际情况调整,本例不修改

  1. cd /data04/digoal/pg_restore_root/
  2. digoal@iZ28tqoemgtZ-> ll
  3. total 124K
  4. -rw------- 1 digoal digoal 193 Aug 29 17:05 backup_label.old
  5. drwx------ 7 digoal digoal 4.0K Aug 29 17:05 base
  6. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 global
  7. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_clog
  8. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_commit_ts
  9. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_dynshmem
  10. -rw------- 1 digoal digoal 4.4K Aug 29 17:05 pg_hba.conf
  11. -rw------- 1 digoal digoal 1.6K Aug 29 17:05 pg_ident.conf
  12. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_log
  13. drwx------ 4 digoal digoal 4.0K Aug 29 17:05 pg_logical
  14. drwx------ 4 digoal digoal 4.0K Aug 29 17:05 pg_multixact
  15. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_notify
  16. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_replslot
  17. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_serial
  18. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_snapshots
  19. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_stat
  20. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_stat_tmp
  21. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_subtrans
  22. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_tblspc
  23. drwx------ 2 digoal digoal 4.0K Aug 29 17:05 pg_twophase
  24. -rw------- 1 digoal digoal 4 Aug 29 17:05 PG_VERSION
  25. lrwxrwxrwx 1 digoal digoal 27 Aug 29 17:05 pg_xlog -> /data05/digoal/pg_xlog_1922
  26. -rw------- 1 digoal digoal 88 Aug 29 17:05 postgresql.auto.conf
  27. -rw------- 1 digoal digoal 22K Aug 29 17:05 postgresql.conf
  28. -rw------- 1 digoal digoal 44 Aug 29 17:05 postmaster.opts
  29. -rw-r--r-- 1 digoal digoal 130 Aug 29 17:06 recovery.conf
  30. digoal@iZ28tqoemgtZ-> cd pg_tblspc/
  31. digoal@iZ28tqoemgtZ-> ll
  32. total 0
  33. lrwxrwxrwx 1 digoal digoal 24 Aug 29 17:05 16719 -> /data02/digoal/tbs1_1922
  34. cd ..
  35. vi postgresql.conf
  36. archive_command = 'cp %p /data04/digoal/arc_log1922/%f'
  37. vi recovery.conf
  38. # recovery.conf generated by pg_rman 1.3.2
  39. restore_command = 'cp /data04/digoal/arc_log1922/%f %p'
  40. recovery_target_timeline = '1'

5. 如果备份集的时间线发生了变化,需要先手工拷贝到归档目录,再执行restore

  1. digoal@iZ28tqoemgtZ-> pg_rman restore -B /data05/digoal/pgstdbak -D /data04/digoal/pg_restore_root
  2. WARNING: could not open pg_controldata file "/data04/digoal/pg_restore_root/global/pg_control": No such file or directory
  3. WARNING: could not open pg_controldata file "/data04/digoal/pg_restore_root/global/pg_control": No such file or directory
  4. INFO: the recovery target timeline ID is not given
  5. INFO: use timeline ID of latest full backup as recovery target: 2
  6. INFO: calculating timeline branches to be used to recovery target point
  7. ERROR: could not open destination file "/data04/digoal/arc_log1922/00000002.history": No such file or directory
  8. digoal@iZ28tqoemgtZ-> mkdir /data04/digoal/arc_log1922
  9. digoal@iZ28tqoemgtZ-> cp /data05/digoal/pgstdbak/timeline_history/00000002.history /data04/digoal/arc_log1922/
  10. digoal@iZ28tqoemgtZ-> pg_rman restore -B /data05/digoal/pgstdbak -D /data04/digoal/pg_restore_root
  11. WARNING: could not open pg_controldata file "/data04/digoal/pg_restore_root/global/pg_control": No such file or directory
  12. WARNING: could not open pg_controldata file "/data04/digoal/pg_restore_root/global/pg_control": No such file or directory
  13. INFO: the recovery target timeline ID is not given
  14. INFO: use timeline ID of latest full backup as recovery target: 2
  15. INFO: calculating timeline branches to be used to recovery target point
  16. INFO: searching latest full backup which can be used as restore start point
  17. INFO: found the full backup can be used as base in recovery: "2016-08-29 17:14:20"
  18. INFO: copying online WAL files and server log files
  19. INFO: clearing restore destination
  20. INFO: validate: "2016-08-29 17:14:20" backup and archive log files by SIZE
  21. INFO: backup "2016-08-29 17:14:20" is valid
  22. INFO: restoring database files from the full mode backup "2016-08-29 17:14:20"
  23. INFO: searching incremental backup to be restored
  24. INFO: searching backup which contained archived WAL files to be restored
  25. INFO: backup "2016-08-29 17:14:20" is valid
  26. INFO: restoring WAL files from backup "2016-08-29 17:14:20"
  27. INFO: restoring online WAL files and server log files
  28. INFO: generating recovery.conf
  29. INFO: restore complete
  30. HINT: Recovery will start automatically when the PostgreSQL server is started.
  31. digoal@iZ28tqoemgtZ-> cd /data04/digoal/arc_log1922
  32. digoal@iZ28tqoemgtZ-> ll
  33. total 16K
  34. lrwxrwxrwx 1 digoal digoal 71 Aug 29 17:18 00000002000000470000000C -> /data05/digoal/pgstdbak/20160829/171420/arclog/00000002000000470000000C
  35. lrwxrwxrwx 1 digoal digoal 71 Aug 29 17:18 00000002000000470000000D -> /data05/digoal/pgstdbak/20160829/171420/arclog/00000002000000470000000D
  36. lrwxrwxrwx 1 digoal digoal 87 Aug 29 17:18 00000002000000470000000D.00000028.backup -> /data05/digoal/pgstdbak/20160829/171420/arclog/00000002000000470000000D.00000028.backup
  37. -rw------- 1 digoal digoal 42 Aug 29 17:18 00000002.history

6. 启动恢复目标数据库

  1. digoal@iZ28tqoemgtZ-> pg_ctl start -D /data04/digoal/pg_restore_root
  2. server starting
  3. digoal@iZ28tqoemgtZ-> LOG: 00000: redirecting log output to logging collector process
  4. HINT: Future log output will appear in directory "pg_log".
  5. LOCATION: SysLogger_Start, syslogger.c:622
  6. digoal@iZ28tqoemgtZ-> psql -h 127.0.0.1 -p 1922
  7. psql (9.5.3)
  8. Type "help" for help.
  9. postgres=# select pg_is_in_recovery();
  10. pg_is_in_recovery
  11. -------------------
  12. f
  13. (1 row)
  14. postgres=# \l+
  15. List of databases
  16. Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description
  17. --------------------+----------+----------+---------+-------+-----------------------+---------+------------+--------------------------------------------
  18. contrib_regression | postgres | UTF8 | C | C | | 7137 kB | pg_default |
  19. db1 | postgres | UTF8 | C | C | | 111 MB | tbs1 |
  20. postgres | postgres | UTF8 | C | C | | 797 MB | pg_default | default administrative connection database
  21. | | | | | postgres=CTc/postgres | | |
  22. template1 | postgres | UTF8 | C | C | =c/postgres +| 7137 kB | pg_default | default template for new databases
  23. | | | | | postgres=CTc/postgres | | |
  24. (5 rows)

注意事项

  1. 小心覆盖原有的部分

  2. 建议先将原有的目录重命名,或者在其他机器恢复,

  3. 用户可以指定$PGDATA,恢复到新的目标目录,但是arch_log, 表空间, pg_xlog目录无法指定新的位置,所以原地还原时,必须注意这些目录可能被覆盖,先重命名是比较好的手段。

pg_rman 可以优化的地方

  1. 检查哪些要恢复的块与目标块的CRC是否一致,如果一致,不需要拷贝,减少WRITE。

pg_rman 软件限制

pg_rman has the following restrictions.

  1. Requires to read database cluster directory and write backup catalog directory.
    For example, you need to mount the disk where backup catalog is placed with NFS from database server.
    实际上不是必须的,如果没有指定原来的$PGDATA,则使用备份集的元数据。

  2. Block sizes of pg_rman and server should be matched. BLCKSZ and XLOG_BLCKSZ also should be matched.
    编译pg_rman时,最好使用启动数据集的集群软件的pg_config。 确保块大小一致。
    因为需要做块的校验。 读取LSN等,都与块大小有关。

  3. If there are some unreadable files/directories in database cluster directory, WAL directory or archived WAL directory, the backup or restore would be failed.

Getting backup from standby-site, pg_rman has the follow restrictions too.

  1. The environment of replication should be built right, or the backup will not finish.

  2. You can’t get backups on master and standby at the same time.
    因为pg_rman使用的是exclusive bakcup,(pg_start_backup),所以同一时间,只能跑一次pg_start_backup。
    pg_basebackup则使用的是shared backup,可以跑多个。

  3. You can’t get backups on multi standbys at the same time too.
    道理同上

  4. Basically, the backup from standby-site is used for restoring on MASTER.
    pg_rman doesn’t treat the backup as restoring on standby automatically.

  5. If you want to restore the backup on STANDBY, you have to manage archive logs with your self.
    因为备库不归档,所以从standby备份时,需要解决归档备份的问题。
    我在前面的文档中已经提及,包括解决思路。

When using storage snapshot, pg_rman has the following restrictions too.

  1. If your snapshot does not have any file update time, incremental backup is same with full backup.

  2. Because pg_rman judges performing full backup or incremental backup by update time for files.
    If files don’t have update time because of storage snapshot specification, pg_rman performs full backup every time.

  3. You can’t backup for one side works storage with split mirror snapshot.

  4. Before you execute pg_rman, you should perform storage “RESYNC”.

  5. After pg_rman performs backup with split mirror snapshot, storeage will be “SPLITTED”(works on one side).
    pg_rman perform SPLIT command for getting snapshot, but doesn’t perform RESYNC command.

  6. You cant’t get snapshot from different vendor storages in a time.

  7. You cant’t use some vendor storages which have different commands for getting snapshot.

  8. The script and commands for getting storage snapshot should be executable.

  9. It’s expected to have authority of root for getting snapshot or mounting volumes.
    So a user, performs pg_rman, is granted to execute any commands in the script.

  10. If you use LVM(Logical Volume Manager), it’s needed root authority for mount, umount, lvcreate, lvremove, lvscan commands.
    You should granted to these commands with sudo command to non-password executable.

  1. 增量备份代码

上次备份以来,数据块的LSN是否发生了变化,如果自从上次备份的start_lsn以来没有发生变化,则不备份。

代码举例

  1. else
  2. {
  3. pgBackupGetPath(prev_backup, prev_file_txt, lengthof(prev_file_txt),
  4. DATABASE_FILE_LIST);
  5. prev_files = dir_read_file_list(pgdata, prev_file_txt);
  6. /*
  7. * Do backup only pages having larger LSN than previous backup.
  8. */
  9. lsn = &prev_backup->start_lsn;
  10. xlogid = (uint32) (*lsn >> 32);
  11. xrecoff = (uint32) *lsn;
  12. elog(DEBUG, _("backup only the page updated after LSN(%X/%08X)"),
  13. xlogid, xrecoff);
  14. }
  15. ...
  16. /* backup files from non-snapshot */
  17. pgBackupGetPath(&current, path, lengthof(path), DATABASE_DIR);
  18. backup_files(pgdata, path, files, prev_files, lsn, current.compress_data, NULL);
  1. 备份结果backup.ini相关代码
  1. # configuration
  2. BACKUP_MODE=FULL
  3. FULL_BACKUP_ON_ERROR=false
  4. WITH_SERVERLOG=true
  5. COMPRESS_DATA=true
  6. # result
  7. TIMELINEID=1
  8. START_LSN=43/d5000028
  9. STOP_LSN=43/d5000168
  10. START_TIME='2016-08-26 15:43:39'
  11. END_TIME='2016-08-26 15:44:27'
  12. RECOVERY_XID=3896508572
  13. RECOVERY_TIME='2016-08-26 15:44:18'
  14. TOTAL_DATA_BYTES=823571731
  15. READ_DATA_BYTES=823571731
  16. READ_ARCLOG_BYTES=234881668
  17. READ_SRVLOG_BYTES=218248
  18. WRITE_BYTES=206009921
  19. BLOCK_SIZE=8192
  20. XLOG_BLOCK_SIZE=8192
  21. STATUS=OK

对应的数据结构

  1. /*
  2. * pg_rman takes backup into the directory $BACKUP_PATH/<date>/<time>.
  3. *
  4. * status == -1 indicates the pgBackup is invalid.
  5. */
  6. typedef struct pgBackup
  7. {
  8. /* Backup Level */
  9. BackupMode backup_mode;
  10. bool with_serverlog;
  11. bool compress_data;
  12. bool full_backup_on_error;
  13. /* Status - one of BACKUP_STATUS_xxx */
  14. BackupStatus status;
  15. /* Timestamp, etc. */
  16. TimeLineID tli;
  17. XLogRecPtr start_lsn;
  18. XLogRecPtr stop_lsn;
  19. time_t start_time;
  20. time_t end_time;
  21. time_t recovery_time;
  22. uint32 recovery_xid;
  23. /* Size (-1 means not-backup'ed) */
  24. int64 total_data_bytes;
  25. int64 read_data_bytes;
  26. int64 read_arclog_bytes;
  27. int64 read_srvlog_bytes;
  28. int64 write_bytes;
  29. /* data/wal block size for compatibility check */
  30. uint32 block_size;
  31. uint32 wal_block_size;
  32. /* if backup from standby or not */
  33. bool is_from_standby;
  34. } pgBackup;

备份开始时记录pg_start_backup调用返回的lsn,写入backup->start_lsn

  1. /*
  2. * Notify start of backup to PostgreSQL server.
  3. */
  4. static void
  5. pg_start_backup(const char *label, bool smooth, pgBackup *backup)
  6. {
  7. PGresult *res;
  8. const char *params[2];
  9. params[0] = label;
  10. elog(DEBUG, "executing pg_start_backup()");
  11. reconnect();
  12. /* Assumes PG version >= 8.4 */
  13. /* 2nd argument is 'fast' (IOW, !smooth) */
  14. params[1] = smooth ? "false" : "true";
  15. res = execute("SELECT * from pg_xlogfile_name_offset(pg_start_backup($1, $2))", 2, params);
  16. if (backup != NULL)
  17. get_lsn(res, &backup->tli, &backup->start_lsn);
  18. elog(DEBUG, "backup start point is (WAL file: %s, xrecoff: %s)",
  19. PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 1));
  20. PQclear(res);
  21. disconnect();
  22. }

备份停止,调用pg_stop_backup,从返回结果中取出LSN,写入backup->stop_lsn

  1. /*
  2. * Notify end of backup to PostgreSQL server.
  3. */
  4. static void
  5. pg_stop_backup(pgBackup *backup)
  6. {
  7. elog(DEBUG, "executing pg_stop_backup()");
  8. wait_for_archive(backup,
  9. "SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup())");
  10. }
  11. static void
  12. wait_for_archive(pgBackup *backup, const char *sql)
  13. {
  14. PGresult *res;
  15. char ready_path[MAXPGPATH];
  16. int try_count;
  17. reconnect();
  18. res = execute(sql, 0, NULL);
  19. if (backup != NULL)
  20. {
  21. get_lsn(res, &backup->tli, &backup->stop_lsn);
  22. elog(DEBUG, "backup end point is (WAL file: %s, xrecoff: %s)",
  23. PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 1));
  24. }
  25. /* get filename from the result of pg_xlogfile_name_offset() */
  26. elog(DEBUG, "waiting for %s is archived", PQgetvalue(res, 0, 0));
  27. snprintf(ready_path, lengthof(ready_path),
  28. "%s/pg_xlog/archive_status/%s.ready", pgdata, PQgetvalue(res, 0, 0));
  29. PQclear(res);
  30. res = execute(TXID_CURRENT_SQL, 0, NULL);
  31. if(backup != NULL)
  32. {
  33. get_xid(res, &backup->recovery_xid);
  34. backup->recovery_time = time(NULL);
  35. }
  36. disconnect();
  37. /* wait until switched WAL is archived */
  38. try_count = 0;
  39. while (fileExists(ready_path))
  40. {
  41. sleep(1);
  42. if (interrupted)
  43. ereport(FATAL,
  44. (errcode(ERROR_INTERRUPTED),
  45. errmsg("interrupted during waiting for WAL archiving")));
  46. try_count++;
  47. if (try_count > TIMEOUT_ARCHIVE)
  48. ereport(ERROR,
  49. (errcode(ERROR_ARCHIVE_FAILED),
  50. errmsg("switched WAL could not be archived in %d seconds",
  51. TIMEOUT_ARCHIVE)));
  52. }
  53. elog(DEBUG, "WAL file contains backup end point is archived after %d seconds waiting",
  54. try_count);
  55. }

validate 时,改backup.ini的STATUS字段

  1. validate.c
  2. for (i = 0; i < parray_num(backup_list); i++)
  3. {
  4. pgBackup *backup = (pgBackup *)parray_get(backup_list, i);
  5. /* clean extra backups (switch STATUS to ERROR) */
  6. if(!another_pg_rman &&
  7. (backup->status == BACKUP_STATUS_RUNNING ||
  8. backup->status == BACKUP_STATUS_DELETING))
  9. {
  10. backup->status = BACKUP_STATUS_ERROR;
  11. pgBackupWriteIni(backup);
  12. }
  13. /* Validate completed backups only. */
  14. if (backup->status != BACKUP_STATUS_DONE)
  15. continue;
  16. /* validate with CRC value and update status to OK */
  17. pgBackupValidate(backup, false, false, (HAVE_DATABASE(backup)));
  18. }
  19. ...
  20. /* update status to OK */
  21. if (corrupted)
  22. backup->status = BACKUP_STATUS_CORRUPT;
  23. else
  24. backup->status = BACKUP_STATUS_OK;
  25. pgBackupWriteIni(backup);

注意

1.备份参数 -C 表示无缝checkpoint, 所以可能很慢,视checkpoint_completion_target和segment_size的配置。
如果你发现pg_rman开始很慢,可以把-C去掉,速度就快了,但是可能在高峰时,造成冲击。
建议高峰是不要备份。
2.BUG
unix socket 是$PGDATA时, validate会报错

  1. pg_rman validate
  2. INFO: validate: "2016-08-26 16:19:25" backup, archive log files and server log files by CRC
  3. ERROR: invalid type '?' found in "/data05/digoal/pgbak/20160826/161925/file_database.txt"
  4. vi /data05/digoal/pgbak/20160826/161925/file_database.txt
  5. .s.PGSQL.1921 ? 0 0 0777 2016-08-26 15:35:05

修改一下dir.c的代码即可修复这个问题,修改如下

  1. if (strncmp(path, ".s.PGSQL", 7) != 0 && type != 'f' && type != 'F' && type != 'd' && type != 'l')
  2. ereport(ERROR,
  3. errmsg("invalid type '%c' found in \"%s\"", type, file_txt)));

阿里云的小伙伴们加油,努力 做好内核与服务,打造最贴地气的云数据库