copy_bot 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7b2ad280edebcf3bc0d1161562843dbfac9a11d2a5f6988c7b85379fbab7fec6
4
+ data.tar.gz: 0d1d7d715306c770a4e5aa448428b8ba10ae3f0fd5e2a91312d60c5b9c1ddb39
5
+ SHA512:
6
+ metadata.gz: 58db3aa615b6c86a88fb6c98a0bbdbbf548a8bfa3bb8e9d14645b727f9719505e76d685f11ed52cefaf394d8627de34cdde52f2eb0df354b767a3617a86a7e32
7
+ data.tar.gz: 5ea92339041eb75bccb8341d2d9417af2644471408eae64f703f03f99b03c3480eb63d38bf2a7fd9d5e1461a700460bb65c2700e2005322b4e019c3c006107e2
@@ -0,0 +1,28 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+
6
+ jobs:
7
+ lint:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - uses: actions/checkout@v2
11
+ - name: Set up Ruby
12
+ uses: ruby/setup-ruby@v1
13
+ with:
14
+ ruby-version: '3.0.1'
15
+ bundler-cache: true
16
+ - name: Run rubocop
17
+ run: bundle exec rubocop
18
+ test:
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v2
22
+ - name: Set up Ruby
23
+ uses: ruby/setup-ruby@v1
24
+ with:
25
+ ruby-version: '3.0.1'
26
+ bundler-cache: true
27
+ - name: Run specs
28
+ run: bundle exec rspec
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,16 @@
1
+ inherit_gem:
2
+ rubocop-infinum: rubocop.yml
3
+
4
+ require: rubocop-infinum
5
+
6
+ AllCops:
7
+ TargetRubyVersion: 3.0.1
8
+
9
+ RSpec/MultipleExpectations:
10
+ Max: 5
11
+
12
+ RSpec/ExampleLength:
13
+ Max: 15
14
+
15
+ Style/FrozenStringLiteralComment:
16
+ Enabled: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.0.1
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-02-26
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at eva.cukor@infinum.hr. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in copy_bot.gemspec
6
+ gemspec
data/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # CopyBot
2
+
3
+ A gem that provides a rake task for importing a database dump into the local database,
4
+ as well as for running any additional scripts afterwards.
5
+
6
+ This can be useful in situations when you want to sync your staging and production data so that you can debug issues
7
+ in production without having to access the production environment itself. Also, it is useful for populating
8
+ a database with production data so development and testing can be performed in circumstances that are as close to
9
+ production as possible. It is advised that the production data is anonymized beforehand.
10
+
11
+ The gem assumes that the database dump that is to be restored to the local database has already been prepared and
12
+ made available either on an AWS S3 bucket or on a local path.
13
+
14
+ ## Requirements
15
+
16
+ * `aws-sdk-ruby`
17
+ * `rails`
18
+
19
+ ## Supported databases
20
+
21
+ * PostgreSQL
22
+
23
+ ## Installation
24
+
25
+ Add this line to your application's Gemfile:
26
+
27
+ ```ruby
28
+
29
+ gem 'copy_bot'
30
+
31
+ ```
32
+
33
+ And then execute:
34
+
35
+ $ bundle install
36
+
37
+ Or install it yourself as:
38
+
39
+ $ gem install copy_bot
40
+
41
+ ## Application configuration
42
+
43
+ Add `config/initializers/copy_bot.rb`
44
+
45
+ ```ruby
46
+
47
+ CopyBot.setup do |config|
48
+ config.logger = Rails.logger
49
+ config.permitted_environments = ['development', 'staging']
50
+ end
51
+
52
+ ```
53
+ | Option | Default value | Description |
54
+ |--------------------------|:----------------------------:|----------------------------------------------------------------------------------------------------------|
55
+ | `logger` | Ruby's built-in Logger class | Logging utility that by default outputs to $stdout |
56
+ | `permitted_environments` | `['development']` | Array with environments where the rake task is allowed to be run (since it contains destructive actions) |
57
+
58
+ ### Step definitions file
59
+
60
+ It is necessary to define steps that should be run in a .yml file:
61
+
62
+ ```yml
63
+ steps:
64
+ download_remote_db_dump:
65
+ s3_credentials:
66
+ access_key_id: <%= Rails.application.secrets.aws_access_key_id %>
67
+ access_key: <%= Rails.application.secrets.aws_secret_access_key %>
68
+ region: <%= Rails.application.secrets.aws_region %>
69
+ bucket: <%= Rails.application.secrets.aws_s3_bucket %>
70
+ source_file_path: '/staging_db_dump.sql'
71
+ destination_file_path: './tmp/downloaded_db_dump.sql'
72
+ create_local_db_backup:
73
+ destination_file_path: './tmp/development_backup.sql'
74
+ drop_local_db_tables:
75
+ import_remote_db_to_local_db:
76
+ remote_db_dump_file_path: './tmp/downloaded_db_dump.sql'
77
+ run_migrations_on_local_db:
78
+ delete_remote_db_dump:
79
+ remote_db_dump_file_path: './tmp/downloaded_db_dump.sql'
80
+ execute_custom_command:
81
+ command: 'RAILS_ENV=staging bundle exec rake some_task'
82
+ ```
83
+
84
+ The example above contains all possible steps in the exact order in which they are run.
85
+ Not all steps are mandatory.
86
+ If a certain step doesn't need to be run, just omit it from the steps definition file. For example, you may not want
87
+ to download the database dump from an S3 bucket, but you have acquired it in some other way and you have it available
88
+ locally. In that case, omit the `download_remote_db_dump` step and add the relevant `remote_db_dump_file_path` to the
89
+ `import_remote_db_to_local_db` step.
90
+
91
+ **IMPORTANT:**
92
+ These steps include some destructive actions, e.g. `drop_local_db_tables` will drop all tables in the local database
93
+ so make sure you don't use this gem in an environment where you do not want to lose data.
94
+
95
+ ## Usage
96
+
97
+ To use the gem, simply run:
98
+
99
+ $ bundle exec rake copy_bot STEP_DEFINITIONS_FILE_PATH=config/copy_bot/step_definitions.yml
100
+
101
+ Please note that the step definitions file is passed to the rake task as an environment variable, not an argument.
102
+
103
+ ## Development
104
+
105
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests.
106
+ You can also run `bin/console` for an interactive prompt that will allow you to experiment.
107
+
108
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update
109
+ the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for
110
+ the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
111
+
112
+ ## Contributing
113
+
114
+ Bug reports and pull requests are welcome on GitHub at https://github.com/infinum/copy_bot. This project is intended
115
+ to be a safe, welcoming space for collaboration, and contributors are expected to adhere to
116
+ the [code of conduct](https://github.com/infinum/copy_bot/blob/master/CODE_OF_CONDUCT.md).
117
+
118
+ ## License
119
+
120
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
121
+
122
+ ## Code of Conduct
123
+
124
+ Everyone interacting in the CopyBot project's codebases, issue trackers, chat rooms and mailing lists is expected
125
+ to follow the [code of conduct](https://github.com/infinum/copy_bot/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
data/bin/console ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'copy_bot'
5
+
6
+ require 'pry'
7
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/copy_bot.gemspec ADDED
@@ -0,0 +1,41 @@
1
+ require_relative 'lib/copy_bot/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = 'copy_bot'
5
+ spec.version = CopyBot::VERSION
6
+ spec.authors = ['Rails Team']
7
+ spec.email = ['team.rails@infinum.com']
8
+
9
+ spec.summary = 'Tool for syncing data between two environments.'
10
+ spec.description = 'Provides a rake task for importing a database dump into a database on a particular environment.'
11
+ spec.homepage = 'https://github.com/infinum/copy_bot'
12
+ spec.license = 'MIT'
13
+ spec.required_ruby_version = Gem::Requirement.new('>= 3.0.1')
14
+
15
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = spec.homepage
19
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ # Uncomment to register a new dependency of your gem
31
+ spec.add_dependency 'aws-sdk-s3'
32
+ spec.add_dependency 'rails', '>= 6.1'
33
+
34
+ spec.add_development_dependency 'pry'
35
+ spec.add_development_dependency 'rspec'
36
+ spec.add_development_dependency 'rubocop-infinum'
37
+
38
+ # For more information and examples about making a new gem, check out our
39
+ # guide at: https://bundler.io/guides/creating_gem.html
40
+ spec.metadata['rubygems_mfa_required'] = 'true'
41
+ end
@@ -0,0 +1,24 @@
1
+ module CopyBot
2
+ class Config
3
+ # @return [Logger]
4
+ attr_accessor :logger
5
+
6
+ # @return [Array<String>]
7
+ attr_accessor :permitted_environments
8
+
9
+ DEFAULT_PERMITTED_ENVIRONMENTS = ['development'].freeze
10
+
11
+ def initialize
12
+ @logger = default_logger
13
+ @permitted_environments = DEFAULT_PERMITTED_ENVIRONMENTS
14
+ end
15
+
16
+ private
17
+
18
+ def default_logger
19
+ Logger.new($stdout).tap do |log|
20
+ log.progname = self.class.name.split('::').first
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,8 @@
1
+ module CopyBot
2
+ class Railtie < Rails::Railtie
3
+ rake_tasks do
4
+ path = File.expand_path(__dir__)
5
+ Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f }
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,21 @@
1
+ module CopyBot
2
+ class ShellCommand
3
+ # @param [String] command
4
+ def initialize(command)
5
+ @command = command
6
+ end
7
+
8
+ # @return [FalseClass, TrueClass]
9
+ def execute
10
+ stdout, stderr, status = Open3.capture3(command)
11
+ return true if status.exitstatus&.zero?
12
+
13
+ CopyBot.config.logger.debug { "#{stdout}, #{stderr}" }
14
+ false
15
+ end
16
+
17
+ private
18
+
19
+ attr_reader :command
20
+ end
21
+ end
@@ -0,0 +1,22 @@
1
+ module CopyBot
2
+ class StepDefinitions
3
+ # @return [Hash]
4
+ attr_reader :loaded_step_definitions
5
+
6
+ def initialize
7
+ @loaded_step_definitions = {}
8
+ end
9
+
10
+ # @param [String] step_definitions_file_path
11
+ # @return [Hash]
12
+ def load_step_definitions_file(step_definitions_file_path)
13
+ @loaded_step_definitions = YAML.safe_load(ERB.new(File.read(step_definitions_file_path)).result)
14
+ .deep_symbolize_keys
15
+ end
16
+
17
+ # @return [Hash]
18
+ def steps
19
+ loaded_step_definitions[:steps]
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,32 @@
1
+ module CopyBot
2
+ class StepFactory
3
+ attr_reader :step_name
4
+
5
+ # @param [Symbol] step_name
6
+ def initialize(step_name)
7
+ @step_name = step_name
8
+ end
9
+
10
+ # @return [Class<CopyBot::Steps::BaseStep>]
11
+ def build # rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity
12
+ case step_name
13
+ when :download_remote_db_dump
14
+ ::CopyBot::Steps::DownloadRemoteDbDump
15
+ when :create_local_db_backup
16
+ ::CopyBot::Steps::CreateLocalDbBackup
17
+ when :drop_local_db_tables
18
+ ::CopyBot::Steps::DropLocalDbTables
19
+ when :import_remote_db_to_local_db
20
+ ::CopyBot::Steps::ImportRemoteDbToLocalDb
21
+ when :run_migrations_on_local_db
22
+ ::CopyBot::Steps::RunMigrationsOnLocalDb
23
+ when :delete_remote_db_dump
24
+ ::CopyBot::Steps::DeleteRemoteDbDump
25
+ when :execute_custom_command
26
+ ::CopyBot::Steps::ExecuteCustomCommand
27
+ else
28
+ raise ArgumentError
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,38 @@
1
+ module CopyBot
2
+ class StepRunner
3
+ # @param [String] step_name
4
+ def initialize(step_name)
5
+ @step_name = step_name.to_sym
6
+ end
7
+
8
+ # @return [FalseClass, TrueClass]
9
+ def call # rubocop:disable Metrics/AbcSize
10
+ logger.info("Started step: #{step_name}")
11
+
12
+ step.run
13
+
14
+ step.success ? logger.info(step.message) : logger.debug(step.message)
15
+ step.success
16
+ end
17
+
18
+ private
19
+
20
+ attr_reader :step_name
21
+
22
+ def logger
23
+ CopyBot.config.logger
24
+ end
25
+
26
+ def step
27
+ @step ||= step_class.new(step_definition)
28
+ end
29
+
30
+ def step_definition
31
+ CopyBot.step_definitions.steps[step_name]
32
+ end
33
+
34
+ def step_class
35
+ CopyBot::StepFactory.new(step_name).build
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,31 @@
1
+ module CopyBot
2
+ module Steps
3
+ class BaseStep
4
+ # @param [String]
5
+ attr_reader :message
6
+
7
+ # @return [FalseClass, TrueClass]
8
+ attr_reader :success
9
+
10
+ # @param [Hash] step_definition
11
+ def initialize(step_definition)
12
+ @step_definition = step_definition
13
+ @message = nil
14
+ @success = false
15
+ end
16
+
17
+ # @raise [NotImplementedError]
18
+ def run
19
+ raise NotImplementedError
20
+ end
21
+
22
+ private
23
+
24
+ attr_reader :step_definition
25
+
26
+ def step_name
27
+ self.class.name.demodulize.underscore
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,26 @@
1
+ module CopyBot
2
+ module Steps
3
+ class CreateLocalDbBackup < BaseStep
4
+ # @return [String]
5
+ def run
6
+ @success = CopyBot::ShellCommand.new(command).execute
7
+ @message = @success ? 'Created backup of local DB.' : 'Local DB backup creation failed.'
8
+ end
9
+
10
+ private
11
+
12
+ def command
13
+ "PGPASSWORD=#{db_conn_config[:password]} pg_dump -U #{db_conn_config[:username]} -h #{db_conn_config[:host]}" \
14
+ " -p #{db_conn_config[:port]} #{db_conn_config[:database]} > #{destination_file_path}"
15
+ end
16
+
17
+ def db_conn_config
18
+ ActiveRecord::Base.connection_db_config.configuration_hash
19
+ end
20
+
21
+ def destination_file_path
22
+ step_definition[:destination_file_path]
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,24 @@
1
+ module CopyBot
2
+ module Steps
3
+ class DeleteRemoteDbDump < BaseStep
4
+ # @return [String]
5
+ def run
6
+ return @message = 'Missing remote DB dump file' unless remote_db_dump_file_valid?
7
+
8
+ File.delete(remote_db_dump_file_path)
9
+ @success = true
10
+ @message = "Deleted file #{remote_db_dump_file_path}"
11
+ end
12
+
13
+ private
14
+
15
+ def remote_db_dump_file_valid?
16
+ remote_db_dump_file_path && File.exist?(remote_db_dump_file_path)
17
+ end
18
+
19
+ def remote_db_dump_file_path
20
+ step_definition[:remote_db_dump_file_path]
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,47 @@
1
+ module CopyBot
2
+ module Steps
3
+ class DownloadRemoteDbDump < BaseStep
4
+ # @return [String]
5
+ def run
6
+ return @message = 'Missing S3 credentials in config' unless s3_credentials
7
+
8
+ @success = source_object.download_file(destination_file_path)
9
+ @message = @success ? successful_download_message : 'Remote DB dump download failed.'
10
+ end
11
+
12
+ private
13
+
14
+ def s3_credentials
15
+ step_definition[:s3_credentials]
16
+ end
17
+
18
+ def source_object
19
+ s3_resource.bucket(s3_credentials[:bucket]).object(source_file_path)
20
+ end
21
+
22
+ def s3_resource
23
+ Aws::S3::Resource.new(client: s3_client)
24
+ end
25
+
26
+ def s3_client
27
+ Aws::S3::Client.new(region: s3_credentials[:region], credentials: aws_credentials)
28
+ end
29
+
30
+ def aws_credentials
31
+ Aws::Credentials.new(s3_credentials[:access_key_id], s3_credentials[:access_key])
32
+ end
33
+
34
+ def successful_download_message
35
+ "s3://#{s3_credentials[:bucket]}/#{source_file_path} has been downloaded to #{destination_file_path}"
36
+ end
37
+
38
+ def source_file_path
39
+ step_definition[:source_file_path]
40
+ end
41
+
42
+ def destination_file_path
43
+ step_definition[:destination_file_path]
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,17 @@
1
+ module CopyBot
2
+ module Steps
3
+ class DropLocalDbTables < BaseStep
4
+ # @return [String]
5
+ def run
6
+ conn = ActiveRecord::Base.connection
7
+ conn.tables.each do |table|
8
+ CopyBot.config.logger.info("Dropping #{table}")
9
+ conn.drop_table(table, force: :cascade, if_exists: true)
10
+ end
11
+
12
+ @success = true
13
+ @message = 'Reset local DB schema.'
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,21 @@
1
+ module CopyBot
2
+ module Steps
3
+ class ExecuteCustomCommand < BaseStep
4
+ # @return [String]
5
+ def run
6
+ return @message = 'Custom command missing' unless custom_command
7
+
8
+ @success = CopyBot::ShellCommand.new(custom_command).execute
9
+ @message = @success ? 'Custom command executed.' : 'Custom command failed.'
10
+ end
11
+
12
+ private
13
+
14
+ def custom_command
15
+ return unless step_definition
16
+
17
+ step_definition[:command]
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,32 @@
1
+ module CopyBot
2
+ module Steps
3
+ class ImportRemoteDbToLocalDb < BaseStep
4
+ # @return [String]
5
+ def run
6
+ return @message = 'Missing remote DB dump file' unless source_file_valid?
7
+
8
+ @success = CopyBot::ShellCommand.new(command).execute
9
+ @message = @success ? 'Imported remote DB to local DB.' : 'Remote DB to local DB import failed.'
10
+ end
11
+
12
+ private
13
+
14
+ def source_file_valid?
15
+ source_file_path && File.exist?(source_file_path)
16
+ end
17
+
18
+ def source_file_path
19
+ step_definition[:remote_db_dump_file_path]
20
+ end
21
+
22
+ def command
23
+ "PGPASSWORD=#{db_conn_config[:password]} psql -U #{db_conn_config[:username]} -h #{db_conn_config[:host]} " \
24
+ "-p #{db_conn_config[:port]} #{db_conn_config[:database]} < #{source_file_path}"
25
+ end
26
+
27
+ def db_conn_config
28
+ ActiveRecord::Base.connection_db_config.configuration_hash
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,12 @@
1
+ module CopyBot
2
+ module Steps
3
+ class RunMigrationsOnLocalDb < BaseStep
4
+ # @return [String]
5
+ def run
6
+ Rake::Task['db:migrate'].invoke
7
+ @success = true
8
+ @message = 'Ran migrations on local DB.'
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,26 @@
1
+ desc 'Starting point for data sync'
2
+ task copy_bot: :environment do
3
+ logger = CopyBot.config.logger
4
+
5
+ unless CopyBot.config.permitted_environments.include?(Rails.env)
6
+ logger.debug('Forbidden to run in this environment')
7
+ abort
8
+ end
9
+
10
+ step_definitions_file_path = Rails.root.join(ENV['STEP_DEFINITIONS_FILE_PATH'])
11
+ unless step_definitions_file_path && File.exist?(step_definitions_file_path)
12
+ logger.debug('Invalid or missing step_definitions file path')
13
+ abort
14
+ end
15
+
16
+ CopyBot.step_definitions.load_step_definitions_file(step_definitions_file_path)
17
+ unless CopyBot.step_definitions.steps
18
+ logger.debug('Missing steps in config')
19
+ abort
20
+ end
21
+
22
+ CopyBot.step_definitions.steps.each_key do |step_name|
23
+ success = CopyBot::StepRunner.new(step_name).call
24
+ abort unless success
25
+ end
26
+ end
@@ -0,0 +1,3 @@
1
+ module CopyBot
2
+ VERSION = '0.1.0'.freeze
3
+ end
data/lib/copy_bot.rb ADDED
@@ -0,0 +1,41 @@
1
+ require 'active_record'
2
+ require 'aws-sdk-s3'
3
+ require 'erb'
4
+ require 'logger'
5
+ require 'open3'
6
+ require 'rake'
7
+ require 'rails'
8
+ require 'yaml'
9
+
10
+ require 'copy_bot/version'
11
+ require 'copy_bot/shell_command'
12
+ require 'copy_bot/config'
13
+ require 'copy_bot/railtie' if defined?(Rails::Railtie)
14
+ require 'copy_bot/step_definitions'
15
+ require 'copy_bot/step_factory'
16
+ require 'copy_bot/step_runner'
17
+ require 'copy_bot/steps/base_step'
18
+ require 'copy_bot/steps/create_local_db_backup'
19
+ require 'copy_bot/steps/delete_remote_db_dump'
20
+ require 'copy_bot/steps/download_remote_db_dump'
21
+ require 'copy_bot/steps/drop_local_db_tables'
22
+ require 'copy_bot/steps/execute_custom_command'
23
+ require 'copy_bot/steps/import_remote_db_to_local_db'
24
+ require 'copy_bot/steps/run_migrations_on_local_db'
25
+
26
+ module CopyBot
27
+ # @yield [CopyBot::Config]
28
+ def self.setup
29
+ yield config
30
+ end
31
+
32
+ # @return [CopyBot::Config]
33
+ def self.config
34
+ @config ||= Config.new
35
+ end
36
+
37
+ # @return [CopyBot::StepDefinitions]
38
+ def self.step_definitions
39
+ @step_definitions ||= StepDefinitions.new
40
+ end
41
+ end
metadata ADDED
@@ -0,0 +1,149 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: copy_bot
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Rails Team
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-04-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: aws-sdk-s3
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rails
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '6.1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '6.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: pry
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop-infinum
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: Provides a rake task for importing a database dump into a database on
84
+ a particular environment.
85
+ email:
86
+ - team.rails@infinum.com
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - ".github/workflows/ci.yml"
92
+ - ".gitignore"
93
+ - ".rspec"
94
+ - ".rubocop.yml"
95
+ - ".ruby-version"
96
+ - CHANGELOG.md
97
+ - CODE_OF_CONDUCT.md
98
+ - Gemfile
99
+ - README.md
100
+ - Rakefile
101
+ - bin/console
102
+ - bin/setup
103
+ - copy_bot.gemspec
104
+ - lib/copy_bot.rb
105
+ - lib/copy_bot/config.rb
106
+ - lib/copy_bot/railtie.rb
107
+ - lib/copy_bot/shell_command.rb
108
+ - lib/copy_bot/step_definitions.rb
109
+ - lib/copy_bot/step_factory.rb
110
+ - lib/copy_bot/step_runner.rb
111
+ - lib/copy_bot/steps/base_step.rb
112
+ - lib/copy_bot/steps/create_local_db_backup.rb
113
+ - lib/copy_bot/steps/delete_remote_db_dump.rb
114
+ - lib/copy_bot/steps/download_remote_db_dump.rb
115
+ - lib/copy_bot/steps/drop_local_db_tables.rb
116
+ - lib/copy_bot/steps/execute_custom_command.rb
117
+ - lib/copy_bot/steps/import_remote_db_to_local_db.rb
118
+ - lib/copy_bot/steps/run_migrations_on_local_db.rb
119
+ - lib/copy_bot/tasks/copy_bot.rake
120
+ - lib/copy_bot/version.rb
121
+ homepage: https://github.com/infinum/copy_bot
122
+ licenses:
123
+ - MIT
124
+ metadata:
125
+ allowed_push_host: https://rubygems.org
126
+ homepage_uri: https://github.com/infinum/copy_bot
127
+ source_code_uri: https://github.com/infinum/copy_bot
128
+ changelog_uri: https://github.com/infinum/copy_bot/blob/master/CHANGELOG.md
129
+ rubygems_mfa_required: 'true'
130
+ post_install_message:
131
+ rdoc_options: []
132
+ require_paths:
133
+ - lib
134
+ required_ruby_version: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: 3.0.1
139
+ required_rubygems_version: !ruby/object:Gem::Requirement
140
+ requirements:
141
+ - - ">="
142
+ - !ruby/object:Gem::Version
143
+ version: '0'
144
+ requirements: []
145
+ rubygems_version: 3.2.15
146
+ signing_key:
147
+ specification_version: 4
148
+ summary: Tool for syncing data between two environments.
149
+ test_files: []