dante 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/dante/runner.rb CHANGED
@@ -17,6 +17,10 @@ This is a utility for setting up a binary executable for a service.
17
17
  module Dante
18
18
  class Runner
19
19
  MAX_START_TRIES = 5
20
+ # Seconds a new daemon must stay up before it counts as started.
21
+ # ceiling: a daemon that dies later than this is still reported as started; a
22
+ # readiness signal from the startup block would close that.
23
+ START_GRACE = 1
20
24
 
21
25
  attr_accessor :options, :name, :description, :verify_options_hook
22
26
 
@@ -43,35 +47,29 @@ module Dante
43
47
  @with_options = block
44
48
  end
45
49
 
46
- # Executes the runner based on options
50
+ # Executes the runner based on options, after parsing the command-line options in
51
+ # options[:argv] (given to new or execute), or else in ARGV
47
52
  # @runner.execute
48
53
  # @runner.execute { ... }
49
54
  def execute(opts={}, &block)
55
+ options[:argv] = opts[:argv] if opts.key?(:argv) # needed before the rest of opts is merged
50
56
  parse_options
51
57
  self.options.merge!(opts)
52
58
 
53
59
  @verify_options_hook.call(self.options) if @verify_options_hook
54
60
 
55
- if options.include?(:kill)
61
+ # A key given as false is off; -k with no argument sets :kill to nil, which is on.
62
+ if options.fetch(:kill, false) != false
56
63
  self.stop
57
64
  else # create process
58
- self.stop if options.include?(:restart)
65
+ self.stop if options.fetch(:restart, false) != false
59
66
 
60
67
  # If a username, uid, groupname, or gid is passed,
61
68
  # drop privileges accordingly.
62
-
63
- if options[:group]
64
- gid = options[:group].is_a?(Integer) ? options[:group] : Etc.getgrnam(options[:group]).gid
65
- Process::GID.change_privilege(gid)
66
- end
67
-
68
- if options[:user]
69
- uid = options[:user].is_a?(Integer) ? options[:user] : Etc.getpwnam(options[:user]).uid
70
- Process::UID.change_privilege(uid)
71
- end
69
+ switch_user(options[:user], options[:group]) if options[:user] || options[:group]
72
70
 
73
71
  @startup_command = block if block_given?
74
- options[:daemonize] ? daemonize : start
72
+ start_service
75
73
  end
76
74
  end
77
75
 
@@ -82,19 +80,49 @@ module Dante
82
80
  options[:log_path] = "/var/log/#{@name}.log"
83
81
  end
84
82
 
85
- # Start process
83
+ # Start process: a session leader forks the daemon, then exits with success only
84
+ # if the daemon is still running START_GRACE seconds later. As the daemon's parent
85
+ # it sees the daemon exit at once, where the pid file cannot tell.
86
86
  pid = fork do
87
- exit if fork
88
- Process.setsid
89
- exit if fork
90
- store_pid(Process.pid)
91
- File.umask 0000
92
- redirect_output!
93
- start
87
+ started = false
88
+ begin
89
+ Process.setsid
90
+ daemon = fork do
91
+ # Handle INT and TERM before the pid file tells the caller we have started
92
+ trap_signals
93
+ store_pid(Process.pid)
94
+ redirect_output!
95
+ reopen_stream(IO.for_fd(0, autoclose: false), File::NULL, 'r') # fd 0, whatever STDIN or $stdin is
96
+ start
97
+ end
98
+ started = daemon_survives?(daemon)
99
+ remove_pid_file(daemon) unless started # the pid of a daemon that is gone
100
+ rescue Exception => e
101
+ warn "#{e.class}: #{e.message}"
102
+ ensure
103
+ # Like Process.daemon, leave without running the at_exit handlers inherited
104
+ # from the caller: they are the caller's, and one that exits or raises would
105
+ # replace this exit status.
106
+ exit!(started)
107
+ end
108
+ end
109
+ waited = false
110
+ started = begin
111
+ survived = Process.waitpid2(pid)[1].success?
112
+ waited = true
113
+ # Ensure process is running
114
+ survived && until_true(MAX_START_TRIES) { self.daemon_running? }
115
+ rescue Errno::ECHILD
116
+ # SIGCHLD is ignored, so the session leader's status is lost. It has exited, though,
117
+ # removing the pid file of a daemon that died, so one look at the pid file tells.
118
+ waited = true
119
+ self.daemon_running?
120
+ ensure
121
+ # Interrupted while the session leader runs: reap it in the background, or it
122
+ # lingers as a zombie.
123
+ Process.detach(pid) unless waited
94
124
  end
