6 changed files with 81 additions and 1 deletions
@ -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 |
|||
@ -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 |
|||
@ -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 |
|||
@ -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…
Reference in new issue