broadside 0.0.1 → 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: bf7af1a3d95745e8c208d866da7936dcffbc66b9
4
- data.tar.gz: db5d5c03f60d77464b536f8505ec5ba1904aaeb2
3
+ metadata.gz: 3693defb94dc9f5396cf5d5ad907eecd49032c77
4
+ data.tar.gz: 2dc28e92eb875b2bae69cc4a3a25896eacfe79c7
5
5
  SHA512:
6
- metadata.gz: 0f06d8a671d93309450ff17b3f289980cde9fbd5374d372656ba954d7036dec2b6f4119994491c72e048b4d5ed26c76a6329f931c439fb05f09689740605f837
7
- data.tar.gz: 301976eb3eeec7da29da54a875feec0673c3daabb2883c81001766ba0caa4efb4bfdf4351e2419e6be140deeb686293cf58484ccd35010348c638529923d2c87
6
+ metadata.gz: 81e4d4e8e4d1afb13f49e0e822119b102a8489c69626e22930e7a160590c328c4f110f910790cca1513a7d18a73748ee0abe8797d60fea12d81ee6e991e4c960
7
+ data.tar.gz: db75a3e185c21492bb78641e288079e59aa4a602666f513ea0aaabfd7d6245c5e8704ae4f21c3f1f44f628605597a0990d23a329722f97f9c47aba8d60cdedec
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ .bundle/
2
+ *.log
3
+ pkg/
4
+ *~
5
+ .env
6
+ .DS_Store
7
+
8
+ *.gem
9
+ Gemfile.lock
data/.gitmodules ADDED
@@ -0,0 +1,3 @@
1
+ [submodule "broadside.wiki"]
2
+ path = broadside.wiki
3
+ url = git@github.com:lumoslabs/broadside.wiki.git
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,13 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.1.6
5
+ cache: bundler
6
+ script:
7
+ - bundle exec rspec
8
+ branches:
9
+ except:
10
+ - /^production_release_\d+$/
11
+ - /^staging_release_\d+$/
12
+ notifications:
13
+ email: false
data/AUTHORS ADDED
@@ -0,0 +1,4 @@
1
+ Cameron Dutro <camertron@gmail.com>
2
+ Jay O'Connor <jay@jayoconnor.com>
3
+ Matthew Leung <leung.mattp@gmail.com>
4
+ Rob Froetscher <rfroetscher@lumoslabs.com>
data/CHANGELOG.md ADDED
@@ -0,0 +1,2 @@
1
+ # 1.0.0
2
+ - Initial release.
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in broadside.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Lumos Labs
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.
data/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # Broadside
2
+ A command-line tool for deploying applications on AWS EC2 Container Service (ECS)
3
+
4
+ This tool is primarily intended for use with ruby applications.
5
+
6
+
7
+ ## Overview
8
+ Amazon ECS presents a low barrier to entry for production-level docker applications. Combined with ECS's built-in blue-green deployment, Elastic Load Balancers, Autoscale Groups, and CloudWatch, one can set up a robust cluster that can scale to serve any number of applications in a short amount of time. Broadside seeks to leverage these benefits and improve the deployment process for developers.
9
+
10
+ Broadside offers a simple command-line interface to perform deployments on ECS. It does not attempt to handle operational tasks like infrastructure setup and configuration, which are better suited for tools like [terraform](https://www.terraform.io/). This allows applications using broadside to employ a clean configuration file that looks something like:
11
+
12
+ ```ruby
13
+ Broadside.configure do |config|
14
+ config.base.application = 'hello_world'
15
+ config.base.docker_image = 'lumoslabs/hello_world'
16
+ config.deploy.type = 'ecs'
17
+ config.ecs.cluster = 'micro-cluster'
18
+ config.deploy.targets = {
19
+ production_web: {
20
+ scale: 7,
21
+ command: ['bundle', 'exec', 'unicorn', '-c', 'config/unicorn.conf.rb'],
22
+ env_file: '../.env.production'
23
+ predeploy_commands: [
24
+ ['bundle', 'exec', 'rake', 'db:migrate'],
25
+ ['bundle', 'exec', 'rake', 'data:migrate']
26
+ ]
27
+ },
28
+ production_worker: {
29
+ scale: 15,
30
+ command: ['bundle', 'exec', 'rake', 'resque:work'],
31
+ env_file: '../.env.production'
32
+ }
33
+ staging_web: {
34
+ scale: 1,
35
+ command: ['bundle', 'exec', 'puma'],
36
+ env_file: '../.env.staging'
37
+ }
38
+ staging_worker: {
39
+ scale: 1,
40
+ command: ['bundle', 'exec', 'rake', 'resque:work'],
41
+ env_file: '../.env.staging'
42
+ }
43
+ }
44
+ end
45
+ ```
46
+
47
+ From here, developers can use broadside's command-line interface to initiate a basic deployment:
48
+ ```
49
+ broadside deploy short --target production_web --tag $GIT_SHA
50
+ ```
51
+ or run
52
+ ```
53
+ broadside deploy full --target production_web --tag $GIT_SHA
54
+ ```
55
+ which will run the listed `predeploy_commands` listed in the config above prior to the deployment.
56
+
57
+ In the case of an error or timeout during a deploy, broadside will automatically rollback to the latest stable version. You can perform manual rollbacks as well through the command-line.
58
+
59
+ See the complete command-line reference in the wiki.
60
+
61
+
62
+ ## Setup
63
+ First, install broadside by adding it to your application gemfile:
64
+ ```
65
+ gem 'broadside'
66
+ ```
67
+
68
+ Then run
69
+ ```
70
+ bundle install
71
+ bundle binstubs broadside
72
+ ```
73
+
74
+ It's recommended that you specify broadside as a development gem so it doesn't inflate your production image.
75
+
76
+ You can now run the executable in your app directory:
77
+ ```
78
+ bin/broadside --help
79
+ ```
80
+
81
+ For a full application setup, see the detailed instructions in the wiki.
82
+
83
+
84
+ ## Contributing
85
+ Pull requests, bug reports, and feature suggestions are welcome! Before starting on a contribution, I recommend opening an issue or replying to an existing one to give others some initial context on the work needing to be done.
86
+
87
+ 1. Create your feature branch (`git checkout -b my-new-feature`)
88
+ 2. Commit your changes (`git commit -am 'Add some feature'`)
89
+ 3. Push to the branch (`git push origin my-new-feature`)
90
+ 4. Create a new Pull Request
data/bin/broadside ADDED
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'gli'
4
+ require 'broadside'
5
+
6
+ include GLI::App
7
+ include Broadside::Utils
8
+
9
+ program_desc 'A command-line tool for deployment and development of docker applications.'
10
+
11
+ version Broadside::VERSION
12
+
13
+ subcommand_option_handling :normal
14
+ arguments :strict
15
+ synopsis_format :full
16
+
17
+ desc 'Configuration file to use.'
18
+ default_value 'config/broadside.conf.rb'
19
+ arg_name 'FILE'
20
+ flag [:c, :config]
21
+
22
+ def add_shared_deploy_configs(subcmd)
23
+ # deployment always requires target
24
+ subcmd.desc 'Deployment target to use, e.g. production_web'
25
+ subcmd.arg_name 'TARGET'
26
+ subcmd.flag [:t, :target], type: Symbol
27
+
28
+ subcmd.action do |global_options, options, args|
29
+ _DeployObj = Kernel.const_get("Broadside::#{Broadside.config.deploy.type.capitalize}Deploy")
30
+ _DeployObj.new(options).send(subcmd.name)
31
+ end
32
+ end
33
+
34
+ # GLI type coercions
35
+ accept Symbol do |val|
36
+ val.to_sym
37
+ end
38
+ accept Array do |val|
39
+ val.split(' ')
40
+ end
41
+ accept Fixnum do |val|
42
+ val.to_i
43
+ end
44
+
45
+ desc 'Deploy your application.'
46
+ command :deploy do |d|
47
+ d.desc 'Deploys without running migrations'
48
+ d.command :short do |subcmd|
49
+ subcmd.desc 'Docker tag for application container'
50
+ subcmd.arg_name 'TAG'
51
+ subcmd.flag [:tag]
52
+
53
+ add_shared_deploy_configs(subcmd)
54
+ end
55
+
56
+ d.desc 'Performs a full deployment (with migration)'
57
+ d.command :full do |subcmd|
58
+ subcmd.desc 'Docker tag for application container'
59
+ subcmd.arg_name 'TAG'
60
+ subcmd.flag [:tag]
61
+
62
+ add_shared_deploy_configs(subcmd)
63
+ end
64
+
65
+ d.desc 'Scales application to a given count'
66
+ d.command :scale do |subcmd|
67
+ subcmd.desc 'Specify a new scale for application'
68
+ subcmd.arg_name 'NUM'
69
+ subcmd.flag [:s, :scale], type: Fixnum
70
+
71
+ add_shared_deploy_configs(subcmd)
72
+ end
73
+
74
+ d.desc 'Creates a single instance of the application to run a command.'
75
+ d.command :run do |subcmd|
76
+ subcmd.desc 'Docker tag for application container'
77
+ subcmd.arg_name 'TAG'
78
+ subcmd.flag [:tag]
79
+
80
+ subcmd.desc 'Command to run (wrap argument in quotes)'
81
+ subcmd.arg_name 'COMMAND'
82
+ subcmd.flag [:command], type: Array
83
+
84
+ add_shared_deploy_configs(subcmd)
85
+ end
86
+
87
+ d.desc 'Rolls back n releases and deploys'
88
+ d.command :rollback do |subcmd|
89
+ subcmd.desc 'Number of releases to rollback'
90
+ subcmd.arg_name 'COUNT'
91
+ subcmd.flag [:r, :rollback], type: Fixnum
92
+
93
+ add_shared_deploy_configs(subcmd)
94
+ end
95
+
96
+ d.desc 'Gets information about what is currently deployed.'
97
+ d.command :status do |subcmd|
98
+ add_shared_deploy_configs(subcmd)
99
+ end
100
+
101
+ d.desc 'Tail the logs inside the running container.'
102
+ d.command :logtail do |subcmd|
103
+ subcmd.desc '0-based instance index'
104
+ subcmd.default_value '0'
105
+ subcmd.arg_name 'INSTANCE'
106
+ subcmd.flag [:n, :instance], type: Fixnum
107
+
108
+ add_shared_deploy_configs(subcmd)
109
+ end
110
+
111
+ d.desc 'Establish a secure shell on the instance running the container.'
112
+ d.command :ssh do |subcmd|
113
+ subcmd.desc '0-based instance index'
114
+ subcmd.default_value '0'
115
+ subcmd.arg_name 'INSTANCE'
116
+ subcmd.flag [:n, :instance], type: Fixnum
117
+
118
+ add_shared_deploy_configs(subcmd)
119
+ end
120
+
121
+ d.desc 'Establish a shell inside the running container.'
122
+ d.command :bash do |subcmd|
123
+ subcmd.desc '0-based instance index'
124
+ subcmd.default_value '0'
125
+ subcmd.arg_name 'INSTANCE'
126
+ subcmd.flag [:n, :instance], type: Fixnum
127
+
128
+ add_shared_deploy_configs(subcmd)
129
+ end
130
+ end
131
+
132
+ def call_hook(type, command)
133
+ hook = Broadside.config.base.send(type)
134
+ if hook.is_a?(Proc)
135
+ hook_args =
136
+ if command.parent.is_a?(GLI::Command)
137
+ {
138
+ command: command.parent.name,
139
+ subcommand: command.name
140
+ }
141
+ else
142
+ { command: command.name }
143
+ end
144
+ debug "Calling", type, "with args", hook_args
145
+ hook.call(hook_args)
146
+ end
147
+ end
148
+
149
+ pre do |global, command, options, args|
150
+ Broadside.load_config(global[:config])
151
+
152
+ call_hook(:prehook, command)
153
+ true
154
+ end
155
+
156
+ post do |global, command, options, args|
157
+ call_hook(:posthook, command)
158
+ true
159
+ end
160
+
161
+
162
+ on_error do |exception|
163
+ # false skips default error handling
164
+ case exception
165
+ when Broadside::MissingVariableError
166
+ error exception.message, "\nRun your last command with --help for more information."
167
+ false
168
+ else
169
+ true
170
+ end
171
+ end
172
+
173
+ exit run(ARGV)
data/broadside.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'broadside/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'broadside'
8
+ spec.version = Broadside::VERSION
9
+ spec.authors = ['Matthew Leung']
10
+ spec.email = ['leung.mattp@gmail.com']
11
+
12
+ spec.summary = 'A command-line tool for EC2 Container Service deployment.'
13
+ spec.homepage = 'https://github.com/lumoslabs/broadside'
14
+ spec.license = 'MIT'
15
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
16
+ spec.bindir = "bin"
17
+ spec.executables = ['broadside']
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_dependency 'aws-sdk', '~> 2.2.7'
21
+ spec.add_dependency 'rainbow', '~> 2.1'
22
+ spec.add_dependency 'gli', '~> 2.13'
23
+ spec.add_dependency 'dotenv', '>= 0.9.0'
24
+ spec.add_development_dependency 'rspec'
25
+ spec.add_development_dependency 'bundler', '~> 1.9'
26
+ spec.add_development_dependency 'fakefs'
27
+ end
data/lib/broadside.rb ADDED
@@ -0,0 +1,48 @@
1
+ require 'broadside/error'
2
+ require 'broadside/utils'
3
+ require 'broadside/configuration'
4
+ require 'broadside/configuration/struct'
5
+ require 'broadside/configuration/aws'
6
+ require 'broadside/configuration/base'
7
+ require 'broadside/configuration/deploy'
8
+ require 'broadside/configuration/ecs'
9
+ require 'broadside/deploy'
10
+ require 'broadside/deploy/ecs'
11
+ require 'broadside/version'
12
+
13
+ module Broadside
14
+ extend Utils
15
+
16
+ SYSTEM_CONFIG_FILE = "#{Dir.home}/.broadside/config.rb"
17
+
18
+ def self.configure
19
+ yield config
20
+ end
21
+
22
+ def self.load_config(config_file)
23
+ begin
24
+ load SYSTEM_CONFIG_FILE if File.exists?(SYSTEM_CONFIG_FILE)
25
+ rescue LoadError => e
26
+ error "Encountered an error loading system configuration file '#{SYSTEM_CONFIG_FILE}' !"
27
+ raise e
28
+ end
29
+
30
+ begin
31
+ load config_file
32
+ config.file = config_file
33
+ rescue LoadError => e
34
+ error "Encountered an error loading required configuration file '#{config_file}' !"
35
+ raise e
36
+ end
37
+
38
+ config.verify
39
+ end
40
+
41
+ def self.config
42
+ @config ||= Configuration.new
43
+ end
44
+
45
+ def self.reset!
46
+ @config = nil
47
+ end
48
+ end
@@ -0,0 +1,32 @@
1
+ module Broadside
2
+ class Configuration
3
+ include Utils
4
+
5
+ attr_accessor :base, :deploy, :ecs, :aws, :file
6
+
7
+ def initialize
8
+ @base = BaseConfig.new
9
+ end
10
+
11
+ def deploy
12
+ @deploy ||= DeployConfig.new
13
+ end
14
+
15
+ def aws
16
+ @aws ||= AwsConfig.new
17
+ end
18
+
19
+ def ecs
20
+ @ecs ||= EcsConfig.new
21
+ end
22
+
23
+ def verify
24
+ @base.verify(:application, :docker_image)
25
+ end
26
+
27
+ def method_missing(m, *args, &block)
28
+ warn "Unknown configuration '#{m}' provided, ignoring. Check your version of broadside?"
29
+ ConfigStruct.new
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,14 @@
1
+ require 'aws-sdk'
2
+
3
+ module Broadside
4
+ class Configuration
5
+ class AwsConfig < ConfigStruct
6
+ attr_accessor :region, :credentials
7
+
8
+ def initialize
9
+ @region = 'us-east-1'
10
+ @credentials = Aws::SharedCredentials.new.credentials
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,19 @@
1
+ require 'logger'
2
+
3
+ module Broadside
4
+ class Configuration
5
+ class BaseConfig < ConfigStruct
6
+ attr_accessor :application, :git_repo, :docker_image, :logger, :loglevel, :prehook, :posthook
7
+
8
+ def initialize
9
+ @application = nil
10
+ @docker_image = nil
11
+ @logger = Logger.new(STDOUT)
12
+ @logger.level = Logger::DEBUG
13
+ @logger.datetime_format = '%Y-%m-%d_%H:%M:%S'
14
+ @prehook = nil
15
+ @posthook = nil
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,114 @@
1
+ require 'dotenv'
2
+ require 'pathname'
3
+
4
+ module Broadside
5
+ class Configuration
6
+ class DeployConfig < ConfigStruct
7
+ include Utils
8
+
9
+ DEFAULT_PREDEPLOY_COMMANDS = [
10
+ ['bundle', 'exec', 'rake', '--trace', 'db:migrate']
11
+ ]
12
+
13
+ attr_accessor(
14
+ :type,
15
+ :tag,
16
+ :ssh,
17
+ :rollback,
18
+ :timeout,
19
+ :target,
20
+ :targets,
21
+ :scale,
22
+ :env_vars,
23
+ :command,
24
+ :instance,
25
+ :predeploy_commands
26
+ )
27
+
28
+ TARGET_ATTRIBUTE_VALIDATIONS = {
29
+ scale: ->(target_attribute) { validate_types([Fixnum], target_attribute) },
30
+ env_file: ->(target_attribute) { validate_types([String], target_attribute) },
31
+ command: ->(target_attribute) { validate_types([Array, NilClass], target_attribute) },
32
+ predeploy_commands: ->(target_attribute) { validate_predeploy(target_attribute) }
33
+ }
34
+
35
+ def initialize
36
+ @type = 'ecs'
37
+ @ssh = nil
38
+ @tag = nil
39
+ @rollback = 1
40
+ @timeout = 600
41
+ @target = nil
42
+ @targets = nil
43
+ @scale = nil
44
+ @env_vars = nil
45
+ @command = nil
46
+ @predeploy_commands = DEFAULT_PREDEPLOY_COMMANDS
47
+ @instance = 0
48
+ end
49
+
50
+ # Validates format of deploy targets
51
+ # Checks existence of provided target
52
+ def validate_targets!
53
+ @targets.each do |target, configuration|
54
+ TARGET_ATTRIBUTE_VALIDATIONS.each do |var, validation|
55
+ message = validation.call(configuration[var])
56
+
57
+ unless message.nil?
58
+ exception "Deploy target '#{@target}' parameter '#{var}' is invalid: #{message}"
59
+ end
60
+ end
61
+ end
62
+
63
+ unless @targets.has_key?(@target)
64
+ exception "Could not find deploy target #{@target} in configuration !"
65
+ end
66
+ end
67
+
68
+ # Loads deploy target data using provided target
69
+ def load_target!
70
+ validate_targets!
71
+
72
+ env_file = Pathname.new(@targets[@target][:env_file])
73
+
74
+ unless env_file.absolute?
75
+ dir = config.file.nil? ? Dir.pwd : Pathname.new(config.file).dirname
76
+ env_file = env_file.expand_path(dir)
77
+ end
78
+
79
+ if env_file.exist?
80
+ vars = Dotenv.load(env_file)
81
+ @env_vars = vars.map { |k,v| {'name'=> k, 'value' => v } }
82
+ else
83
+ exception "Could not find file '#{env_file}' for loading environment variables !"
84
+ end
85
+
86
+ @scale ||= @targets[@target][:scale]
87
+ @command = @targets[@target][:command]
88
+ @predeploy_commands = @targets[@target][:predeploy_commands] if @targets[@target][:predeploy_commands]
89
+ end
90
+
91
+ private
92
+
93
+ def self.validate_types(types, target_attribute)
94
+ unless types.include?(target_attribute.class)
95
+ return "'#{target_attribute}' must be of type [#{types.join('|')}], got '#{target_attribute.class}' !"
96
+ end
97
+
98
+ nil
99
+ end
100
+
101
+ def self.validate_predeploy(target_attribute)
102
+ return nil if target_attribute.nil?
103
+
104
+ return 'predeploy_commands must be an array' unless target_attribute.is_a?(Array)
105
+
106
+ target_attribute.each do |command|
107
+ return "predeploy_command '#{command}' must be an array" unless command.is_a?(Array)
108
+ end
109
+
110
+ nil
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,12 @@
1
+ module Broadside
2
+ class Configuration
3
+ class EcsConfig < ConfigStruct
4
+ attr_accessor :cluster, :poll_frequency
5
+
6
+ def initialize
7
+ @cluster = nil
8
+ @poll_frequency = 2
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,24 @@
1
+ module Broadside
2
+ class Configuration
3
+ class ConfigStruct
4
+ def verify(*args)
5
+ args.each do |var|
6
+ if self.send(var).nil?
7
+ raise Broadside::MissingVariableError, "Missing required #{self.class.to_s.split("::").last} variable '#{var}' !"
8
+ end
9
+ end
10
+ end
11
+
12
+ def to_h
13
+ self.instance_variables.inject({}) do |h, var|
14
+ h[var] = self.instance_variable_get(var)
15
+ h
16
+ end
17
+ end
18
+
19
+ def method_missing(m, *args, &block)
20
+ warn "Unknown configuration '#{m}' provided, ignoring. Check your version of broadside?"
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,106 @@
1
+ module Broadside
2
+ class Deploy
3
+ include Utils
4
+
5
+ attr_accessor :deploy_config
6
+
7
+ def initialize(opts)
8
+ @deploy_config = Broadside.config.deploy.dup
9
+ @deploy_config.tag = opts[:tag] || @deploy_config.tag
10
+ @deploy_config.target = opts[:target] || @deploy_config.target
11
+ @deploy_config.verify(:target, :targets)
12
+ @deploy_config.load_target!
13
+
14
+ @deploy_config.scale = opts[:scale] || @deploy_config.scale
15
+ @deploy_config.rollback = opts[:rollback] || @deploy_config.rollback
16
+ @deploy_config.instance = opts[:instance] || @deploy_config.instance
17
+ @deploy_config.command = opts[:command] || @deploy_config.command
18
+ end
19
+
20
+ def short
21
+ deploy
22
+ end
23
+
24
+ def full
25
+ run_predeploy
26
+ deploy
27
+ end
28
+
29
+ def deploy
30
+ @deploy_config.verify(:tag)
31
+ info "Deploying #{image_tag} to #{family}..."
32
+ yield
33
+ info 'Deployment complete.'
34
+ end
35
+
36
+ def rollback(count = @deploy_config.rollback)
37
+ @deploy_config.verify(:rollback)
38
+ info "Rolling back #{@deploy_config.rollback} release for #{family}..."
39
+ yield
40
+ info 'Rollback complete.'
41
+ end
42
+
43
+ def scale
44
+ info "Rescaling #{family} with scale=#{@deploy_config.scale}"
45
+ yield
46
+ info 'Rescaling complete.'
47
+ end
48
+
49
+ def run
50
+ @deploy_config.verify(:tag, :ssh, :command)
51
+ info "Running command [#{@deploy_config.command}] for #{family}..."
52
+ yield
53
+ info 'Complete.'
54
+ end
55
+
56
+ def run_predeploy
57
+ @deploy_config.verify(:tag, :ssh)
58
+ info "Running predeploy commands for #{family}..."
59
+ yield
60
+ info 'Predeploy complete.'
61
+ end
62
+
63
+ def status
64
+ info "Getting status information about #{family}"
65
+ yield
66
+ info 'Complete.'
67
+ end
68
+
69
+ def logtail
70
+ @deploy_config.verify(:instance)
71
+ yield
72
+ end
73
+
74
+ def ssh
75
+ @deploy_config.verify(:instance)
76
+ yield
77
+ end
78
+
79
+ def bash
80
+ @deploy_config.verify(:instance)
81
+ yield
82
+ end
83
+
84
+ protected
85
+
86
+ def family
87
+ "#{config.base.application}_#{@deploy_config.target}"
88
+ end
89
+
90
+ def image_tag
91
+ "#{config.base.docker_image}:#{@deploy_config.tag}"
92
+ end
93
+
94
+ def gen_ssh_cmd(ip, options = { tty: false })
95
+ opts = @deploy_config.ssh
96
+ cmd = 'ssh -o StrictHostKeyChecking=no'
97
+ cmd << ' -t -t' if options[:tty]
98
+ cmd << " -i #{opts[:keyfile]}" if opts[:keyfile]
99
+ if opts[:proxy]
100
+ cmd << " -o ProxyCommand=\"ssh #{opts[:proxy][:host]} nc #{ip} #{opts[:proxy][:port]}\""
101
+ end
102
+ cmd << " #{opts[:user]}@#{ip}"
103
+ cmd
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,322 @@
1
+ require 'aws-sdk'
2
+ require 'open3'
3
+ require 'pp'
4
+ require 'rainbow'
5
+ require 'shellwords'
6
+
7
+ module Broadside
8
+ class EcsDeploy < Deploy
9
+ def initialize(opts)
10
+ super(opts)
11
+ config.ecs.verify(:cluster, :poll_frequency)
12
+ check_service_existence
13
+ end
14
+
15
+ def deploy
16
+ super do
17
+ update_task
18
+
19
+ begin
20
+ update_service
21
+ rescue SignalException::Interrupt
22
+ error 'Caught interrupt signal, rolling back...'
23
+ rollback(1)
24
+ error 'Deployment did not finish successfully.'
25
+ abort
26
+ rescue StandardError => e
27
+ error e.inspect, "\n", e.backtrace.join("\n")
28
+ error 'Deploy failed! Rolling back...'
29
+ rollback(1)
30
+ error 'Deployment did not finish successfully.'
31
+ abort
32
+ end
33
+ end
34
+ end
35
+
36
+ def rollback(count = @deploy_config.rollback)
37
+ super do
38
+ begin
39
+ deregister_tasks(count)
40
+ update_service
41
+ rescue StandardError => e
42
+ error 'Rollback failed to complete!'
43
+ raise e
44
+ end
45
+ end
46
+ end
47
+
48
+ def scale
49
+ super do
50
+ update_service
51
+ end
52
+ end
53
+
54
+ def run
55
+ super do
56
+ update_task
57
+
58
+ begin
59
+ run_command(@deploy_config.command)
60
+ ensure
61
+ deregister_tasks(1)
62
+ end
63
+ end
64
+ end
65
+
66
+ # runs before deploy commands using the latest task definition
67
+ def run_predeploy
68
+ super do
69
+ update_task
70
+
71
+ begin
72
+ @deploy_config.predeploy_commands.each do |command|
73
+ run_command(command)
74
+ end
75
+ ensure
76
+ deregister_tasks(1)
77
+ end
78
+ end
79
+ end
80
+
81
+ def status
82
+ super do
83
+ td = get_latest_task_def
84
+ ips = get_running_instance_ips
85
+ info "\n---------------",
86
+ "\nDeployed task definition information:\n",
87
+ Rainbow(PP.pp(td, '')).blue,
88
+ "\nPrivate ips of instances running containers:\n",
89
+ Rainbow(ips.join(' ')).blue,
90
+ "\n\nssh command:\n#{Rainbow(gen_ssh_cmd(ips.first)).cyan}",
91
+ "\n---------------\n"
92
+ end
93
+ end
94
+
95
+ def logtail
96
+ super do
97
+ ip = get_running_instance_ip_at_index!(@deploy_config.instance)
98
+ debug "Tailing logs for running container at ip #{ip}..."
99
+ search_pattern = Shellwords.shellescape(family)
100
+ cmd = "docker logs -f --tail=10 `docker ps -n 1 --quiet --filter name=#{search_pattern}`"
101
+ tail_cmd = gen_ssh_cmd(ip) + " '#{cmd}'"
102
+ exec tail_cmd
103
+ end
104
+ end
105
+
106
+ def ssh
107
+ super do
108
+ ip = get_running_instance_ip_at_index!(@deploy_config.instance)
109
+ debug "Establishing an SSH connection to ip #{ip}..."
110
+ exec gen_ssh_cmd(ip)
111
+ end
112
+ end
113
+
114
+ def bash
115
+ super do
116
+ ip = get_running_instance_ip_at_index!(@deploy_config.instance)
117
+ debug "Running bash for running container at ip #{ip}..."
118
+ search_pattern = Shellwords.shellescape(family)
119
+ cmd = "docker exec -i -t `docker ps -n 1 --quiet --filter name=#{search_pattern}` bash"
120
+ bash_cmd = gen_ssh_cmd(ip, tty: true) + " '#{cmd}'"
121
+ exec bash_cmd
122
+ end
123
+ end
124
+
125
+ private
126
+
127
+ def get_running_instance_ip_at_index(index)
128
+ ips = get_running_instance_ips
129
+ ips.size > index ? ips[index] : false
130
+ end
131
+
132
+ def get_running_instance_ip_at_index!(index)
133
+ ip = get_running_instance_ip_at_index(index)
134
+ return ip if ip
135
+ exception 'Instance index greater than available instance count.'
136
+ end
137
+
138
+ # removes latest n task definitions
139
+ def deregister_tasks(count)
140
+ task_definition_ids = ecs_client.list_task_definitions({family_prefix: family}).task_definition_arns
141
+ task_definition_ids.last(count).each do |td_id|
142
+ ecs_client.deregister_task_definition({task_definition: td_id})
143
+ debug "Deregistered #{td_id}"
144
+ end
145
+ end
146
+
147
+ # creates a new task revision using current directory's env vars and provided tag
148
+ def update_task
149
+ debug "Creating a new task definition..."
150
+ new_task_def = create_new_task_revision
151
+
152
+ #TODO instead of first, use select to cover task defs w multiple containers
153
+ new_task_def[:container_definitions].first[:environment] = @deploy_config.env_vars
154
+ new_task_def[:container_definitions].first[:image] = image_tag
155
+ new_task_def[:container_definitions].first[:command] = @deploy_config.command
156
+ new_task_def_id = ecs_client.register_task_definition(new_task_def).task_definition.task_definition_arn
157
+ debug "Successfully created #{new_task_def_id}"
158
+ end
159
+
160
+ # reloads the service using the latest task definition
161
+ def update_service
162
+ td = get_latest_task_def_id
163
+ debug "Updating #{family} with scale=#{@deploy_config.scale} using task #{td}..."
164
+ resp = ecs_client.update_service({
165
+ cluster: config.ecs.cluster,
166
+ service: family,
167
+ task_definition: get_latest_task_def_id,
168
+ desired_count: @deploy_config.scale
169
+ })
170
+ if resp.successful?
171
+ begin
172
+ ecs_client.wait_until(:services_stable, {cluster: config.ecs.cluster, services: [family]}) do |w|
173
+ w.max_attempts = @deploy_config.timeout.nil? ? @deploy_config.timeout : @deploy_config.timeout / config.ecs.poll_frequency
174
+ w.delay = config.ecs.poll_frequency
175
+ seen_event = nil
176
+ w.before_wait do |attempt, response|
177
+ debug "(#{attempt}/#{w.max_attempts}) Polling ECS for events..."
178
+ # skip first event since it doesn't apply to current request
179
+ if response.services[0].events.first &&
180
+ response.services[0].events.first.id != seen_event &&
181
+ attempt > 1
182
+ seen_event = response.services[0].events.first.id
183
+ debug(response.services[0].events.first.message)
184
+ end
185
+ end
186
+ end
187
+ rescue Aws::Waiters::Errors::TooManyAttemptsError
188
+ exception 'Deploy did not finish in the expected amount of time.'
189
+ end
190
+ else
191
+ exception 'Failed to update service during deploy.'
192
+ end
193
+ end
194
+
195
+ def run_command(command)
196
+ command_name = command.join(' ')
197
+ resp = ecs_client.run_task({
198
+ cluster: config.ecs.cluster,
199
+ task_definition: get_latest_task_def_id,
200
+ overrides: {
201
+ container_overrides: [
202
+ {
203
+ name: family,
204
+ command: command
205
+ },
206
+ ],
207
+ },
208
+ count: 1,
209
+ started_by: "before_deploy:#{command_name}"[0...36]
210
+ })
211
+ if resp.successful?
212
+ task_id = resp.tasks[0].task_arn
213
+ debug "Launched #{command_name} task #{task_id}"
214
+ debug "Waiting for #{command_name} to complete..."
215
+ ecs_client.wait_until(:tasks_stopped, {cluster: config.ecs.cluster, tasks: [task_id]}) do |w|
216
+ w.max_attempts = nil
217
+ w.delay = config.ecs.poll_frequency
218
+ w.before_attempt do |attempt|
219
+ debug "Attempt #{attempt}: waiting for #{command_name} to complete..."
220
+ end
221
+ end
222
+ debug 'Task finished running, getting logs...'
223
+ info "#{command_name} task container logs:\n#{get_container_logs(task_id)}"
224
+ if(code = get_task_exit_code(task_id)) == 0
225
+ debug "#{command_name} task #{task_id} exited with status code 0"
226
+ else
227
+ exception "#{command_name} task #{task_id} exited with a non-zero status code #{code}!"
228
+ end
229
+ else
230
+ raise "Failed to run #{command_name} task."
231
+ end
232
+ end
233
+
234
+ def get_container_logs(task_id)
235
+ ip = get_running_instance_ips(task_id).first
236
+ debug "Found ip of container instance: #{ip}"
237
+
238
+ find_container_id_cmd = "#{gen_ssh_cmd(ip)} \"docker ps -aqf 'label=com.amazonaws.ecs.task-arn=#{task_id}'\""
239
+ debug "Running command to find container id:\n#{find_container_id_cmd}"
240
+ container_id = `#{find_container_id_cmd}`.strip
241
+
242
+ get_container_logs_cmd = "#{gen_ssh_cmd(ip)} \"docker logs #{container_id}\""
243
+ debug "Running command to get logs of container #{container_id}:",
244
+ "\n#{get_container_logs_cmd}"
245
+
246
+ logs = nil
247
+ Open3.popen3(get_container_logs_cmd) do |_, stdout, stderr, _|
248
+ logs = "STDOUT:--\n#{stdout.read}\nSTDERR:--\n#{stderr.read}"
249
+ end
250
+ logs
251
+ end
252
+
253
+ def get_task_exit_code(task_id)
254
+ task = ecs_client.describe_tasks({cluster: config.ecs.cluster, tasks: [task_id]}).tasks.first
255
+ task.containers.first.exit_code
256
+ end
257
+
258
+ def get_running_instance_ips(task_ids = nil)
259
+ task_arns = nil
260
+ if task_ids.nil?
261
+ task_arns = ecs_client.list_tasks({cluster: config.ecs.cluster, family: family}).task_arns
262
+ if task_arns.empty?
263
+ exception "No running tasks found for '#{family}' on cluster '#{config.ecs.cluster}' !"
264
+ end
265
+ elsif task_ids.class == String
266
+ task_arns = [task_ids]
267
+ else
268
+ task_arns = task_ids
269
+ end
270
+
271
+ tasks = ecs_client.describe_tasks({cluster: config.ecs.cluster, tasks: task_arns}).tasks
272
+ container_instance_arns = tasks.map { |t| t.container_instance_arn }
273
+ container_instances = ecs_client.describe_container_instances({
274
+ cluster: config.ecs.cluster, container_instances: container_instance_arns
275
+ }).container_instances
276
+ ec2_instance_ids = container_instances.map { |ci| ci.ec2_instance_id }
277
+ reservations = ec2_client.describe_instances({instance_ids: ec2_instance_ids}).reservations
278
+ instances = reservations.map { |r| r.instances }.flatten
279
+ private_ips = instances.map { |i| i.private_ip_address }
280
+ private_ips
281
+ end
282
+
283
+ def get_latest_task_def
284
+ ecs_client.describe_task_definition({task_definition: get_latest_task_def_id}).task_definition.to_h
285
+ end
286
+
287
+ def get_latest_task_def_id
288
+ task_defs = ecs_client.list_task_definitions({family_prefix: family})
289
+ task_defs.task_definition_arns.last
290
+ end
291
+
292
+ def create_new_task_revision
293
+ task_def = get_latest_task_def
294
+ task_def.delete(:task_definition_arn)
295
+ task_def.delete(:requires_attributes)
296
+ task_def.delete(:revision)
297
+ task_def.delete(:status)
298
+ task_def
299
+ end
300
+
301
+ def ecs_client
302
+ @ecs_client ||= Aws::ECS::Client.new({
303
+ region: config.aws.region,
304
+ credentials: config.aws.credentials
305
+ })
306
+ end
307
+
308
+ def ec2_client
309
+ @ec2_client ||= Aws::EC2::Client.new({
310
+ region: config.aws.region,
311
+ credentials: config.aws.credentials
312
+ })
313
+ end
314
+
315
+ def check_service_existence
316
+ resp = ecs_client.describe_services({cluster: config.ecs.cluster, services: [family]})
317
+ unless resp.failures.empty?
318
+ exception "Could not find ECS service '#{family}' in cluster '#{config.ecs.cluster}' !"
319
+ end
320
+ end
321
+ end
322
+ end
@@ -0,0 +1,10 @@
1
+ module Broadside
2
+ class MissingVariableError < StandardError
3
+ end
4
+
5
+ class Error < StandardError
6
+ def initialize(msg = 'Broadside encountered an error !')
7
+ super
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,27 @@
1
+ module Broadside
2
+ module Utils
3
+ def debug(*args)
4
+ config.base.logger.debug(args.join(' '))
5
+ end
6
+
7
+ def info(*args)
8
+ config.base.logger.info(args.join(' '))
9
+ end
10
+
11
+ def warn(*args)
12
+ config.base.logger.warn(args.join(' '))
13
+ end
14
+
15
+ def error(*args)
16
+ config.base.logger.error(args.join(' '))
17
+ end
18
+
19
+ def exception(*args)
20
+ raise Broadside::Error, args.join(' ')
21
+ end
22
+
23
+ def config
24
+ Broadside.config
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,3 @@
1
+ module Broadside
2
+ VERSION = '1.0.0'
3
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: broadside
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
- - matl33t
7
+ - Matthew Leung
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2016-04-22 00:00:00.000000000 Z
11
+ date: 2016-06-21 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: aws-sdk
@@ -25,19 +25,19 @@ dependencies:
25
25
  - !ruby/object:Gem::Version
26
26
  version: 2.2.7
27
27
  - !ruby/object:Gem::Dependency
28
- name: colorize
28
+ name: rainbow
29
29
  requirement: !ruby/object:Gem::Requirement
30
30
  requirements:
31
31
  - - "~>"
32
32
  - !ruby/object:Gem::Version
33
- version: 0.7.7
33
+ version: '2.1'
34
34
  type: :runtime
35
35
  prerelease: false
36
36
  version_requirements: !ruby/object:Gem::Requirement
37
37
  requirements:
38
38
  - - "~>"
39
39
  - !ruby/object:Gem::Version
40
- version: 0.7.7
40
+ version: '2.1'
41
41
  - !ruby/object:Gem::Dependency
42
42
  name: gli
43
43
  requirement: !ruby/object:Gem::Requirement
@@ -66,6 +66,20 @@ dependencies:
66
66
  - - ">="
67
67
  - !ruby/object:Gem::Version
68
68
  version: 0.9.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'
69
83
  - !ruby/object:Gem::Dependency
70
84
  name: bundler
71
85
  requirement: !ruby/object:Gem::Requirement
@@ -80,13 +94,51 @@ dependencies:
80
94
  - - "~>"
81
95
  - !ruby/object:Gem::Version
82
96
  version: '1.9'
97
+ - !ruby/object:Gem::Dependency
98
+ name: fakefs
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'
83
111
  description:
84
112
  email:
85
- - mleung@lumoslabs.com
86
- executables: []
113
+ - leung.mattp@gmail.com
114
+ executables:
115
+ - broadside
87
116
  extensions: []
88
117
  extra_rdoc_files: []
89
- files: []
118
+ files:
119
+ - ".gitignore"
120
+ - ".gitmodules"
121
+ - ".rspec"
122
+ - ".travis.yml"
123
+ - AUTHORS
124
+ - CHANGELOG.md
125
+ - Gemfile
126
+ - LICENSE.txt
127
+ - README.md
128
+ - bin/broadside
129
+ - broadside.gemspec
130
+ - lib/broadside.rb
131
+ - lib/broadside/configuration.rb
132
+ - lib/broadside/configuration/aws.rb
133
+ - lib/broadside/configuration/base.rb
134
+ - lib/broadside/configuration/deploy.rb
135
+ - lib/broadside/configuration/ecs.rb
136
+ - lib/broadside/configuration/struct.rb
137
+ - lib/broadside/deploy.rb
138
+ - lib/broadside/deploy/ecs.rb
139
+ - lib/broadside/error.rb
140
+ - lib/broadside/utils.rb
141
+ - lib/broadside/version.rb
90
142
  homepage: https://github.com/lumoslabs/broadside
91
143
  licenses:
92
144
  - MIT
@@ -110,5 +162,5 @@ rubyforge_project:
110
162
  rubygems_version: 2.2.3
111
163
  signing_key:
112
164
  specification_version: 4
113
- summary: A command-line tool for deployment using docker. Coming soon.
165
+ summary: A command-line tool for EC2 Container Service deployment.
114
166
  test_files: []