Maintenance commands: doctor, records check, restore, sign out all, more

- sam:doctor: health report (secret key, address, HTTPS, SMTP and SSO
  reachable, Google Drive, migrations, disk, jobs, backup/check/off-site/
  procedures/audit recency); exits 1 on a failure
- records:check: backup now + history and signature check; exits 1 on a problem
- backups:list / backups:restore[file]: checks the copy (nightly or Drive
  .gz), refuses while the server runs, moves the current DB aside, asks
  (CONFIRM=yes to skip)
- users:sign_out_all, sam:records_package[tail], email:test[address],
  offsite:backup, offsite:restore_test
- Admin guide: maintenance commands table, restore steps use backups:restore

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 16:42:52 -05:00
1 parent 20fe485f10
commit 1412470cd5
11 files changed
+434 -11

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
require "zlib"
# Puts a database backup in place of the live database (bin/rails
# backups:restore), with the app stopped: a nightly copy from storage/backups,
# or a copy downloaded from Google Drive (.sqlite3.gz). The copy is checked
# first, and the current database is moved aside, never deleted.
class DatabaseRestore
class Error < StandardError; end
attr_reader :source, :target
def self.newest_backup = Dir[DatabaseBackup::DIR.join("sam-*.sqlite3")].max_by { File.mtime(_1) }
def self.live_database = File.expand_path(ActiveRecord::Base.connection_db_config.database.to_s, Rails.root)
def initialize(source: nil, target: self.class.live_database, pidfile: Rails.root.join("tmp/pids/server.pid"))
@pidfile = Pathname(pidfile)
@source = source.presence || self.class.newest_backup or raise Error, "No backup found in #{DatabaseBackup::DIR}; give a file: backups:restore[path]"
@target = File.expand_path(target.to_s, Rails.root)
raise Error, "#{@source} doesn't exist" unless File.file?(@source)
end
# Opens the copy (unzipping a .gz to a temporary file) and checks it.
# Returns a description; raises if it isn't a usable database.
def check
with_plain_copy { |path| describe(path) }
end
# Swaps the copy in. Returns the folder the previous database was moved to.
def restore!
raise Error, "The app seems to be running (#{running_reason}). Stop it first; with Docker: docker compose stop web, then docker compose run --rm web bin/rails backups:restore" if running_reason
with_plain_copy do |path|
describe(path)
ActiveRecord::Base.connection_handler.clear_all_connections! if @target == self.class.live_database
aside = File.join(File.dirname(@target), "pre-restore-#{Time.current.utc.strftime('%Y%m%d-%H%M%S')}")
FileUtils.mkdir_p(aside)
[ "", "-wal", "-shm" ].each { |ext| FileUtils.mv("#{@target}#{ext}", aside) if File.exist?("#{@target}#{ext}") }
FileUtils.cp(path, @target)
Rails.logger.warn("[restore] #{@target} replaced by #{@source}; previous database in #{aside}")
aside
end
end
private
def with_plain_copy
return yield(@source) unless @source.end_with?(".gz")
Dir.mktmpdir("sam-restore") do |dir|
path = File.join(dir, "restore.sqlite3")
Zlib::GzipReader.open(@source) { |gz| File.open(path, "wb") { IO.copy_stream(gz, _1) } }
yield path
end
rescue Zlib::GzipFile::Error => e
raise Error, "#{@source} isn't a valid .gz file (#{e.message})"
end
def describe(path)
db = SQLite3::Database.new(path, readonly: true)
result = db.get_first_value("PRAGMA integrity_check")
raise Error, "integrity check failed: #{result}" unless result == "ok"
counts = %w[aircraft logbook_entries entry_signatures users].to_h { [ _1, db.get_first_value("SELECT COUNT(*) FROM #{_1}") ] }
version = db.get_first_value("SELECT MAX(version) FROM schema_migrations")
"#{File.basename(@source)}: SQLite integrity check ok; #{counts['aircraft']} aircraft, #{counts['logbook_entries']} logbook entries, " \
"#{counts['entry_signatures']} signatures, #{counts['users']} users; schema #{version}"
rescue SQLite3::Exception => e
raise Error, "#{File.basename(@source)} isn't a usable database (#{e.message})"
ensure
db&.close
end
# A live server process (Puma's pid file) means the app is running.
def running_reason
return unless @pidfile.exist?
pid = @pidfile.read.to_i
Process.kill(0, pid) && "server process #{pid}" if pid.positive?
rescue Errno::ESRCH, Errno::EPERM
nil
end
end