95
- Process.waitpid pid
96
- # Ensure process is running
97
- if until_true(MAX_START_TRIES) { self.daemon_running? }
125
+ if started
98
126
  log "Daemon has started successfully"
99
127
  true
100
128
  else # Failed to start
@@ -106,28 +134,35 @@ module Dante
106
134
  def start
107
135
  log "Starting #{@name} service..."
108
136
 
109
- if log_path = options[:log_path] && options[:daemonize].nil?
110
- redirect_output!
111
- end
112
-
113
- trap("INT") {
114
- interrupt
115
- exit
116
- }
137
+ # A daemon has redirected its output already
138
+ redirect_output! if options[:log_path] && !options[:daemonize]
117
139
 
118
- trap("TERM"){
119
- log "Trying to stop #{@name}..."
120
- exit
121
- }
140
+ trap_signals
122
141
 
123
142
  @startup_command.call(self.options) if @startup_command
124
143
  end
125
144
 
126
- # Stops a daemonized process
145
+ # Stops a daemonized process. The pid file is read once: the daemon it names then is
146
+ # the one signalled and waited for, whatever the pid file says by the time it stops.
127
147
  def stop(kill_arg=nil)
128
- if self.daemon_running?
129
- kill_pid(kill_arg || options[:kill])
130
- until_true(MAX_START_TRIES) { self.daemon_stopped? }
148
+ pid, pid_file_stat = read_pid_file(options[:pid_path])
149
+ running = pid && process_running?(pid)
150
+ if running && (untrusted = untrusted_pid_file(pid, pid_file_stat))
151
+ log "#{untrusted}; not stopping it"
152
+ false
153
+ elsif running
154
+ if wait_for_stop(pid, kill_pid(pid, kill_arg || options[:kill]))
155
+ remove_pid_file(pid) # Only once the daemon has stopped
156
+ log "Daemonized process killed after term."
157
+ else
158
+ log "Failed to kill daemonized process"
159
+ if options[:force]
160
+ if wait_for_stop(pid, kill_pid(pid, kill_arg || options[:kill], 'KILL'))
161
+ remove_pid_file(pid) # Only once the daemon has stopped
162
+ log "Daemonized process killed after kill."
163
+ end
164
+ end
165
+ end
131
166
  else # not running
132
167
  log "No #{@name} processes are running"
133
168
  false
@@ -136,7 +171,7 @@ module Dante
136
171
 
137
172
  def restart
138
173
  self.stop
139
- self.start
174
+ start_service
140
175
  end
141
176
 
142
177
  def interrupt
@@ -153,24 +188,28 @@ module Dante
153
188
  ! self.daemon_running?
154
189
  end
155
190
 
156
- # Returns running for the daemonized process
191
+ # Returns running for the daemonized process. A pid file that another user could have
192
+ # written (see untrusted_pid_file) names no daemon.
157
193
  # self.daemon_running?
158
194
  def daemon_running?
159
- return false unless File.exist?(options[:pid_path])
160
- Process.kill 0, File.read(options[:pid_path]).to_i
161
- true
162
- rescue Errno::ESRCH
163
- false
195
+ pid, pid_file_stat = read_pid_file(options[:pid_path])
196
+ return false unless pid
197
+ process_running?(pid) && !untrusted_pid_file(pid, pid_file_stat)
164
198
  end
165
199
 
166
200
  protected
167
201
 
202
+ # Starts the service: as a daemon with :daemonize, else in the foreground.
203
+ def start_service
204
+ options[:daemonize] ? daemonize : start
205
+ end
206
+
168
207
  def parse_options
169
208
  headline = [@name, @description].compact.join(" - ")
170
209
  OptionParser.new do |opts|
171
210
  opts.summary_width = 25
172
211
  opts.banner = [headline, "\n\n",
173
- "Usage: #{@name} [-p port] [-P file] [-d] [-k]\n",
212
+ "Usage: #{@name} [-p port] [-P file] [-d] [-k] [-f]\n",
174
213
  " #{@name} --help\n"].compact.join("")
175
214
  opts.separator ""
176
215
 
