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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
|
# File 'lib/server/starter.rb', line 17
def start_server(opts)
opts = opts.map {|k, v| [k.to_sym, v] }.to_h
opts[:interval] ||= 1
opts[:signal_on_hup] ||= 'TERM'
opts[:signal_on_term] ||= 'TERM'
opts[:backlog] ||= Socket::SOMAXCONN
[:signal_on_hup, :signal_on_term].each do |key|
opts[key].tr!("a-z", "A-Z")
opts[key].sub!(/^SIG/i, "")
end
ports = Array(opts[:port])
paths = Array(opts[:path])
unless ports.empty? || paths.empty?
croak "either of ``port'' or ``path'' option is mandatory"
end
unless opts[:exec] && opts[:exec].is_a?(Array)
croak "mandatory option ``exec'' is missing or not an array"
end
ENV['ENVDIR'] = opts[:envdir] if opts[:envdir]
ENV['ENABLE_AUTO_RESTART'] = opts[:enable_auto_restart] ? '1' : nil
ENV['KILL_OLD_DELAY'] = opts[:kill_old_delay].to_s if opts[:kill_old_delay]
ENV['AUTO_RESTART_INTERVAL'] = opts[:auto_restart_interval].to_s if opts[:auto_restart_interval]
if opts[:pid_file]
File.open(opts[:pid_file], "w") do |fh|
fh.puts $$
end rescue die "failed to open file:#{opts[:pid_file]}"
at_exit { File.unlink opts[:pid_file] rescue nil }
end
if opts[:log_file]
File.open(opts[:log_file], "a") do |fh|
$stdout.flush
$stderr.flush
$stdout.reopen(fh) rescue die "failed to reopen STDOUT to file"
$stderr.reopen(fh) rescue die "failed to reopen STDERR to file"
end
end
if opts[:status_file]
at_exit { File.unlink opts[:status_file] rescue nil }
end
$stderr.puts "start_server (pid:#{$$}) starting now..."
socks = []
sockenvs = []
ports.each do |port|
sock = nil
begin
if port =~ /^\s*(\d+)\s*$/
sock = TCPServer.new("0.0.0.0", port)
sock.setsockopt(:SOCKET, :REUSEADDR, true)
sock.listen(opts[:backlog])
elsif port =~ /^\s*(.*)\s*:\s*(\d+)\s*$/
_bind, _port = $1, $2
sock = TCPServer.new(_bind, _port)
sock.setsockopt(:SOCKET, :REUSEADDR, true)
sock.listen(opts[:backlog])
else
croak "invalid ``port'' value:#{port}"
end
rescue
die "failed to listen to #{port}"
end
sock.fcntl(Fcntl::F_SETFD, 0) rescue die "fcntl(F_SETFD, 0) failed"
sockenvs.push "#{port}=#{sock.fileno}"
socks.push sock
end
at_exit {
paths.each do |path|
File.symlink?(path) and File.unlink(path) rescue nil
end
}
paths.each do |path|
if File.symlink?(path)
warn "removing existing socket file:#{path}"
File.unlink(path) rescue die "failed to remove existing socket file:#{path}"
end
File.unlink(path) rescue nil
saved_umask = File.umask(0)
begin
sock = UNIXServer.new(path)
sock.listen(opts[:backlog])
rescue
die "failed to listen to file #{path}"
end
sock.fcntl(Fcntl::F_SETFD, 0) rescue die "fcntl(F_SETFD, 0) failed"
sockenvs.push "#{path}=#{sock.fileno}"
socks.push sock
end
ENV['SERVER_STARTER_PORT'] = sockenvs.join(";")
ENV['SERVER_STARTER_GENERATION'] = "0"
%w(INT TERM HUP ALRM).each do |signal|
Signal.trap(signal) {
@signals_received.push(signal)
@signal_wait_thread.kill if @signal_wait_thread
}
end
Signal.trap('PIPE') { 'IGNORE' }
update_status =
if opts[:status_file]
Proc.new {
tmpfn = "#{opts[:status_file]}.#{$$}"
File.open(tmpfn, "w") do |tmpfh|
gen_pids = @current_worker ?
{ENV['SERVER_STARTER_GENERATION'] => @current_worker} :
{}
@old_workers.each {|pid, gen| gen_pids[gen] = pid }
gen_pids.keys.map(&:to_i).sort.each {|gen| tmpfh.puts "#{gen}:#{gen_pids[gen.to_s]}" }
end rescue die "failed to create temporary file:#{tmpfn}"
begin
File.rename(tmpfn, opts[:status_file])
rescue
die "failed to rename #{tmpfn} to #{opts[:status_file]}"
end
}
else
Proc.new {}
end
start_worker = Proc.new {
pid = nil
while true
ENV['SERVER_STARTER_GENERATION'] = (ENV['SERVER_STARTER_GENERATION'].to_i + 1).to_s
begin
pid = fork
rescue
die "fork(2) failed"
end
if pid.nil? args = Array(opts[:exec]).dup
if opts[:dir]
Dir.chdir opts[:dir] rescue die "failed to chdir"
end
begin
bundler_with_clean_env do
args << {:close_others => false}
exec(*args)
end
rescue
$stderr.puts "failed to exec #{args[0]}:#{$!.class} #{$!.message}"
exit(255)
end
end
$stderr.puts "starting new worker #{pid}"
sleep opts[:interval]
break if (@signals_received - [:HUP]).size > 0
break if Process.waitpid(pid, Process::WNOHANG).nil?
$stderr.puts "new worker #{pid} seems to have failed to start, exit status:#{$?.exitstatus}"
end
@current_worker = pid
@last_restart_time = Time.now
update_status.call
}
wait = Proc.new {
flags = @signals_received.empty? ? 0 : Process::WNOHANG
r = nil
@signal_wait_thread = Thread.start do
if flags != 0 && ENV['ENABLE_AUTO_RESTART']
begin
Timeout.timeout(1) do
pid = Process.waitpid(-1, flags)
r = [pid, $?.exitstatus] if pid
end
rescue Timeout::Error
Thread.exit
end
else
pid = Process.waitpid(-1, flags)
r = [pid, $?.exitstatus] if pid
end
end
@signal_wait_thread.join
@signal_wait_thread = nil
r
}
cleanup = Proc.new {|sig|
term_signal = sig == 'TERM' ? opts[:signal_on_term] : 'TERM'
@old_workers[@current_worker] = ENV['SERVER_STARTER_GENERATION']
@current_worker = nil
$stderr.print "received #{sig}, sending #{term_signal} to all workers:",
@old_workers.keys.sort.join(','), "\n"
@old_workers.keys.sort.each {|pid| Process.kill(term_signal, pid) }
while true
died_worker = Process.waitpid(-1, Process::WNOHANG)
if died_worker
$stderr.puts "worker #{died_worker} died, status:#{$?.exitstatus}"
@old_workers.delete(died_worker)
update_status.call
break if @old_workers.empty?
end
end
$stderr.puts "exiting"
}
start_worker.call
while true
r = wait.call
loaded_env = _reload_env
ENV['AUTO_RESTART_INTERVAL'] ||= "360" if ENV['ENABLE_AUTO_RESTART']
with_local_env(loaded_env) do
if r
died_worker, status = r
if died_worker == @current_worker
$stderr.puts "worker #{died_worker} died unexpectedly with status:#{status}, restarting"
start_worker.call
else
$stderr.puts "old worker #{died_worker} died, status:#{status}"
@old_workers.delete(died_worker)
update_status.call
end
end
restart = nil
while !@signals_received.empty?
sig = @signals_received.shift
if sig == 'HUP'
$stderr.puts "received HUP, spawning a new worker"
restart = true
break
elsif sig == 'ALRM'
else
return cleanup.call(sig)
end
end
if !restart && ENV['ENABLE_AUTO_RESTART']
auto_restart_interval = ENV['AUTO_RESTART_INTERVAL'].to_i
elapsed_since_restart = Time.now - @last_restart_time
if elapsed_since_restart >= auto_restart_interval && @old_workers.empty?
$stderr.puts "autorestart triggered (interval=#{auto_restart_interval})"
restart = true
elsif elapsed_since_restart >= auto_restart_interval * 2
$stderr.puts "autorestart triggered (forced, interval=#{auto_restart_interval})"
restart = true
end
end
if restart
@old_workers[@current_worker] = ENV['SERVER_STARTER_GENERATION']
start_worker.call
$stderr.print "new worker is now running, sending #{opts[:signal_on_hup]} to old workers:"
if !@old_workers.empty?
$stderr.puts @old_workers.keys.sort.join(',')
else
$stderr.puts "none"
end
kill_old_delay = ENV['KILL_OLD_DELAY'] ? ENV['KILL_OLD_DELAY'].to_i : ENV['ENABLE_AUTO_RESTART'] ? 5 : 0
if kill_old_delay != 0
$stderr.puts "sleeping #{kill_old_delay} secs before killing old workers"
sleep kill_old_delay
end
$stderr.puts "killing old workers"
@old_workers.keys.sort.each {|pid| Process.kill(opts[:signal_on_hup], pid) }
end
end
end
die "unreachable"
end
|