lambda_ruby_bundler 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7bf3f89fe8cb3dead5a5d935366eaada4eceb209ceaf3298774d6dd61877e1ee
4
+ data.tar.gz: 686a6b547bf4983b268f665e11da63aced31f6bd3a367c027adbe04bce11aaae
5
+ SHA512:
6
+ metadata.gz: a3df72a48792cdc0c04b159b89c9a00a60d08a8831707a4726632f71c7cb20df0e23ec264aa7eba3c99c20d2c95664359f14b8b5d439decf25dd2845bc44e269
7
+ data.tar.gz: 51465948b799fd031b69a32e726a61c3f6e7540bd969ee29233ce0a30be0a414bbe3dd8140a58f556f380f855aa1e41988b547b53aa44f1a3ec6b3d3163ea2cd
@@ -0,0 +1,14 @@
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
12
+
13
+ spec/tmp/*
14
+ !spec/tmp/.keep
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1 @@
1
+ 2.5.7
@@ -0,0 +1,12 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.7
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 2.0.2
8
+ script:
9
+ - bundle exec rspec
10
+ - bundle exec rubocop
11
+ services:
12
+ - docker
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## [v1.0.0] - 2019-11-06
4
+ ### Features
5
+ - Added initial implementation of the gem.
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at michal.begejowicz@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in lambda_ruby_bundler.gemspec
6
+ gemspec
@@ -0,0 +1,73 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ lambda_ruby_bundler (1.0.0)
5
+ docker-api
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.0)
11
+ coderay (1.1.2)
12
+ diff-lcs (1.3)
13
+ docile (1.3.2)
14
+ docker-api (1.34.2)
15
+ excon (>= 0.47.0)
16
+ multi_json
17
+ excon (0.68.0)
18
+ jaro_winkler (1.5.4)
19
+ json (2.2.0)
20
+ method_source (0.9.2)
21
+ multi_json (1.14.1)
22
+ parallel (1.18.0)
23
+ parser (2.6.5.0)
24
+ ast (~> 2.4.0)
25
+ pry (0.12.2)
26
+ coderay (~> 1.1.0)
27
+ method_source (~> 0.9.0)
28
+ rainbow (3.0.0)
29
+ rake (13.0.0)
30
+ rspec (3.9.0)
31
+ rspec-core (~> 3.9.0)
32
+ rspec-expectations (~> 3.9.0)
33
+ rspec-mocks (~> 3.9.0)
34
+ rspec-core (3.9.0)
35
+ rspec-support (~> 3.9.0)
36
+ rspec-expectations (3.9.0)
37
+ diff-lcs (>= 1.2.0, < 2.0)
38
+ rspec-support (~> 3.9.0)
39
+ rspec-mocks (3.9.0)
40
+ diff-lcs (>= 1.2.0, < 2.0)
41
+ rspec-support (~> 3.9.0)
42
+ rspec-support (3.9.0)
43
+ rubocop (0.76.0)
44
+ jaro_winkler (~> 1.5.1)
45
+ parallel (~> 1.10)
46
+ parser (>= 2.6)
47
+ rainbow (>= 2.2.2, < 4.0)
48
+ ruby-progressbar (~> 1.7)
49
+ unicode-display_width (>= 1.4.0, < 1.7)
50
+ ruby-progressbar (1.10.1)
51
+ rubyzip (2.0.0)
52
+ simplecov (0.17.1)
53
+ docile (~> 1.1)
54
+ json (>= 1.8, < 3)
55
+ simplecov-html (~> 0.10.0)
56
+ simplecov-html (0.10.2)
57
+ unicode-display_width (1.6.0)
58
+
59
+ PLATFORMS
60
+ ruby
61
+
62
+ DEPENDENCIES
63
+ bundler
64
+ lambda_ruby_bundler!
65
+ pry
66
+ rake
67
+ rspec
68
+ rubocop
69
+ rubyzip
70
+ simplecov
71
+
72
+ BUNDLED WITH
73
+ 2.0.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 TD Reply
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,125 @@
1
+ # LambdaRubyBundler
2
+
3
+ LambdaRubyBundler is a command-line tool for packaging Ruby applications for AWS Lambda.
4
+
5
+ Most notably, it properly compiles dependencies with C extensions, using a custom Docker image based on [lambci/lambda:build-ruby2.5](https://hub.docker.com/r/lambci/lambda/tags).
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile for programmatic usage:
10
+
11
+ ```ruby
12
+ gem 'lambda_ruby_bundler'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install lambda_ruby_bundler
22
+
23
+ ## Usage
24
+
25
+ Note that the library requires running Docker on your system!
26
+
27
+ Let's assume the following directory structure:
28
+
29
+ ```
30
+ /tmp/my_serverless_app
31
+ ├── Gemfile
32
+ ├── Gemfile.lock
33
+ ├── backend/
34
+ │ └── handler.rb
35
+ └── node_modules/...
36
+ ```
37
+
38
+ ### Command line usage
39
+
40
+ Run:
41
+
42
+ ```bash
43
+ lambda_ruby_bundler \
44
+ --root-path /tmp/my_serverless_app \
45
+ --app-path backend \
46
+ --out /tmp/build.zip
47
+ ```
48
+
49
+ It will produce two ZIP files, one with the contents of the application directory:
50
+
51
+ ```
52
+ # build.zip
53
+ ├ handler.rb
54
+ ```
55
+
56
+ And one with bundled dependencies:
57
+
58
+ ```
59
+ # build-dependencies.zip
60
+ ruby/gems/2.5.0
61
+ ├── gems/...
62
+ ```
63
+
64
+ The first one is meant as the Lambda code, while second will work as Lambda Layer, allowing you to share it between multiple Lambdas using the same codebase.
65
+
66
+ Note that:
67
+
68
+ 1. The structure will be "flattened" (based on contents of the `--app-path`)
69
+ 2. Only gems **not in** development and test groups will be bundled
70
+ 3. The first run might be very long. It requires pulling the base image, building Bundler image, fetching and building gems for your application
71
+
72
+ ### Programmatic usage
73
+
74
+ ```ruby
75
+ executor = LambdaRubyBundler::Executor.new(
76
+ '/tmp/my_serverless_app',
77
+ 'backend',
78
+ true
79
+ )
80
+
81
+ result = executor.run
82
+ File.write('bundle.zip', result[:application_bundle].read)
83
+ File.write('dependencies.zip', result[:dependency_layer].read)
84
+ ```
85
+
86
+ ### Cache mode
87
+
88
+ The gem can also automatically assign build paths and cache them. To use Cache Mode, simply use `--cache-dir` option in CLI usage or use `LambdaRubyBundler::CLI::CacheRunner` class to generate the bundles.
89
+
90
+ ```bash
91
+ lambda_ruby_bundler --app-path backend --cache-dir tmp
92
+ ```
93
+
94
+ ```ruby
95
+ runner = LambdaRubyBundler::CLI::CacheRunner.new(Dir.pwd, 'backend', 'tmp')
96
+ runner.run
97
+ ```
98
+
99
+ This will save the bundles in cache directory and will output the paths to STDOUT (CLI case) or return them as Hash (programmatic usage).
100
+
101
+ ### Ruby versions
102
+
103
+ Currently, Lambda supports only Ruby 2.5 environment - specifically, `2.5.5`. At the moment of writing this Readme, newest version from `2.5.x` family is `2.5.7`.
104
+
105
+ Your application is expected to work properly on Ruby 2.5.5, but the `LambdaRubyBundler` does not verify it in any way. To ease the development of the application, the `ruby` entry from Gemfile will be removed while bundling gems, allowing you to develop your application with any ruby version.
106
+
107
+ Note that it is still best to use a version from Ruby 2.5.x family - other versions might be packaged successfully, but might not work when deployed to Lambda!
108
+
109
+ ## Development
110
+
111
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
112
+
113
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
114
+
115
+ ## Contributing
116
+
117
+ Bug reports and pull requests are welcome on GitHub at https://github.com/td-berlin/lambda_ruby_bundler. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
118
+
119
+ ## License
120
+
121
+ The gem is available as open-source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
122
+
123
+ ## Code of Conduct
124
+
125
+ Everyone interacting in the LambdaRubyBundler project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'lambda_ruby_bundler'
6
+
7
+ require 'pry'
8
+ Pry.start
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'lambda_ruby_bundler'
5
+
6
+ options = LambdaRubyBundler::CLI::OptionParser.new.parse!(ARGV)
7
+
8
+ runner = if options[:cache_dir]
9
+ LambdaRubyBundler::CLI::CacheRunner.new(
10
+ options[:root_path], options[:app_path], options[:cache_dir]
11
+ )
12
+ else
13
+ LambdaRubyBundler::CLI::StandardRunner.new(
14
+ options[:root_path],
15
+ options[:app_path],
16
+ options[:build_dependencies],
17
+ application_bundle: options[:output_path],
18
+ dependency_layer: options[:dependencies_path]
19
+ )
20
+ end
21
+
22
+ puts runner.run.to_json
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'lambda_ruby_bundler/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'lambda_ruby_bundler'
9
+ spec.version = LambdaRubyBundler::VERSION
10
+ spec.authors = ['TD Reply']
11
+ spec.email = ['michal.begejowicz@gmail.com']
12
+
13
+ spec.summary = 'Bundler for Ruby applications running on lambda'
14
+ spec.description = <<~DESC
15
+ Bundler for Ruby applications running on lambda.
16
+
17
+ It manages proper building of dependencies and native extensions.
18
+ DESC
19
+
20
+ spec.homepage = 'https://github.com/td-berlin/lambda_ruby_bundler'
21
+ spec.license = 'MIT'
22
+
23
+ spec.metadata['homepage_uri'] = spec.homepage
24
+ spec.metadata['source_code_uri'] = spec.homepage
25
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md"
26
+
27
+ # Specify which files should be added to the gem when it is released.
28
+ # The `git ls-files -z` loads the files in the RubyGem that have been
29
+ # added into git.
30
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
31
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^spec/}) }
32
+ end
33
+ spec.bindir = 'exe'
34
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
35
+ spec.require_paths = ['lib']
36
+
37
+ spec.add_dependency 'docker-api'
38
+
39
+ spec.add_development_dependency 'bundler'
40
+ spec.add_development_dependency 'pry'
41
+ spec.add_development_dependency 'rake'
42
+ spec.add_development_dependency 'rspec'
43
+ spec.add_development_dependency 'rubocop'
44
+ spec.add_development_dependency 'rubyzip'
45
+ spec.add_development_dependency 'simplecov'
46
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'lambda_ruby_bundler/version'
4
+
5
+ require 'digest'
6
+ require 'docker'
7
+ require 'forwardable'
8
+ require 'optparse'
9
+ require 'json'
10
+ require 'singleton'
11
+
12
+ require 'lambda_ruby_bundler/image'
13
+ require 'lambda_ruby_bundler/volume'
14
+ require 'lambda_ruby_bundler/container'
15
+ require 'lambda_ruby_bundler/executor'
16
+
17
+ require 'lambda_ruby_bundler/cli'
18
+ require 'lambda_ruby_bundler/cli/option_parser'
19
+ require 'lambda_ruby_bundler/cli/base_runner'
20
+ require 'lambda_ruby_bundler/cli/cache_runner'
21
+ require 'lambda_ruby_bundler/cli/standard_runner'
22
+
23
+ module LambdaRubyBundler
24
+ class Error < StandardError; end
25
+ end
@@ -0,0 +1,11 @@
1
+ FROM lambci/lambda:build-ruby2.5
2
+
3
+ RUN mkdir -p /workspace/build
4
+ WORKDIR /workspace
5
+
6
+ ENV BUNDLE_WITHOUT=development:test
7
+
8
+ RUN mkdir /app /scripts
9
+ COPY packager.rb /scripts/packager.rb
10
+
11
+ ENTRYPOINT [ "/scripts/packager.rb" ]
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ # Namespace for handling Command Line Interface
5
+ module CLI
6
+ end
7
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ module CLI
5
+ # Runs the executor.
6
+ # @api private
7
+ class BaseRunner
8
+ attr_reader :root_path, :app_path
9
+
10
+ def initialize(root_path, app_path)
11
+ @root_path = root_path
12
+ @app_path = app_path
13
+ end
14
+
15
+ private
16
+
17
+ def bundle(build_dependencies)
18
+ executor = LambdaRubyBundler::Executor.new(
19
+ root_path, app_path, build_dependencies
20
+ )
21
+
22
+ result = executor.run
23
+
24
+ save(result[:application_bundle], paths[:application_bundle])
25
+ return unless build_dependencies
26
+
27
+ save(result[:dependency_layer], paths[:dependency_layer])
28
+ end
29
+
30
+ def save(io, path)
31
+ File.open(path, 'wb+') { |file| file.write(io.read) }
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ module CLI
5
+ # Runs the executor in Cache Mode.
6
+ class CacheRunner < BaseRunner
7
+ MD5_EXTRACT_REGEX = /build(?:dep)?-([a-f0-9]{32}).zip/.freeze
8
+
9
+ attr_reader :cache_dir
10
+
11
+ # Creates new instance of cache runner.
12
+ #
13
+ # @param [String] root_path
14
+ # Path to the root of application (containing Gemfile.lock)
15
+ # @param [String] app_path
16
+ # Path (relative to root_path) containing application code
17
+ # @param [String]
18
+ # cache_dir Directory containing cached builds
19
+ def initialize(root_path, app_path, cache_dir)
20
+ super(root_path, app_path)
21
+ @cache_dir = cache_dir
22
+ end
23
+
24
+ # Runs the executor, if necessary. Returns hash with two keys:
25
+ # :application_bundle => path to the application code bundle
26
+ # :dependency_layer => path to dependency bundle
27
+ #
28
+ # @return [Hash] Paths to the builds
29
+ def run
30
+ build_dependencies = !dependencies_builds.key?(dependencies_hash)
31
+ build_application = !application_builds.key?(application_hash)
32
+
33
+ if build_application || build_dependencies
34
+ clear_cache
35
+ bundle(build_dependencies)
36
+ end
37
+
38
+ paths
39
+ end
40
+
41
+ private
42
+
43
+ def clear_cache
44
+ (application_builds.values + dependencies_builds.values).each do |file|
45
+ FileUtils.rm(file)
46
+ end
47
+ end
48
+
49
+ def paths
50
+ @paths ||= {
51
+ application_bundle:
52
+ File.join(cache_dir, "build-#{application_hash}.zip"),
53
+ dependency_layer:
54
+ File.join(cache_dir, "builddep-#{dependencies_hash}.zip")
55
+ }
56
+ end
57
+
58
+ def application_hash
59
+ @application_hash ||= begin
60
+ files = Dir[File.join(root_path, app_path, '**', '*')]
61
+ digest = Digest::MD5.new
62
+
63
+ files.each do |file|
64
+ digest << File.read(file) if File.file?(file)
65
+ end
66
+
67
+ digest.hexdigest
68
+ end
69
+ end
70
+
71
+ def dependencies_hash
72
+ @dependencies_hash ||= begin
73
+ path = File.join(root_path, 'Gemfile.lock')
74
+ content = File.read(path)
75
+ Digest::MD5.hexdigest(content)
76
+ end
77
+ end
78
+
79
+ def application_builds
80
+ @application_builds ||= fetch_builds('build-*.zip')
81
+ end
82
+
83
+ def dependencies_builds
84
+ @dependencies_builds ||= fetch_builds('builddep-*.zip')
85
+ end
86
+
87
+ def fetch_builds(name_glob)
88
+ Dir[File.join(cache_dir, name_glob)]
89
+ .group_by(&method(:extract_md5))
90
+ .transform_values(&:first)
91
+ .tap { |result| result.delete(nil) }
92
+ end
93
+
94
+ def extract_md5(path)
95
+ MD5_EXTRACT_REGEX.match(path)&.captures&.at(0)
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ module CLI
5
+ # Custom OptionParser which collects user-supplied options about the build.
6
+ # @api private
7
+ class OptionParser < ::OptionParser
8
+ attr_reader :options
9
+
10
+ OPTIONS = %i[
11
+ root_path_option
12
+ app_path_option
13
+ output_option
14
+ no_dependencies_option
15
+ dependencies_path_option
16
+ cache_dir_option
17
+ ].freeze
18
+
19
+ def initialize
20
+ @options = defaults
21
+
22
+ super { |builder| OPTIONS.each { |option| send(option, builder) } }
23
+ end
24
+
25
+ def parse!(*)
26
+ super
27
+
28
+ options[:dependencies_path] ||= build_default_dependencies_path(
29
+ options[:output_path]
30
+ )
31
+
32
+ options
33
+ end
34
+
35
+ private
36
+
37
+ def defaults
38
+ {
39
+ root_path: Dir.pwd,
40
+ app_path: '.',
41
+ build_dependencies: true,
42
+ dependencies_path: nil,
43
+ output_path: 'build.zip',
44
+ cache_dir: nil
45
+ }
46
+ end
47
+
48
+ def build_default_dependencies_path(output_path)
49
+ File.join(
50
+ File.dirname(output_path),
51
+ [File.basename(output_path, '.*'), 'dependencies.zip'].join('-')
52
+ )
53
+ end
54
+
55
+ def root_path_option(builder)
56
+ builder.on(
57
+ '--root-path=ROOT_PATH',
58
+ 'Sets root path (containing Gemfile) of the application' \
59
+ ' (defaults to current directory)'
60
+ ) do |path|
61
+ options[:root_path] = File.expand_path(path)
62
+ end
63
+ end
64
+
65
+ def app_path_option(builder)
66
+ builder.on(
67
+ '--app-path=APP_PATH',
68
+ 'Sets application path (relative to root) with the application code' \
69
+ ' (defaults to current directory)',
70
+ &assign_option(:app_path)
71
+ )
72
+ end
73
+
74
+ def output_option(builder)
75
+ builder.on(
76
+ '--out=OUT_PATH',
77
+ 'Sets output path, to which the ZIP with the bundled code ' \
78
+ 'will be saved',
79
+ &assign_option(:output_path)
80
+ )
81
+ end
82
+
83
+ def no_dependencies_option(builder)
84
+ builder.on(
85
+ '--no-dependencies', 'Prevents building dependency layer'
86
+ ) do |option|
87
+ options[:build_dependencies] = option
88
+ end
89
+ end
90
+
91
+ def dependencies_path_option(builder)
92
+ builder.on(
93
+ '--dependencies-path=APP_PATH',
94
+ 'Sets path for the dependencies layer package (defaults to ' \
95
+ '{OUT_PATH}-dependencies.zip)',
96
+ &assign_option(:dependencies_path)
97
+ )
98
+ end
99
+
100
+ def cache_dir_option(builder)
101
+ builder.on(
102
+ '--cache-dir=CACHE_DIR',
103
+ 'Enables Cache Mode and uses chosen directory as target directory ' \
104
+ 'for the builds.',
105
+ &assign_option(:cache_dir)
106
+ )
107
+ end
108
+
109
+ def assign_option(option)
110
+ proc { |value| options[option] = value }
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ module CLI
5
+ # Runs the executor with given parameters.
6
+ class StandardRunner < BaseRunner
7
+ attr_reader :build_dependencies, :paths
8
+
9
+ # Creates new instance of cache runner.
10
+ #
11
+ # @param [String] root_path
12
+ # Path to the root of application (containing Gemfile.lock)
13
+ # @param [String] app_path
14
+ # Path (relative to root_path) containing application code
15
+ # @param [Boolean] build_dependencies
16
+ # Whether or not to build dependencies
17
+ # @param [Hash] paths
18
+ # Hash with :application_bundle and :dependency_layer output paths
19
+ def initialize(root_path, app_path, build_dependencies, paths)
20
+ super(root_path, app_path)
21
+ @build_dependencies = build_dependencies
22
+ @paths = paths
23
+ end
24
+
25
+ # Runs the executo. Returns hash with two keys:
26
+ # :application_bundle => path to the application code bundle
27
+ # :dependency_layer => path to dependency bundle
28
+ #
29
+ # @return [Hash] Paths to the builds
30
+ def run
31
+ bundle(build_dependencies)
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ # Wrapper around [Docker::Container] for creating, running and removing
5
+ # bundler containers.
6
+ # @api private
7
+ class Container
8
+ attr_reader :root_path, :app_path, :volume, :build_dependencies
9
+
10
+ def initialize(root_path, app_path, volume, build_dependencies)
11
+ @root_path = root_path
12
+ @app_path = app_path
13
+ @volume = volume
14
+ @build_dependencies = build_dependencies
15
+ end
16
+
17
+ def run(timeout: 120)
18
+ container.start
19
+
20
+ container.attach({}, read_timeout: timeout)
21
+ end
22
+
23
+ def destroy
24
+ container.remove
25
+ @container = nil
26
+ end
27
+
28
+ private
29
+
30
+ def container
31
+ @container ||= Docker::Container.create(container_arguments)
32
+ end
33
+
34
+ def container_arguments
35
+ { 'Cmd' => [app_path, build_dependencies ? 'use-deps' : 'no-deps'],
36
+ 'Image' => Image.instance.id,
37
+ 'HostConfig' => {
38
+ 'AutoRemove' => true,
39
+ 'Mounts' => mounts
40
+ } }
41
+ end
42
+
43
+ def mounts
44
+ [
45
+ { 'Target' => '/app',
46
+ 'Source' => root_path,
47
+ 'Type' => 'bind',
48
+ 'ReadOnly' => true },
49
+ { 'Target' => '/workspace/build/vendor/bundle',
50
+ 'Source' => volume.id,
51
+ 'Type' => 'volume' }
52
+ ]
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ # Main entrypoint to the application, which packages the code from given
5
+ # directory into ZIP.
6
+ #
7
+ # The packaging is done inside a container resembling Lambda environment,
8
+ # ensuring that the gems with C extensions will work there properly.
9
+ #
10
+ #
11
+ # @example Default use case
12
+ # # Given following directory structure:
13
+ # # /tmp/my_serverless_app
14
+ # # +-- Gemfile
15
+ # # +-- Gemfile.lock
16
+ # # +-- backend/
17
+ # # | +-- handler.rb
18
+ # # +-- node_modules/...
19
+ #
20
+ # executor = LambdaRubyBundler::Executor.new(
21
+ # '/tmp/my_serverless_app',
22
+ # 'backend',
23
+ # true
24
+ # )
25
+ #
26
+ # result = executor.run
27
+ # File.write('bundle.zip', result[:application_bundle].read)
28
+ # File.write('dependencies.zip', result[:dependency_layer].read)
29
+ #
30
+ # # Note that resulting structure of the ZIP will be flattened!
31
+ # # + handler.rb
32
+ # # + vendor/bundle/...
33
+ class Executor
34
+ attr_reader :root_path, :app_path, :build_dependencies
35
+
36
+ # Creates new instance of the Executor.
37
+ #
38
+ # @param [String] root_path
39
+ # Path to the root of the application (with Gemfile)
40
+ # @param [String] app_path
41
+ # Path to the Ruby application code, relative to root.
42
+ # @param [Boolean] build_dependencies
43
+ # Flag whether or not to bundle the dependencies.
44
+ # Useful in cases when dependencies (Gemfile.lock) does not change
45
+ # between builds.
46
+ def initialize(root_path, app_path, build_dependencies)
47
+ @root_path = root_path
48
+ @app_path = app_path
49
+ @build_dependencies = build_dependencies
50
+ end
51
+
52
+ # Generates the ZIP contents.
53
+ #
54
+ # @return [Hash{:application_bundle, :dependency_layer => StringIO}]
55
+ # Hash with the zip IOs. If `build_dependencies` options was falsey,
56
+ # There will be no :dependency_layer key.
57
+ def run
58
+ zipped_contents, = container.run.tap { container.destroy }
59
+ contents = JSON.parse(zipped_contents.join)
60
+
61
+ decode(contents)
62
+ end
63
+
64
+ private
65
+
66
+ def decode(contents)
67
+ contents.each_with_object({}) do |(key, data), result|
68
+ result[key.to_sym] = StringIO.new(Base64.strict_decode64(data))
69
+ end
70
+ end
71
+
72
+ def application_name
73
+ @application_name ||= File.basename(root_path)
74
+ end
75
+
76
+ def container
77
+ @container ||= Container.new(
78
+ root_path, app_path, volume, build_dependencies
79
+ )
80
+ end
81
+
82
+ def volume
83
+ @volume ||= Volume.new(application_name)
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ # Wrapper around [Docker::Image] for building the image for the bundler
5
+ # containers.
6
+ # @api private
7
+ class Image
8
+ include Singleton
9
+ extend Forwardable
10
+
11
+ delegate id: :@image
12
+
13
+ def initialize
14
+ @image = Docker::Image.build_from_dir(__dir__, 't' => tag)
15
+ end
16
+
17
+ def tag
18
+ @tag ||= [
19
+ 'lambda-ruby-bundler',
20
+ VERSION
21
+ ].join(':')
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Packager script run inside the container
5
+
6
+ require 'fileutils'
7
+ require 'json'
8
+ require 'base64'
9
+
10
+ APPLICATION_DIRECTORY, = ARGV
11
+ BUNDLE_DEPS = ARGV.include?('use-deps')
12
+
13
+ def silent(command)
14
+ system(command, out: File::NULL, err: File::NULL)
15
+ end
16
+
17
+ def bundle_install(*additional_options)
18
+ [
19
+ 'bundle install',
20
+ '--path build/vendor/bundle',
21
+ *additional_options
22
+ ].join(' ')
23
+ end
24
+
25
+ RUBY_ENTRY_REGEX = /\A\s*ruby\s+("|')\d+\.\d+\.\d+("|')\s*\z/.freeze
26
+
27
+ result = {}
28
+
29
+ if BUNDLE_DEPS
30
+ # Copy Gemfile and Gemfile.lock to the workspace
31
+ FileUtils.cp('/app/Gemfile', '/workspace/Gemfile')
32
+ FileUtils.cp('/app/Gemfile.lock', '/workspace/Gemfile.lock')
33
+
34
+ # Clean Ruby version requirement from Gemfile
35
+ contents = File.read('/workspace/Gemfile').lines
36
+ contents.reject! { |line| RUBY_ENTRY_REGEX.match(line) }
37
+ File.write('/workspace/Gemfile', contents.join)
38
+
39
+ # Check if all gems are installed
40
+ all_installed = silent(bundle_install('--local'))
41
+
42
+ # Install if some gems are missing locally
43
+ silent(bundle_install) unless all_installed
44
+
45
+ # Clean unused gems
46
+ silent('bundle clean')
47
+
48
+ # Create proper structure for AWS Layer
49
+ FileUtils.mkdir_p('/tmp/layer/ruby/gems')
50
+ FileUtils.symlink(
51
+ '/workspace/build/vendor/bundle/ruby/2.5.0',
52
+ '/tmp/layer/ruby/gems/2.5.0'
53
+ )
54
+
55
+ # Zip the dependencies
56
+ silent('cd /tmp/layer && zip -r /tmp/dependencies.zip .')
57
+
58
+ # Add serialized ZIP to result
59
+ content = File.read('/tmp/dependencies.zip')
60
+ result[:dependency_layer] = Base64.strict_encode64(content)
61
+ end
62
+
63
+ # Zip the application code
64
+ app_path = File.join('/app', APPLICATION_DIRECTORY)
65
+ silent("cd #{app_path} && zip -r /tmp/app.zip .")
66
+
67
+ # Add serialized ZIP to result
68
+ content = File.read('/tmp/app.zip')
69
+ result[:application_bundle] = Base64.strict_encode64(content)
70
+
71
+ puts(result.to_json)
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ VERSION = '1.0.0'
5
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LambdaRubyBundler
4
+ # Wrapper around [Docker::Volume] for creating and fetching bundler volumes,
5
+ # which are used to cache built gems. This speeds up the process
6
+ # significantly.
7
+ # @api private
8
+ class Volume
9
+ NAME_TEMPLATE = 'lambda-ruby-bundler-%<app>s-volume'
10
+
11
+ attr_reader :application_name
12
+
13
+ def initialize(application_name)
14
+ @application_name = application_name
15
+ end
16
+
17
+ def id
18
+ volume.id
19
+ end; alias name id
20
+
21
+ private
22
+
23
+ def volume
24
+ @volume ||= fetch_volume
25
+ end
26
+
27
+ def fetch_volume
28
+ name = format(NAME_TEMPLATE, app: application_name)
29
+
30
+ Docker::Volume.get(name)
31
+ rescue Docker::Error::NotFoundError
32
+ Docker::Volume.create(name)
33
+ end
34
+ end
35
+ end
metadata ADDED
@@ -0,0 +1,191 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lambda_ruby_bundler
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - TD Reply
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-11-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: docker-api
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: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
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: rake
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: rspec
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
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubyzip
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: simplecov
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ description: |
126
+ Bundler for Ruby applications running on lambda.
127
+
128
+ It manages proper building of dependencies and native extensions.
129
+ email:
130
+ - michal.begejowicz@gmail.com
131
+ executables:
132
+ - lambda_ruby_bundler
133
+ extensions: []
134
+ extra_rdoc_files: []
135
+ files:
136
+ - ".gitignore"
137
+ - ".rspec"
138
+ - ".ruby-version"
139
+ - ".travis.yml"
140
+ - CHANGELOG.md
141
+ - CODE_OF_CONDUCT.md
142
+ - Gemfile
143
+ - Gemfile.lock
144
+ - LICENSE.txt
145
+ - README.md
146
+ - Rakefile
147
+ - bin/console
148
+ - bin/setup
149
+ - exe/lambda_ruby_bundler
150
+ - lambda_ruby_bundler.gemspec
151
+ - lib/lambda_ruby_bundler.rb
152
+ - lib/lambda_ruby_bundler/Dockerfile
153
+ - lib/lambda_ruby_bundler/cli.rb
154
+ - lib/lambda_ruby_bundler/cli/base_runner.rb
155
+ - lib/lambda_ruby_bundler/cli/cache_runner.rb
156
+ - lib/lambda_ruby_bundler/cli/option_parser.rb
157
+ - lib/lambda_ruby_bundler/cli/standard_runner.rb
158
+ - lib/lambda_ruby_bundler/container.rb
159
+ - lib/lambda_ruby_bundler/executor.rb
160
+ - lib/lambda_ruby_bundler/image.rb
161
+ - lib/lambda_ruby_bundler/packager.rb
162
+ - lib/lambda_ruby_bundler/version.rb
163
+ - lib/lambda_ruby_bundler/volume.rb
164
+ homepage: https://github.com/td-berlin/lambda_ruby_bundler
165
+ licenses:
166
+ - MIT
167
+ metadata:
168
+ homepage_uri: https://github.com/td-berlin/lambda_ruby_bundler
169
+ source_code_uri: https://github.com/td-berlin/lambda_ruby_bundler
170
+ changelog_uri: https://github.com/td-berlin/lambda_ruby_bundler/blob/master/CHANGELOG.md
171
+ post_install_message:
172
+ rdoc_options: []
173
+ require_paths:
174
+ - lib
175
+ required_ruby_version: !ruby/object:Gem::Requirement
176
+ requirements:
177
+ - - ">="
178
+ - !ruby/object:Gem::Version
179
+ version: '0'
180
+ required_rubygems_version: !ruby/object:Gem::Requirement
181
+ requirements:
182
+ - - ">="
183
+ - !ruby/object:Gem::Version
184
+ version: '0'
185
+ requirements: []
186
+ rubyforge_project:
187
+ rubygems_version: 2.7.6.2
188
+ signing_key:
189
+ specification_version: 4
190
+ summary: Bundler for Ruby applications running on lambda
191
+ test_files: []