Module: Wakame::Daemonize

Defined in:
lib/isono/daemonize.rb

Instance Method Summary collapse

Instance Method Details

#change_privilege(user, group = user) ⇒ Object

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



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/isono/daemonize.rb', line 21

def change_privilege(user, group=user)
  Wakame.log.info("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
    if pid_file && File.exist?(pid_file) && uid == 0
      File.chown(target_uid, target_gid, pid_file)
    end

    # 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
  Wakame.log.error("Couldn't change user and group to #{user}:#{group}: #{e}")
end

#daemonize(log_path) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/isono/daemonize.rb', line 61

def daemonize(log_path)
  # Cleanup stale pidfile or prevent from multiple process running.
  if File.exist?(pid_file)
    if pid && Process.running?(pid)
      raise "#{pid_file} already exists, seems like it's already running (process ID: #{pid}). " +
        "Stop the process or delete #{pid_file}."
    else
      Wakame.log.info "Deleting the stale PID file: #{pid_file}"
      remove_pidfile
    end
  end

  ::Daemonize.daemonize(log_path, File.basename($0.to_s))

  setup_pidfile
  #Signal.trap('HUP') {}
end

#on_restart(&blk) ⇒ Object



79
80
81
# File 'lib/isono/daemonize.rb', line 79

def on_restart(&blk)
  @on_restart = blk
end

#pidObject



46
47
48
# File 'lib/isono/daemonize.rb', line 46

def pid
  File.exist?(pid_file) ? open(pid_file).read.to_i : nil
end

#pid_fileObject



42
43
44
# File 'lib/isono/daemonize.rb', line 42

def pid_file
  @options[:pid_file]
end

#remove_pidfileObject



89
90
91
92
93
# File 'lib/isono/daemonize.rb', line 89

def remove_pidfile
  File.delete(pid_file) if pid_file && File.exist?(pid_file)
rescue => e
  Wakame.log.error(e)
end

#restartObject



83
84
85
86
87
# File 'lib/isono/daemonize.rb', line 83

def restart
  raise '' if @on_restart.nil?

  @on_restart.call
end

#setup_pidfileObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/isono/daemonize.rb', line 50

def setup_pidfile
  #raise 'Please implement pid_file() method' unless respond_to? :pid_file

  unless File.exist?(File.dirname(pid_file))
    FileUtils.mkpath(File.dirname(pid_file))
  end

  open(pid_file, "w") { |f| f.write(Process.pid) }
  File.chmod(0644, pid_file)
end