lib/invoker/power/balancer.rb in invoker-1.0.4 vs lib/invoker/power/balancer.rb in invoker-1.1.0
- old
+ new
@@ -1,5 +1,8 @@
+require 'em-proxy'
+require 'http-parser'
+
module Invoker
module Power
class BalancerConnection < EventMachine::ProxyServer::Connection
attr_accessor :host, :ip, :port
def set_host(host, selected_backend)
@@ -43,11 +46,11 @@
class Balancer
attr_accessor :connection, :http_parser, :session
DEV_MATCH_REGEX = /([\w-]+)\.dev(\:\d+)?$/
def self.run(options = {})
- EventMachine.start_server('0.0.0.0', Invoker::CONFIG.http_port,
+ EventMachine.start_server('0.0.0.0', Invoker.config.http_port,
BalancerConnection, options) do |connection|
balancer = Balancer.new(connection)
balancer.install_callbacks
end
end
@@ -66,13 +69,13 @@
connection.on_finish { |backend, name| frontend_disconnect(backend, name) }
end
def headers_received(header)
@session = UUID.generate()
- config = select_backend_config(header['Host'])
- if config
- connection.server(session, host: '0.0.0.0', port: config.port)
+ dns_check_response = select_backend_config(header['Host'])
+ if dns_check_response && dns_check_response.port
+ connection.server(session, host: '0.0.0.0', port: dns_check_response.port)
connection.relay_to_servers(@buffer.join)
@buffer = []
else
return_error_page(404)
connection.close_connection_after_writing
@@ -100,30 +103,37 @@
@backend_data = true
data
end
def frontend_disconnect(backend, name)
- http_parser.reset()
+ http_parser.reset
unless @backend_data
Invoker::Logger.puts("\nApplication not running. Returning error page.".color(:red))
return_error_page(503)
end
@backend_data = false
- connection.close_connection_after_writing() if backend == session
+ connection.close_connection_after_writing if backend == session
end
def extract_host_from_domain(host)
host.match(DEV_MATCH_REGEX)
end
private
+
def select_backend_config(host)
matching_string = extract_host_from_domain(host)
return nil unless matching_string
if selected_app = matching_string[1]
- Invoker::CONFIG.process(selected_app)
+ dns_check(process_name: selected_app)
else
nil
+ end
+ end
+
+ def dns_check(dns_args)
+ Invoker::IPC::UnixClient.send_command("dns_check", dns_args) do |dns_response|
+ dns_response
end
end
def return_error_page(status)
http_response = Invoker::Power::HttpResponse.new()