pg_archivecleanup 和 pg_rewind 是pg 中兩個重要的功能,一個是為了清理過期的 archive log 使用的命令,另一個是你可以理解為物理級別的 wal log的搬運工。
我們先說第一個 pg_archivecleanup 命令,這個命令主要是用于使用了archive log 功能的 postgresql 但在 archive log 堆積如山的情況下,你怎么來根據某些規則,清理這些日志呢?
這里面就要使用 pg_archivecleanup 這個命令了,可以定時的來運行它,將已經移動到archivecleanup 的目錄的archivelog 根據要求開始清理。
當然我們先的說說如果不定期清理會出什么問題
1 如果不定期清理archive 如果存放archivelog 的位置無法在接受新的日志,則大量wal日志會滯留在 wal_log 目錄中,則整體數據庫系統都會受到影響。
2 占用大量的存儲空間,存儲無效的數據
那一般來說如果沒有第三方的備份工具的情況下,怎么來通過pg_archivecleanup 來進行archivelog 的清理。
需要關注幾個點
1 清理的時,清理的wal_log 是否已經是包含在最后一次的備份中,保證清理的wal_log 也可以從備份文件中恢復數據庫
2 清理的時候,對于保存在非主庫的wal_log 怎么辦
一般來說,設置自動清理archive_log 可以在配置文件中添加
1
|
archive_cleanup_command = 'pg_archivecleanup archivelocation %r' |
來操作。
但一般來說這樣做好處少,弊病多,我比較喜歡寫相關的腳本,定時去運行的方式,并且可以記錄相關的log 日志等等。
可以寫一個腳本,來輔助定時清理相關的archive_log
當然這樣的方法也是有弊端的,如果由于備份的原因的故障,而直接使用天數來清理會有因為沒有備份而直接將 wal_log 給清理掉,所以更加靠譜的方法是通過某些命令來獲得需要截止的清理的wal_log 名稱。
例如 備份后的
會在wal_log 里面有backup 的標記,這說明這個wal log 以前的數據已經備份了,如果清理這個wal log 之前的log 是安全的。
1
|
000000010000000300000030.00000060.backup |
使用下面的腳本可以來更安全的清理
1
2
3
4
5
6
|
#!/bin/bash archivedir= '/pgdata/archive' chk_safe=$(find $archivedir -type f -mtime +3 - name '*backup' -printf '%f\n' | sort -r | head -1) cd $archivedir /usr/ local /postgres/bin/pg_archivecleanup $archivedir $chk_safe find $archivedir -type f -mtime +3 -a - name '*backup' -a ! -newer $chkpoint - delete |
補充:postgresql流日志誤刪處理(xlog)
今天同事誤刪postgresql庫數據文件下的pg_xlog文件夾,導致所有流日志丟失,數據庫無法啟動,觀察警告日志:
1
2
3
4
5
6
7
8
|
2018-03-12 18:45:54 cst log: database system shutdown was interrupted; last known up at 2018-03-12 17:48:27 cst 2018-03-12 18:45:54 cst log: could not open file "pg_xlog/000000010000001400000060" (log file 20, segment 96): no such file or directory 2018-03-12 18:45:54 cst log: invalid primary checkpoint record 2018-03-12 18:45:54 cst log: could not open file "pg_xlog/000000010000001400000060" (log file 20, segment 96): no such file or directory 2018-03-12 18:45:54 cst log: invalid secondary checkpoint record 2018-03-12 18:45:54 cst panic: could not locate a valid checkpoint record 2018-03-12 18:45:54 cst log: startup process (pid 32680) was terminated by signal 6: aborted 2018-03-12 18:45:54 cst log: aborting startup due to startup process failure |
用postgresql自帶的pg_resetxlog工具可以跳過對wal log的恢復。不過會丟失一些事務。恢復命令也很簡單如下:
1
|
pg_resetxlog -f /var/lib/pgsql/9.6/data |
然后啟動postgrsql ,數據庫就可正常進入
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/liuhuayang/article/details/106682045