kage 0.9.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in kage.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Tatsuhiko Miyagawa
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # Kage
2
+
3
+ Kage (kah-geh) is an HTTP shadow proxy server that sits between clients and your server(s) to enable "shadow requests".
4
+
5
+ Kage can be used to duplex requests to the master (production) server and shadow servers that have newer code changes that are going to be deployed. By shadowing requests to the new code you can make sure there are no big/surprising changes in the response in terms of data, performance and database loads etc.
6
+
7
+ You can customize the behavior of Kage with simple callbacks, when it chooses which backends to send shadow requests to (or not at all), appends or deletes HTTP headers per backend, and examines the complete HTTP response (including headers and body).
8
+
9
+ ## Features
10
+
11
+ * Support HTTP/1.0 and HTTP/1.1 with partial keep-alive support (See below)
12
+ * Callback to decide backends per request URLs
13
+ * Callback to manipulate request headers per request and backend
14
+ * Callback to examine responses from multiple backends (e.g. calcurate diffs)
15
+
16
+ Kage does not yet support:
17
+
18
+ * SSL
19
+ * HTTP/1.1 requests pipelining
20
+
21
+ ## Usage
22
+
23
+ ```ruby
24
+ require 'kage'
25
+
26
+ def compare(a, b)
27
+ p [a, b]
28
+ end
29
+
30
+ Kage::ProxyServer.start do |server|
31
+ server.port = 8090
32
+ server.host = '0.0.0.0'
33
+ server.debug = false
34
+
35
+ # backends can share the same host/port
36
+ server.add_master_backend(:production, 'localhost', 80)
37
+ server.add_backend(:sandbox, 'localhost', 80)
38
+
39
+ server.client_timeout = 15
40
+ server.backend_timeout = 10
41
+
42
+ # Dispatch all GET requests to multiple backends, otherwise only :production
43
+ server.on_select_backends do |request, headers|
44
+ if request[:method] == 'GET'
45
+ [:production, :sandbox]
46
+ else
47
+ [:production]
48
+ end
49
+ end
50
+
51
+ # Add optional headers
52
+ server.on_munge_headers do |backend, headers|
53
+ headers['X-Kage-Session'] = self.session_id
54
+ headers['X-Kage-Sandbox'] = 1 if backend == :sandbox
55
+ end
56
+
57
+ # This callback is only fired when there are multiple backends to respond
58
+ server.on_backends_finished do |backends, requests, responses|
59
+ compare(responses[:production][:data], responses[:sandbox][:data])
60
+ end
61
+ end
62
+ ```
63
+
64
+ Read more sample code under the `examples/` directory.
65
+
66
+ ## Keep-alives
67
+
68
+ Kage supports keep-alives for single backend requests, i.e. for requests where `on_select_backends` returns only the master backend.
69
+
70
+ To make `on_backend_finished` callback simpler, if the current request matches with multiple backends, Kage sends `Connection: close` to the backends so that the callback will only get one response per backend in `responses` hash, which would look like:
71
+
72
+ ```ruby
73
+ responses = {
74
+ :original => {:data => "(RAW HTTP response)", :elapsed => 0.1234},
75
+ :sandbox => {:data => "(RAW HTTP response)", :elspaed => 0.2333},
76
+ }
77
+ ```
78
+
79
+ ## Authors
80
+
81
+ Tatsuhiko Miyagawa, Yusuke Mito
82
+
83
+ ## Acknowledgements
84
+
85
+ Ilya Grigorik, Jos Boumans
86
+
87
+ ## Based On
88
+
89
+ * [EventMachine](http://rubyeventmachine.com/)
90
+ * [em-proxy](https://github.com/igrigorik/em-proxy/)
91
+ * [http_parser.rb](https://github.com/tmm1/http_parser.rb)
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
data/examples/proxy.rb ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env ruby
2
+ require 'kage'
3
+
4
+ def compare(a, b)
5
+ p [a, b]
6
+ end
7
+
8
+ Kage::ProxyServer.start do |server|
9
+ server.port = 8090
10
+ server.host = '0.0.0.0'
11
+ server.debug = false
12
+
13
+ # backends can share the same host/port
14
+ server.add_master_backend(:production, 'localhost', 80)
15
+ server.add_backend(:sandbox, 'localhost', 80)
16
+
17
+ server.client_timeout = 15
18
+ server.backend_timeout = 10
19
+
20
+ # Dispatch all GET requests to multiple backends, otherwise only :production
21
+ server.on_select_backends do |request, headers|
22
+ if request[:method] == 'GET'
23
+ [:production, :sandbox]
24
+ else
25
+ [:production]
26
+ end
27
+ end
28
+
29
+ # Add optional headers
30
+ server.on_munge_headers do |backend, headers|
31
+ headers['X-Kage-Session'] = self.session_id
32
+ headers['X-Kage-Sandbox'] = 1 if backend == :sandbox
33
+ end
34
+
35
+ # This callback is only fired when there are multiple backends to respond
36
+ server.on_backends_finished do |backends, requests, responses|
37
+ compare(responses[:production][:data], responses[:sandbox][:data])
38
+ end
39
+ end
data/kage.gemspec ADDED
@@ -0,0 +1,22 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/kage/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Tatsuhiko Miyagawa"]
6
+ gem.email = ["miyagawa@bulknews.net"]
7
+ gem.description = %q{em-proxy based shadow proxy server}
8
+ gem.summary = %q{Kage (kah-geh) is an HTTP shadow proxy server that sits between your production servers to send shaddow traffic to the servers with new code changes.}
9
+ gem.homepage = "https://github.com/cookpad/kage"
10
+
11
+ gem.files = `git ls-files`.split($\)
12
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
+ gem.name = "kage"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = Kage::VERSION
17
+
18
+ gem.add_dependency 'em-proxy', '>= 0.1.7'
19
+ gem.add_dependency 'http_parser.rb', '>= 0.5.3'
20
+
21
+ gem.add_development_dependency 'rspec'
22
+ end
@@ -0,0 +1,167 @@
1
+ require 'http/parser'
2
+
3
+ module Kage
4
+ module Connection
5
+ attr_accessor :master_backend, :session_id
6
+
7
+ # http://eventmachine.rubyforge.org/EventMachine/Connection.html#unbind-instance_method
8
+ def close_connection(*args)
9
+ @server_side_close = true
10
+ super
11
+ end
12
+
13
+ def unbind
14
+ if !@server_side_close
15
+ if @state == :request
16
+ info "Client disconnected in the request phase"
17
+ super
18
+ elsif @backends && @backends.size == 1 && @responses[master_backend]
19
+ info "Client disconnected after the master response. Closing master"
20
+ super
21
+ else
22
+ info "Client disconnected. Waiting for all backends to finish"
23
+ end
24
+ end
25
+ end
26
+
27
+ def cleanup!
28
+ @parser.reset!
29
+ end
30
+
31
+ def all_servers_finished?
32
+ @servers.values.compact.size.zero?
33
+ end
34
+
35
+ def callback(cb, *args)
36
+ if @callbacks[cb]
37
+ instance_exec *args, &@callbacks[cb]
38
+ elsif block_given?
39
+ yield
40
+ end
41
+ rescue Exception => e
42
+ info "#{e} - #{e.backtrace}"
43
+ end
44
+
45
+ def build_headers(parser, headers)
46
+ "#{parser.http_method} #{parser.request_url} HTTP/#{parser.http_version.join(".")}\r\n" +
47
+ headers.map{|k, v| "#{k}: #{v}\r\n" }.join('') +
48
+ "\r\n"
49
+ end
50
+
51
+ def connect_backends!(req, headers, backends)
52
+ @backends = select_backends(req, headers).select {|b| backends[b]}
53
+ @backends.unshift master_backend unless @backends.include? master_backend
54
+ info "Backends for #{req[:method]} #{req[:url]} -> #{@backends}"
55
+
56
+ @backends.each do |name|
57
+ s = server name, backends[name]
58
+ s.comm_inactivity_timeout = 10
59
+ end
60
+ end
61
+
62
+ def select_backends(request, headers)
63
+ callback(:on_select_backends, request, headers) { [master_backend] }
64
+ end
65
+
66
+ def handle(server)
67
+ self.comm_inactivity_timeout = server.client_timeout
68
+ self.master_backend = server.master
69
+
70
+ @session_id = "%016x" % Random.rand(2**64)
71
+ info "New connection"
72
+
73
+ @callbacks = server.callbacks
74
+
75
+ @responses = {}
76
+ @request = {}
77
+ @requests = []
78
+
79
+ @state = :request
80
+
81
+ @parser = HTTP::Parser.new
82
+ @parser.on_message_begin = proc do
83
+ @start_time ||= Time.now
84
+ @state = :request
85
+ end
86
+
87
+ @parser.on_headers_complete = proc do |headers|
88
+ @request = {
89
+ :method => @parser.http_method,
90
+ :path => @parser.request_path,
91
+ :url => @parser.request_url,
92
+ :headers => headers
93
+ }
94
+ @requests.push @request
95
+ info "#{@request[:method]} #{@request[:url]}"
96
+
97
+ # decide backends on the first request
98
+ unless @backends
99
+ connect_backends!(@request, headers, server.backends)
100
+ end
101
+
102
+ if @backends.size > 1
103
+ info "Multiple backends for this session: Force close connection (disable keep-alives)"
104
+ headers['Connection'] = 'close'
105
+ end
106
+
107
+ @servers.keys.each do |backend|
108
+ callback :on_munge_headers, backend, headers
109
+ relay_to_servers [build_headers(@parser, headers), [backend]]
110
+ end
111
+ end
112
+
113
+ @parser.on_body = proc do |chunk|
114
+ relay_to_servers chunk
115
+ end
116
+
117
+ @parser.on_message_complete = proc do
118
+ @state = :response
119
+ end
120
+
121
+ on_data do |data|
122
+ begin
123
+ @parser << data
124
+ rescue HTTP::Parser::Error
125
+ info "HTTP parser error: Bad Request"
126
+ EM.next_tick { close_connection_after_writing }
127
+ end
128
+ nil
129
+ end
130
+
131
+ # modify / process response stream
132
+ on_response do |backend, resp|
133
+ @responses[backend] ||= {}
134
+ @responses[backend][:elapsed] = Time.now.to_f - @start_time.to_f
135
+ @responses[backend][:data] ||= ''
136
+ @responses[backend][:data] += resp
137
+
138
+ resp if backend == master_backend
139
+ end
140
+
141
+ # termination logic
142
+ on_finish do |backend|
143
+ # terminate connection (in duplex mode, you can terminate when prod is done)
144
+ if all_servers_finished?
145
+ if @backends.all? {|b| @responses[b]}
146
+ callback :on_backends_finished, @backends, @requests, @responses if @backends.size > 1
147
+ else
148
+ info "Server(s) disconnected before response returned: #{@backends.reject {|b| @responses[b]}}"
149
+ end
150
+ cleanup!
151
+ end
152
+
153
+ if backend == master_backend
154
+ info "Master backend closed connection. Closing downstream"
155
+ :close
156
+ end
157
+ end
158
+ rescue Exception => e
159
+ info "#{e} - #{e.backtrace}"
160
+ end
161
+
162
+ def info(msg)
163
+ puts "#{Time.now.strftime('%H:%M:%S')} [#{@session_id}] #{msg}"
164
+ end
165
+ end
166
+ end
167
+
@@ -0,0 +1,50 @@
1
+ require 'em-proxy'
2
+ require 'kage/connection'
3
+
4
+ module Kage
5
+ class ProxyServer < ::Proxy
6
+ attr_accessor :host, :port, :debug, :client_timeout, :backend_timeout, :backends, :master, :callbacks
7
+
8
+ def initialize(options = {})
9
+ @host = '0.0.0.0'
10
+ @port = 80
11
+ @debug = false
12
+ @client_timeout = 15
13
+ @backend_timeout = 30
14
+ @backends = {}
15
+ @master = nil
16
+ @callbacks = {}
17
+
18
+ options.each do |k, v|
19
+ send("#{k}=", v)
20
+ end
21
+ end
22
+
23
+ def on_select_backends(&blk); @callbacks[:on_select_backends] = blk; end
24
+ def on_munge_headers(&blk); @callbacks[:on_munge_headers] = blk; end
25
+ def on_backends_finished(&blk); @callbacks[:on_backends_finished] = blk; end
26
+
27
+ def add_master_backend(name, host, port = 80)
28
+ @master = name
29
+ add_backend(name, host, port)
30
+ end
31
+
32
+ def add_backend(name, host, port = 80)
33
+ @backends[name] = {:host => host, :port => port}
34
+ end
35
+
36
+ def self.start(options = {}, &blk)
37
+ server = new(options)
38
+ server.instance_eval &blk
39
+
40
+ if server.master.nil?
41
+ raise "Configuration error: no master backend defined"
42
+ end
43
+
44
+ super(:host => server.host, :port => server.port, :debug => server.debug) do |conn|
45
+ conn.extend Connection
46
+ conn.handle(server)
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,3 @@
1
+ module Kage
2
+ VERSION = "0.9.0"
3
+ end
data/lib/kage.rb ADDED
@@ -0,0 +1,3 @@
1
+ require "kage/version"
2
+ require "kage/connection"
3
+ require "kage/proxy_server"
metadata ADDED
@@ -0,0 +1,91 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kage
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.9.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Tatsuhiko Miyagawa
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-10-22 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: em-proxy
16
+ requirement: &70352387160200 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: 0.1.7
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *70352387160200
25
+ - !ruby/object:Gem::Dependency
26
+ name: http_parser.rb
27
+ requirement: &70352387159700 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: 0.5.3
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: *70352387159700
36
+ - !ruby/object:Gem::Dependency
37
+ name: rspec
38
+ requirement: &70352387159300 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ! '>='
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ type: :development
45
+ prerelease: false
46
+ version_requirements: *70352387159300
47
+ description: em-proxy based shadow proxy server
48
+ email:
49
+ - miyagawa@bulknews.net
50
+ executables: []
51
+ extensions: []
52
+ extra_rdoc_files: []
53
+ files:
54
+ - .gitignore
55
+ - Gemfile
56
+ - LICENSE
57
+ - README.md
58
+ - Rakefile
59
+ - examples/proxy.rb
60
+ - kage.gemspec
61
+ - lib/kage.rb
62
+ - lib/kage/connection.rb
63
+ - lib/kage/proxy_server.rb
64
+ - lib/kage/version.rb
65
+ homepage: https://github.com/cookpad/kage
66
+ licenses: []
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ none: false
73
+ requirements:
74
+ - - ! '>='
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ required_rubygems_version: !ruby/object:Gem::Requirement
78
+ none: false
79
+ requirements:
80
+ - - ! '>='
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ requirements: []
84
+ rubyforge_project:
85
+ rubygems_version: 1.8.15
86
+ signing_key:
87
+ specification_version: 3
88
+ summary: Kage (kah-geh) is an HTTP shadow proxy server that sits between your production
89
+ servers to send shaddow traffic to the servers with new code changes.
90
+ test_files: []
91
+ has_rdoc: