Module: Thin::Daemonizable

Included in:
Server
Defined in:
lib/thin/daemonizing.rb

Overview

Module included in classes that can be turned into a daemon. Handle stuff like:

  • storing the PID in a file

  • redirecting output to the log file

  • changing processs privileges

  • killing the process gracefully

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#log_fileObject

Returns the value of attribute log_file.



39
40
41
# File 'lib/thin/daemonizing.rb', line 39

def log_file
  @log_file
end

#pid_fileObject

Returns the value of attribute pid_file.



39
40
41
# File 'lib/thin/daemonizing.rb', line 39

def pid_file
  @pid_file
end

Class Method Details

.included(base) ⇒ Object



41
42
43
# File 'lib/thin/daemonizing.rb', line 41

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#change_privilege(user, group = user) ⇒ Object

Change privileges of the process to the specified user and group.



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/thin/daemonizing.rb', line 67

def change_privilege(user, group=user)
  log ">> Changing process privilege to #{user}:#{group}"
  
  uid, gid = Process.euid, Process.egid
  target_uid = Etc.getpwnam(user).uid
  target_gid = Etc.getgrnam(group).gid

  if uid != target_uid || gid != target_gid
    # Change process ownership
    Process.initgroups(user, target_gid)
    Process::GID.change_privilege(target_gid)
    Process::UID.change_privilege(target_uid)
  end
rescue Errno::EPERM => e
  log "Couldn't change user and group to #{user}:#{group}: #{e}"
end

#daemonizeObject

Turns the current script into a daemon process that detaches from the console.

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/thin/daemonizing.rb', line 46

def daemonize
  raise ArgumentError, 'You must specify a pid_file to deamonize' unless @pid_file
  
  pwd = Dir.pwd # Current directory is changed during daemonization, so store it
  super         # Calls Kernel#daemonize
  Dir.chdir pwd
  
  trap('HUP', 'IGNORE') # Don't die upon logout

  # Redirect output to the logfile
  [STDOUT, STDERR].each { |f| f.reopen @log_file, 'a' } if @log_file
  
  write_pid_file
  at_exit do
    log ">> Exiting!"
    remove_pid_file
  end
end