Created
October 7, 2023 01:46
-
-
Save constantm/4a55d37668da999a6e6f5b35914221b2 to your computer and use it in GitHub Desktop.
DB Backup job
This file contains hidden or 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
require 'aws-sdk-s3' | |
require 'net/http' | |
require 'uri' | |
SENTRY_INGEST = 'https://XXXXXXXXXXXXXXXX.ingest.sentry.io' | |
SENTRY_CRONS = "#{SENTRY_INGEST}/api/XXXXXXXXXXXXXXXX/cron/daily-db-backup/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/" | |
class DatabaseBackupJob < ApplicationJob | |
queue_as :default | |
def perform | |
timestamp = Time.now.strftime('%Y%m%d%H%M%S') | |
backup_file = "tmp/db_backup_#{timestamp}.sql" | |
zipped_backup_file = "#{backup_file}.gz" | |
bucket = 'backups' | |
region = 'us-west-2' | |
begin | |
# 🟡 Notify Sentry your job is running | |
uri = URI.parse("#{SENTRY_CRONS}?status=in_progress") | |
Net::HTTP.get(uri) | |
# Backup the database | |
system "pg_dump --dbname=\"$DATABASE_URL\" > #{backup_file}" | |
# Zip the backup | |
system "gzip #{backup_file}" | |
# Upload to S3 | |
s3 = Aws::S3::Resource.new(region:, | |
access_key_id: ENV['S3_ACCESS_KEY'], | |
secret_access_key: ENV['S3_SECRET_KEY']) | |
obj = s3.bucket(bucket).object("db_backups/db_backup_#{timestamp}.sql.gz") | |
obj.upload_file(zipped_backup_file) | |
uri = URI.parse("#{SENTRY_CRONS}?status=ok") | |
Net::HTTP.get(uri) | |
rescue StandardError => e | |
Rails.logger.error "An error occurred while backing up DB: #{e.message}" | |
# 🔴 Notify Sentry your job has failed: | |
uri = URI.parse("#{SENTRY_CRONS}?status=error") | |
Net::HTTP.get(uri) | |
ensure | |
# Delete the local backup | |
File.delete(zipped_backup_file) if File.exist?(zipped_backup_file) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment