forked from nkallen/gogaruco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.rb
executable file
·59 lines (50 loc) · 1.72 KB
/
proxy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env ruby
['rubygems', 'activesupport', 'eventmachine', 'socket', 'optparse'].each { |dependency| require dependency }
['util/statosaurus', 'util/line_buffered_connection', 'util/deferrable'].each { |dependency| require dependency }
['proxy/server', 'proxy/balancers/first', 'proxy/balancers/random', 'proxy/balancers/round_robin', 'proxy/balancers/least_connections', 'proxy/balancers/sticky'].each { |dependency| require dependency }
begin
$options = {
:balancer => First,
:port => 10000,
:count => 10,
:host => "0.0.0.0"
}
OptionParser.new do |opts|
opts.on('-b', "--balancer BALANCER", String) { |balancer| $options[:balancer] = balancer.constantize }
opts.on('-n', "--number COUNT", Integer) { |count| $options[:count] = count }
opts.on('-p', "--port PORT", Integer) { |port| $options[:port] = port }
end.parse!
end
begin
logfile = File.join(File.dirname(__FILE__), 'log', File.basename(__FILE__, '.rb') + '.log')
$stats = Statosaurus.new(['job_user', 'job_sys', 'job_real', 'server'], Logger.new(logfile))
end
module ProxyServer
include LineBufferedConnection
def receive_line(line)
$stats.transaction do
$stats.measure('job') do
send_data(ProxyServer.forward(line + "\n"))
end
end
end
def self.forward(data)
balancer.forward(data)
end
private
def self.servers
@servers ||= Thread.exclusive do
(1..$options[:count]).inject([]) do |servers, i|
servers << Server.new($options[:host], $options[:port] + i)
end
end
end
def self.balancer
@balancer ||= Thread.exclusive do
$options[:balancer].new(servers)
end
end
end
EM.run do
EM.start_server $options[:host], $options[:port], ProxyServer
end