@@ -190,7 +229,7 @@ module Dante
190
229
  options[:log_path] = v
191
230
  end
192
231
 
193
- opts.on("-k", "--kill [PORT]", String, "Kill specified running daemons - leave blank to kill all.") do |v|
232
+ opts.on("-k", "--kill [PORT]", String, "Stop the daemon in the pid file (PORT is ignored)") do |v|
194
233
  options[:kill] = v
195
234
  end
196
235
 
@@ -202,33 +241,187 @@ module Dante
202
241
  options[:group] = group
203
242
  end
204
243
 
244
+ opts.on("-f", "--force", String, "Force kill if SIGTERM fails") do |v|
245
+ options[:force] = true
246
+ end
247
+
205
248
  opts.on_tail("-?", "--help", "Display this usage information.") do
206
249
  puts "#{opts}\n"
207
250
  exit
208
251
  end
209
-
252
+
210
253
  # Load options specified through 'with_options'
211
254
  instance_exec(opts, &@with_options) if @with_options
212
- end.parse!
255
+ end.parse!(options[:argv] ? options[:argv].dup : ARGV) # a copy of the caller's array
213
256
  options
214
257
  end
215
258
 
259
+ # Switches the process to user (a name or uid) and group (a name or gid). When running
260
+ # as root the group defaults to the user's primary group, and the supplementary groups
261
+ # (which changing the uid and gid leaves as they were) are set too: to the user's own
262
+ # groups, or to just the process's group for a group alone or a uid with no passwd
263
+ # entry. Otherwise only what was given changes. Everything is looked up before
264
+ # anything is changed.
265
+ def switch_user(user, group)
266
+ root = Process.euid == 0
267
+ passwd = if user.is_a?(Integer)
268
+ begin
269
+ Etc.getpwuid(user)
270
+ rescue ArgumentError # a uid with no passwd entry
271
+ nil
272
+ end
273
+ elsif user
274
+ Etc.getpwnam(user)
275
+ end
276
+ uid = passwd ? passwd.uid : user
277
+ gid = if group
278
+ group.is_a?(Integer) ? group : Etc.getgrnam(group).gid
279
+ elsif passwd && root
280
+ passwd.gid
281
+ end
282
+
283
+ if root
284
+ if passwd
285
+ Process.initgroups(passwd.name, gid)
286
+ else
287
+ Process.groups = [gid || Process.egid]
288
+ end
289
+ end
290
+ Process::GID.change_privilege(gid) if gid
291
+ Process::UID.change_privilege(uid) if uid
292
+ end
293
+
294
+ def trap_signals
295
+ trap("INT") {
296
+ interrupt
297
+ exit
298
+ }
299
+
300
+ trap("TERM"){
301
+ log "Trying to stop #{@name}..."
302
+ exit
303
+ }
304
+ end
305
+
306
+ # Writes pid to a new file in the pid file's directory and renames it into place, so
307
+ # that whatever was at the pid file's path (a symlink, or another file) is replaced
308
+ # rather than written into, and a reader sees either the old pid file or the whole new
309
+ # one. In a directory the daemon cannot write, it writes the pid file there already.
216
310
  def store_pid(pid)
217
- FileUtils.mkdir_p(File.dirname(options[:pid_path]))
218
- File.open(options[:pid_path], 'w'){|f| f.write("#{pid}\n")}
311
+ pid_path = options[:pid_path]
312
+ FileUtils.mkdir_p(File.dirname(pid_path))
313
+ tmp_path = "#{pid_path}.#{pid}.tmp"
314
+ FileUtils.rm_f(tmp_path) # one left by a crash (a symlink is removed, not followed)
315
+ begin
316
+ # EXCL: never written through a file or symlink put there since
317
+ File.open(tmp_path, File::WRONLY | File::CREAT | File::EXCL) { |f| f.write("#{pid}\n") }
318
+ rescue Errno::EACCES
319
+ # A pid file made for the daemon's user in a directory it cannot write, as an init
320
+ # script might. Without CREAT, a missing one fails, as it did before.
321
+ # ceiling: not atomic, so a reader can see it half-written; giving the daemon's user
322
+ # the directory restores the rename.
323
+ tmp_path = nil
324
+ File.open(pid_path, File::WRONLY | File::TRUNC | File::NOFOLLOW) { |f| f.write("#{pid}\n") }
325
+ return
326
+ end
327
+ File.rename(tmp_path, pid_path)
328
+ ensure
329
+ FileUtils.rm_f(tmp_path) if tmp_path # left only when writing or renaming failed
219
330
  end
