Created
May 24, 2024 08:35
-
-
Save pooza/2ba413562ac0fc0619b9e1bd4bd94d09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'date' | |
require 'pg' | |
# 設定 | |
TARGET = 'zroot/postgres' # 対象パーティション | |
DAYS = 7 # 保管する日数 | |
DSN = 'postgres://postgres@localhost/mastodon' # PG形式の接続文字列 | |
def snapshots(target = TARGET) | |
return `zfs list -t snapshot` | |
.each_line | |
.map {|line| line.split(/\s+/).first} | |
.select {|v| v.split('@').first == target} | |
.map do |name| | |
date = Date.parse(name.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)[0]) rescue nil | |
{name:, date:} | |
end | |
end | |
def clean(snapshots) | |
snapshots.each do |snapshot| | |
if snapshot[:date].nil? || snapshot[:date] < Date.today - DAYS | |
system "zfs destroy #{snapshot[:name]}" | |
puts "destroy snapshot: #{snapshot[:name]}" | |
end | |
end | |
end | |
def create_snapshot | |
name = "#{TARGET}@#{Time.now.strftime('%F_%T')}" | |
pg = PG::Connection.new(DSN) | |
pg.exec_params(%{SELECT * FROM pg_backup_start($1, false)}, [name]) | |
system "zfs snapshot #{name}" | |
puts "create snapshot: #{name}" | |
pg.exec(%{SELECT * FROM pg_backup_stop(true)}) | |
end | |
begin | |
clean(snapshots) | |
create_snapshot | |
rescue => e | |
warn e.message | |
exit 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment