Browse Source

add db dump

main
Christoph Marzell 1 month ago
parent
commit
86c31fcf9b
  1. 1
      Gemfile
  2. 9
      Gemfile.lock
  3. 14
      app/jobs/daily_dump_job.rb
  4. 13
      app/mailers/dump_mailer.rb
  5. 31
      app/services/dump_service.rb
  6. 12
      config/initializers/dump_scheduler.rb

1
Gemfile

@ -49,3 +49,4 @@ group :development do
end
gem 'devise'
gem 'rufus-scheduler'

9
Gemfile.lock

@ -108,6 +108,11 @@ GEM
erb (4.0.4)
cgi (>= 0.3.3)
erubi (1.13.1)
et-orbi (1.4.0)
tzinfo
fugit (1.12.1)
et-orbi (~> 1.4)
raabro (~> 1.4)
globalid (1.3.0)
activesupport (>= 6.1)
i18n (1.14.7)
@ -172,6 +177,7 @@ GEM
stringio
puma (7.1.0)
nio4r (~> 2.0)
raabro (1.4.0)
racc (1.8.1)
rack (3.2.4)
rack-session (2.1.1)
@ -222,6 +228,8 @@ GEM
responders (3.2.0)
actionpack (>= 7.0)
railties (>= 7.0)
rufus-scheduler (3.9.2)
fugit (~> 1.1, >= 1.11.1)
securerandom (0.3.2)
sprockets (4.2.2)
concurrent-ruby (~> 1.0)
@ -267,6 +275,7 @@ DEPENDENCIES
pg (~> 1.1)
puma (>= 5.0)
rails (~> 7.1.5, >= 7.1.5.2)
rufus-scheduler
sprockets-rails
turbolinks (~> 5)
tzinfo-data

14
app/jobs/daily_dump_job.rb

@ -0,0 +1,14 @@
# app/jobs/daily_dump_job.rb
class DailyDumpJob < ApplicationJob
queue_as :default
def perform
zip_path = DumpService.perform
if zip_path
DumpMailer.daily_dump(zip_path).deliver_now
File.delete(zip_path) if File.exist?(zip_path)
else
Rails.logger.error "[DailyDumpJob] Dump fehlgeschlagen."
end
end
end

13
app/mailers/dump_mailer.rb

@ -0,0 +1,13 @@
class DumpMailer < ApplicationMailer
default from: "paktikum@marzell.net"
def daily_dump(zip_path)
attachments[File.basename(zip_path)] = File.read(zip_path)
mail(
to: "christoph@marzell.net",
subject: "📦 Täglicher SQL Dump"
) do |format|
format.text { render plain: "Dump im Anhang." }
end
end
end

31
app/services/dump_service.rb

@ -0,0 +1,31 @@
# app/services/dump_service.rb
class DumpService
def self.perform
timestamp = Time.current.strftime("%Y%m%d_%H%M%S")
filename = "dump_#{timestamp}.sql"
filepath = Rails.root.join("tmp", filename)
db_config = ActiveRecord::Base.connection_db_config.configuration_hash
ENV["PGPASSWORD"] = db_config[:password].to_s
cmd = [
"pg_dump",
"-U", db_config[:username].to_s,
"-h", (db_config[:host] || "localhost").to_s,
"-p", (db_config[:port] || 5432).to_s,
db_config[:database].to_s,
"-f", filepath.to_s
]
success = system(*cmd)
ENV["PGPASSWORD"] = nil
return nil unless success
zip_path = "#{filepath}.zip"
`zip -j #{zip_path} #{filepath}`
File.delete(filepath) if File.exist?(filepath)
zip_path
end
end

12
config/initializers/dump_scheduler.rb

@ -0,0 +1,12 @@
# config/initializers/dump_scheduler.rb
require 'rufus-scheduler'
return unless Rails.env.production? || Rails.env.development?
scheduler = Rufus::Scheduler.singleton
scheduler.cron '0 2 * * *' do
Rails.logger.info "[Scheduler] Starte täglichen Dump-Versand"
DailyDumpJob.perform_later
end
Loading…
Cancel
Save