220
331
 
221
- def kill_pid(k='*')
222
- Dir[options[:pid_path]].each do |f|
223
- begin
224
- pid = IO.read(f).chomp.to_i
225
- FileUtils.rm f
226
- Process.kill('TERM', pid)
227
- log "Stopped PID: #{pid} at #{f}"
228
- rescue => e
229
- log "Failed to stop! #{k}: #{e}"
230
- end
332
+ # Whether daemon, a child of this process, is still running START_GRACE seconds after
333
+ # it was forked. When the caller's SIGCHLD handling reaps children itself (SIGCHLD
334
+ # ignored, or a handler that waits for them), waitpid cannot see the daemon, and
335
+ # signal 0 at the end of the grace period tells instead.
336
+ def daemon_survives?(daemon)
337
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + START_GRACE
338
+ while Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
339
+ return false if Process.waitpid(daemon, Process::WNOHANG)
340
+ sleep 0.1
341
+ end
342
+ true
343
+ rescue Errno::ECHILD
344
+ sleep [deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max
345
+ begin
346
+ Process.kill(0, daemon)
347
+ true
348
+ rescue Errno::ESRCH
349
+ false
350
+ end
351
+ end
352
+
353
+ # Removes the pid file if it still holds pid (another start may have replaced it).
354
+ # ceiling: the read and the delete are two steps, so a daemon that writes its pid between them loses its
355
+ # pid file; a lock on the pid file (flock) would close that window
356
+ def remove_pid_file(pid)
357
+ File.delete(options[:pid_path]) if read_pid(options[:pid_path]) == pid
358
+ rescue Errno::ENOENT
359
+ end
360
+
361
+ # The pid in pid_file, or nil when there is none: no pid file, or one left empty by a
362
+ # crash between creating and writing it, names no process (and pid 0 or a negative pid
363
+ # would signal a whole process group), nor does a number too large for a pid_t.
364
+ def read_pid(pid_file)
365
+ read_pid_file(pid_file)&.first
366
+ end
367
+
368
+ # The pid in pid_file, as read_pid gives it, and the pid file's File::Stat, both from
369
+ # the one file opened; nil without a pid. A symlink is not followed, and names no pid
370
+ # (a start replaces it).
371
+ def read_pid_file(pid_file)
372
+ return unless File.exist?(pid_file)
373
+ File.open(pid_file, File::RDONLY | File::NOFOLLOW) do |file|
374
+ pid = file.read.to_i
375
+ [pid, file.stat] if pid > 0 && pid < 2**31
231
376
  end
377
+ rescue Errno::ENOENT, Errno::ELOOP # removed since the check, or a symlink
378
+ end
379
+
380
+ # Why the pid file, with File::Stat pid_file_stat, cannot be trusted to name pid, its
381
+ # daemon: it has other hard links (which keep the owner of the file they link to), or
382
+ # it is owned by neither root, nor a user that pid runs as (any of its uids), nor the
383
+ # user running this (whose own permissions are all a stop could use), so another user
384
+ # could have written it to have that process stopped. nil when it can be trusted, or
385
+ # when the owner of pid cannot be told (it has gone, say).
386
+ # ceiling: the owner of a process is read from /proc (Linux); elsewhere only the hard
387
+ # links are checked. `ps -o ruid=,uid= -p PID` would tell the owner on other Unixes.
388
+ def untrusted_pid_file(pid, pid_file_stat)
389
+ return "pid file #{options[:pid_path]} has other hard links" if pid_file_stat.nlink > 1
390
+ pid_file_uid = pid_file_stat.uid
391
+ return if pid_file_uid == 0 || pid_file_uid == Process.euid
392
+ uids = File.read("/proc/#{pid}/status")[/^Uid:(.*)$/, 1] or return # no Uid line
393
+ process_uids = uids.split.map { |uid| Integer(uid) } # real, effective, saved, filesystem
394
+ return if process_uids.include?(pid_file_uid)
395
+ "pid file #{options[:pid_path]} is owned by uid #{pid_file_uid} but process #{pid} belongs to uid #{process_uids.first}"
396
+ rescue SystemCallError # no /proc
397
+ end
398
+
399
+ # Whether pid is a running process, counting one that belongs to another user.
400
+ def process_running?(pid)
401
+ Process.kill 0, pid
402
+ true
403
+ rescue Errno::EPERM # the process exists but belongs to another user
404
+ true
405
+ rescue Errno::ESRCH
406
+ false
407
+ end
408
+
409
+ # Sends sig to pid, the daemon, and returns whether it reached it.
410
+ def kill_pid(pid, k, sig='TERM')
411
+ Process.kill(sig, pid)
412
+ log "Sent SIG#{sig} to PID: #{pid} at #{options[:pid_path]}"
413
+ true
414
+ rescue => e
415
+ log "Failed to stop! #{k}: #{e}"
416
+ false
417
+ end
418
+
419
+ # Waits for pid, the daemon, to stop once a signal reached it, checking every 0.1
420
+ # seconds (a Rational step, so the steps add up to exactly MAX_START_TRIES seconds).
421
+ # When no signal reached it (the daemon belongs to another user), it cannot stop, so
422
+ # this only checks once.
423
+ def wait_for_stop(pid, signalled)
424
+ signalled ? until_true(MAX_START_TRIES, Rational(1, 10)) { !process_running?(pid) } : !process_running?(pid)
232
425
  end
233
426
 
234
427
  # Redirect output based on log settings (reopens stdout/stderr to specified logfile)
@@ -237,25 +430,30 @@ module Dante
237
430
  if log_path = options[:log_path]
238
431
  # if the log directory doesn't exist, create it
239
432
  FileUtils.mkdir_p File.dirname(options[:log_path]), :mode => 0755
240
- # touch the log file to create it
241
- FileUtils.touch log_path
242
- # Set permissions on the log file
243
- File.chmod(0644, log_path)
244
- # Reopen $stdout (NOT +STDOUT+) to start writing to the log file
245
- $stdout.reopen(log_path, 'a')
433
+ # Reopen $stdout (NOT +STDOUT+) to append to the log file, created with mode 0644
434
+ # (less the umask) if absent. An existing log file keeps its mode; a symlink is
435
+ # followed.
436
+ reopen_stream($stdout, log_path, 'a', 0644)
246
437
  # Redirect $stderr to $stdout
247
438
  $stderr.reopen $stdout
248
439
  $stdout.sync = true
249
440
  else # redirect to /dev/null
250
441
  # We're not bothering to sync if we're dumping to /dev/null
251
442
  # because /dev/null doesn't care about buffered output
252
- $stdin.reopen '/dev/null'
253
- $stdout.reopen '/dev/null', 'a'
443
+ reopen_stream($stdin, '/dev/null', 'r')
444
+ reopen_stream($stdout, '/dev/null', 'a')
254
445
  $stderr.reopen $stdout
255
446
  end
256
447
  log_path = options[:log_path] ? options[:log_path] : '/dev/null'
257
448
  end
258
449
 
450
+ # Reopens stream onto path, opened with mode (and created with perm). Reopening onto
451
+ # an open File rather than a path works whatever mode the stream itself was opened
452
+ # with (a socket, for one, when run under Spring or Zeus).
453
+ def reopen_stream(stream, path, mode, perm=0666)
454
+ File.open(path, mode, perm) { |file| stream.reopen(file) }
455
+ end
456
+
259
457
  # Runs until the block condition is met or the timeout_seconds is exceeded
260
458
  # until_true(10) { ...return_condition... }
261
459
  def until_true(timeout_seconds, interval=1, &block)
data/lib/dante/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Dante
2
- VERSION = "0.2.0"
2
+ VERSION = "0.4.0"
3
3
  end
data/test/dante_test.rb CHANGED
@@ -2,7 +2,7 @@ require File.expand_path('../test_helper', __FILE__)
2
2
 
3
3
  describe "dante module" do
4
4
  before do
5
- @process = TestingProcess.new('a')
5
+ @process = TestingProcess.new('a', @tmpdir)
6
6
  end
7
7
 
8
8
  it "can run jobs using #run method" do
@@ -10,7 +10,7 @@ describe "dante module" do
10
10
  Dante.run('test-process') { @process.run_a! }
11
11
  end
12
12
  @output = File.read(@process.tmp_path)
13
- assert_match /Started/, @output
13
+ assert_match(/Started/, @output)
14
14
  end
15
15
 
16
- end
16
+ end