ops_backups 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c11d46d1083b3b1b45c330e4b74db480d82d80ebd49356a74934dd63409f2c01
4
+ data.tar.gz: d41344f6c9066beac9ba54ab9e96165fec31b33335b85af0ec26beebf2fba875
5
+ SHA512:
6
+ metadata.gz: 64d6bb17c0bc7e78cf236d4a2077aa3cbb0cf520576544e8b75c16a9745c19e1b2a4886ad548c8446ac6405f1e366c17873ac540a9ec641e98a45002cf5b4571
7
+ data.tar.gz: 93ba27887a32e0a361187ef94189c6a574849f65fe5542a0f09fe329c1bfb42121675258ed97a8ce9b85136a9634902028869eb9e945b7c4163307556e3b7150
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright Koen Handekyn
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # Ops
2
+
3
+ ## Description
4
+ Ops is a Ruby gem designed to enhance and to backup your PostgreSQL database.
5
+
6
+ ## Usage
7
+
8
+ ### Configuration
9
+
10
+ To configure the Ops gem, you need to set up the following environment variables:
11
+ - `DATABASE_URL`: The URL of the PostgreSQL database to backup.
12
+
13
+ Set up Active Storage for backups (e.g., Amazon S3 for production). We expect a service named `:backup_storage` to be configured.
14
+
15
+ ```yaml
16
+ backup_storage:
17
+ service: S3
18
+ access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
19
+ secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
20
+ region: <%= ENV['AWS_REGION'] %>
21
+ bucket: backups
22
+ ```
23
+ ### Backup Method
24
+
25
+ The `Ops::Backup` class provides a method to perform a PostgreSQL database backup:
26
+
27
+ - `db_pg_backup(exclude_tables: [], tag: nil)`: This method performs a full backup of the database, optionally excluding specified tables. The backup is tagged and saved as an attachment.
28
+
29
+ example:
30
+
31
+ ```ruby
32
+ Ops::Backup.new.db_pg_backup(exclude_tables: ["versions"], tag: "db_pg_unveresioned")
33
+ ```
34
+
35
+ ### Backup Retention Strategies
36
+
37
+ Ops gem provides two backup retention strategies:
38
+
39
+ 1. **Tiered Cleanup Policy**:
40
+ - Keeps all backups from the last day.
41
+ - Keeps the last backup of each day from the last week (except the last day).
42
+ - Keeps the last backup of each week from the last month (except the last week).
43
+ - Keeps the last backup of each month before the last month.
44
+
45
+ example:
46
+ ```ruby
47
+ Ops::CleanupTiered.new.cleanup("db_pg_unversioned")
48
+ ```
49
+
50
+ This policy can be applied using the `Ops::CleanupTieredJob`.
51
+
52
+ 2. **Limit Cleanup Policy**:
53
+ - Keeps the last N backups, where N is specified by the `limit` parameter.
54
+
55
+ example:
56
+ ```ruby
57
+ Ops::CleanupLimit.new.cleanup("db_pg_unversioned", limit: 14)
58
+ ```
59
+
60
+ This policy can be applied using the `Ops::CleanupLimitJob`.
61
+
62
+ ### Using SolidQueue Schedule
63
+
64
+ 1. Schedule the backup job using SolidQueue:
65
+ ```ruby
66
+ SolidQueue.schedule(Ops::BackupDbJob.new, cron: '0 0 * * *', args: { tag: "db_pg_full", exclude_tables: [], cleanup: "retain_last_limit" }) # This schedules the backup job to run daily at midnight
67
+ ```
68
+
69
+ 2. Schedule the cleanup job with a tiered policy:
70
+ ```ruby
71
+ SolidQueue.schedule(Ops::CleanupTieredJob.new, cron: '0 1 * * *', args: { tag: "db_pg_full" }) # This schedules the tiered cleanup job to run daily at 1 AM
72
+ ```
73
+
74
+ 3. Schedule the cleanup job with a limit policy:
75
+ ```ruby
76
+ SolidQueue.schedule(Ops::CleanupLimitJob.new, cron: '0 2 * * *', args: { tag: "db_pg_full", limit: 14 }) # This schedules the limit cleanup job to run daily at 2 AM
77
+ ```
78
+
79
+ ### Using `recurring.yml` from SolidQueue
80
+
81
+ Alternatively, you can configure recurring tasks using `recurring.yml` in your SolidQueue configuration:
82
+
83
+ 1. Create or update the `recurring.yml` file in your application's config directory:
84
+ ```yaml
85
+ # filepath: config/recurring.yml
86
+ backup_db_job:
87
+ cron: "0 0 * * *"
88
+ class: "Ops::BackupDbJob"
89
+ args:
90
+ tag: "db_pg_full"
91
+ exclude_tables: []
92
+ cleanup: "retain_last_limit"
93
+
94
+ cleanup_tiered_job:
95
+ cron: "0 1 * * *"
96
+ class: "Ops::CleanupTieredJob"
97
+ args:
98
+ tag: "db_pg_full"
99
+
100
+ cleanup_limit_job:
101
+ cron: "0 2 * * *"
102
+ class: "Ops::CleanupLimitJob"
103
+ args:
104
+ tag: "db_pg_full"
105
+ limit: 14
106
+ ```
107
+
108
+
109
+
110
+ ## Installation
111
+ Add this line to your application's Gemfile:
112
+
113
+ ```ruby
114
+ gem "ops"
115
+ ```
116
+
117
+ And then execute:
118
+ ```bash
119
+ $ bundle
120
+ ```
121
+
122
+ Or install it yourself as:
123
+ ```bash
124
+ $ gem install ops
125
+ ```
126
+
127
+ ## Contributing
128
+
129
+ Bug reports and pull requests are welcome on GitHub at https://github.com/koenhandekyn/ops.
130
+
131
+ ## License
132
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "bundler/setup"
2
+
3
+ APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__)
4
+ load "rails/tasks/engine.rake"
5
+
6
+ load "rails/tasks/statistics.rake"
7
+
8
+ require "bundler/gem_tasks"
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10
+ * files in this directory. Styles in this file should be added after the last require_* statement.
11
+ * It is generally better to create a new file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,6 @@
1
+ module Ops
2
+ module Backups
3
+ class ApplicationController < ActionController::Base
4
+ end
5
+ end
6
+ end
@@ -0,0 +1,4 @@
1
+ module Ops
2
+ module ApplicationHelper
3
+ end
4
+ end
@@ -0,0 +1,6 @@
1
+ module Ops
2
+ module Backups
3
+ class ApplicationJob < ActiveJob::Base
4
+ end
5
+ end
6
+ end
@@ -0,0 +1,15 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ class Ops::Backups::BackupDbJob < ApplicationJob
5
+ queue_as :operations
6
+
7
+ # perform a full backup of the database
8
+ # @param tag [String] the tag to assign to the backup
9
+ # @param exclude_tables [Array<String>] the list of tables to exclude from the backup
10
+ # @param cleanup_policy [String] the cleanup policy to apply to the backup, one of "retain_tiered_cleanup_policy" or "retain_last_limit_cleanup_policy"
11
+ def perform(tag: "db_pg_full", exclude_tables: [], cleanup: nil)
12
+ Ops::Backup.new.db_pg_backup(tag:, exclude_tables:)
13
+ Ops::Backup.send("#{cleanup}_cleanup_policy", tag: tag) if cleanup.present?
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Cleanup job for limit backup policy
4
+ class Ops::Backups::CleanupLimitJob < ApplicationJob
5
+ queue_as :operations
6
+
7
+ # @param [String] tag
8
+ # @param [Integer] limit
9
+ # @return [void]
10
+ #
11
+ # @example Tasks::CleanupLimit.perform_now(tag: "db_pg_full", limit: 14)
12
+ def perform(tag: "db_pg_full", limit: 14)
13
+ Ops::Backup.retain_last_limit_cleanup_policy(tag: tag, limit: limit)
14
+ end
15
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Cleanup job for tiered backup policy
4
+ class Ops::Backups::CleanupTieredJob < ApplicationJob
5
+ queue_as :operations
6
+
7
+ # @param [String] tag
8
+ # @return [void]
9
+ #
10
+ # @example Tasks::CleanupTiered.perform_now(tag: "db_pg_full")
11
+ def perform(tag: "db_pg_full")
12
+ Ops::Backup.retain_tiered_cleanup_policy(tag: tag)
13
+ end
14
+ end
@@ -0,0 +1,8 @@
1
+ module Ops
2
+ module Backups
3
+ class ApplicationRecord < ActiveRecord::Base
4
+ self.abstract_class = true
5
+ self.table_name_prefix = "ops_"
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,71 @@
1
+ module Ops
2
+ puts "Ops module loaded"
3
+
4
+ class Ops::Backups::Backup < ApplicationRecord
5
+ # has_one_attached :backup_file, service: :backup_storage
6
+ has_one_attached :backup_file
7
+
8
+ default_scope { order(updated_at: :desc) }
9
+
10
+ def db_pg_backup(exclude_tables: [], tag: nil)
11
+ tag ||= exclude_tables.empty? ? "db_pg_full" : "db_pg_partial"
12
+ Rails.logger.info("Backing up database, skipping tables: \#{exclude_tables.join(", ")}")
13
+ db_url = ENV["DATABASE_URL"]
14
+ self.tag = tag
15
+ self.name = filename = "pg_\#{db_url.split('/').last}_backup_\#{Time.now.to_i}.dump"
16
+ save!
17
+
18
+ Tempfile.new("pgbackup") do |tempfile|
19
+ begin
20
+ excluded_tables_param = exclude_tables.map { |table| "--exclude-table-data=\#{table}" }.join(" ")
21
+ command = ["pg_dump", "--no-owner", excluded_tables_param, "-v", "-Fc", "-f", tempfile.path, db_url]
22
+
23
+ stdout, stderr, status = Open3.capture3(*command)
24
+
25
+ if status.success?
26
+ Rails.logger.info("PgBackup successful: #{stdout}")
27
+ backup_file.attach io: File.open(tempfile.path), filename:, content_type: "application/octet-stream"
28
+ else
29
+ error_message = "PgBackup failed: #{stderr.strip}"
30
+ Rails.logger.error(error_message)
31
+ raise "PgBackup command failed: #{error_message}"
32
+ end
33
+ rescue StandardError => e
34
+ Rails.logger.error("Failed to backup database: \#{e.message}")
35
+ raise
36
+ end
37
+ end
38
+ end
39
+ end
40
+
41
+ # Keep all the backups of the last day
42
+ # Keep the last backup of each day in the last week (except the last day)
43
+ # Keep the last backup of each week in the last month (except the last week)
44
+ # Keep the last backup of each month before the last month
45
+ def self.retain_tiered_cleanup_policy(tag: "")
46
+ week = where(created_at: 1.week.ago..1.day.ago)
47
+ .group_by { |b| b.created_at.to_date }
48
+ month = where(created_at: 1.month.ago..1.week.ago)
49
+ .group_by { |b| b.created_at.beginning_of_week }
50
+ older = where(created_at: 1.year.ago..1.month.ago)
51
+ .group_by { |b| b.created_at.beginning_of_month }
52
+
53
+ backups = week.merge(month).merge(older)
54
+
55
+ ids = backups.flat_map do |_, group|
56
+ group.sort_by(&:created_at).reverse.drop(1).pluck(:id)
57
+ end
58
+
59
+ records = where(id: ids)
60
+ records = records.where(tag: tag) if tag.present?
61
+ records.destroy_all
62
+ end
63
+
64
+ # Keep the last 14 backups
65
+ def self.retain_last_limit_cleanup_policy(limit: 14, tag: "")
66
+ records = all
67
+ records = records.where(tag: tag) if tag.present?
68
+ records = records.order(updated_at: :desc).offset(limit)
69
+ records.destroy_all
70
+ end
71
+ end
@@ -0,0 +1,17 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Ops</title>
5
+ <%= csrf_meta_tags %>
6
+ <%= csp_meta_tag %>
7
+
8
+ <%= yield :head %>
9
+
10
+ <%= stylesheet_link_tag "ops/application", media: "all" %>
11
+ </head>
12
+ <body>
13
+
14
+ <%= yield %>
15
+
16
+ </body>
17
+ </html>
data/config/routes.rb ADDED
@@ -0,0 +1,2 @@
1
+ Ops::Backups::Engine.routes.draw do
2
+ end
@@ -0,0 +1,10 @@
1
+ class CreateOpsBackups < ActiveRecord::Migration[8.0]
2
+ def change
3
+ create_table :ops_backups do |t|
4
+ t.string :name, null: false
5
+ t.string :tag, null: false
6
+
7
+ t.timestamps
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,8 @@
1
+ require "ops/backups/version"
2
+ require "ops/backups/engine"
3
+
4
+ module Ops
5
+ module Backups
6
+ # Your code goes here...
7
+ end
8
+ end
@@ -0,0 +1,7 @@
1
+ module Ops
2
+ module Backups
3
+ class Engine < ::Rails::Engine
4
+ isolate_namespace Ops::Backups
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,5 @@
1
+ module Ops
2
+ module Backups
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :ops do
3
+ # # Task goes here
4
+ # end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ops_backups
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Koen Handekyn
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-11-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6'
27
+ description: This gem provides functionality to backup PostgreSQL databases to ActiveStorage
28
+ (S3) from within a Rails context.
29
+ email:
30
+ - github.com@handekyn.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - MIT-LICENSE
36
+ - README.md
37
+ - Rakefile
38
+ - app/assets/stylesheets/ops/application.css
39
+ - app/controllers/ops/backups/application_controller.rb
40
+ - app/helpers/ops/application_helper.rb
41
+ - app/jobs/ops/backups/application_job.rb
42
+ - app/jobs/ops/backups/backup_db_job.rb
43
+ - app/jobs/ops/backups/cleanup_limit_job.rb
44
+ - app/jobs/ops/backups/cleanup_tiered_job.rb
45
+ - app/models/ops/backups/application_record.rb
46
+ - app/models/ops/backups/backup.rb
47
+ - app/views/layouts/ops/application.html.erb
48
+ - config/routes.rb
49
+ - db/migrate/20241114173612_create_ops_backups.rb
50
+ - lib/ops/backups/backups.rb
51
+ - lib/ops/backups/engine.rb
52
+ - lib/ops/backups/version.rb
53
+ - lib/tasks/ops_tasks.rake
54
+ homepage: https://github.com/koenhandekyn/ops-backups
55
+ licenses:
56
+ - MIT
57
+ metadata:
58
+ homepage_uri: https://github.com/koenhandekyn/ops-backups
59
+ source_code_uri: https://github.com/koenhandekyn/ops-backups/tree/main
60
+ changelog_uri: https://github.com/koenhandekyn/ops-backups/blob/main/CHANGELOG.md
61
+ post_install_message:
62
+ rdoc_options: []
63
+ require_paths:
64
+ - lib
65
+ required_ruby_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 3.0.0
70
+ required_rubygems_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ requirements: []
76
+ rubygems_version: 3.5.22
77
+ signing_key:
78
+ specification_version: 4
79
+ summary: A Ruby gem for managing PostgreSQL backups.
80
+ test_files: []