-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathserver.rb
111 lines (83 loc) · 2.53 KB
/
server.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
require 'childprocess'
require 'socket'
module BrowserMob
module Proxy
class Server
attr_reader :port
#
# Create a new server instance
#
# @param [String] path Path to the BrowserMob Proxy server executable
# @param [Hash] opts options to create the server with
# @option opts [Integer] port What port to start the server on
# @option opts [Boolean] log Show server output (server inherits stdout/stderr)
# @option opts [Integer] timeout Seconds to wait for server to launch before timing out.
#
def initialize(path, opts = {})
assert_executable path
@path = path
@port = Integer(opts[:port] || 8080)
@timeout = Integer(opts[:timeout] || 10)
@log = !!opts[:log]
@process = create_process
end
def start
@process.start
wait_for_startup
pid = Process.pid
at_exit { stop if Process.pid == pid }
self
end
def url
"http://localhost:#{port}"
end
def create_proxy(port = nil, args={})
Client.from url, port, args
end
def stop
@process.stop if @process.alive?
end
private
def create_process
process = ChildProcess.new(@path, "--port", @port.to_s)
process.leader = true
process.io.inherit! if @log
process
end
def wait_for_startup
end_time = Time.now + @timeout
sleep 0.1 until (listening? && initialized?) || Time.now > end_time || [email protected]?
if Time.now > end_time
raise TimeoutError, "timed out waiting for the server to start (rerun with :log => true to see process output)"
end
unless @process.alive?
raise ServerDiedError, "unable to launch the server (rerun with :log => true to see process output)"
end
end
def listening?
TCPSocket.new("127.0.0.1", port).close
true
rescue
false
end
def initialized?
RestClient.get("#{url}/proxy")
true
rescue RestClient::Exception
false
end
def assert_executable(path)
unless File.exist?(path)
raise Errno::ENOENT, path
end
unless File.executable?(path)
raise Errno::EACCES, "not executable: #{path}"
end
end
class TimeoutError < StandardError
end
class ServerDiedError < StandardError
end
end # Server
end # Proxy
end # BrowserMob