Module: Kajiki::Handler

Included in:
Runner
Defined in:
lib/kajiki/handler.rb

Instance Method Summary collapse

Instance Method Details

#change_privilegesObject

Change process UID and GID.



53
54
55
56
# File 'lib/kajiki/handler.rb', line 53

def change_privileges
  Process.egid = @opts[:group] if @opts[:group_given]
  Process.euid = @opts[:user] if @opts[:user_given]
end

#check_existing_pidBoolean

Check if process exists then fail, otherwise clean up.

Returns:

  • (Boolean)

    ‘false` if no PID file exists, `true` if it cleaned up.



7
8
9
10
11
12
# File 'lib/kajiki/handler.rb', line 7

def check_existing_pid
  return false unless pid_file_exists?
  pid = read_pid
  fail 'Existing process found.' if pid > 0 && pid_exists?(pid)
  delete_pid
end

#delete_pidBoolean

Delete PID file if it exists.

Returns:

  • (Boolean)

    ‘false` if nothing done, `true` if file was deleted.



44
45
46
47
48
49
50
# File 'lib/kajiki/handler.rb', line 44

def delete_pid
  if @opts[:pid_given] && File.exists?(@opts[:pid])
    File.delete(@opts[:pid]) 
    return true
  end
  return false
end

#pid_exists?(pid) ⇒ Boolean

Check if process exists.

Parameters:

  • pid (Fixnum)

Returns:

  • (Boolean)


17
18
19
20
21
22
# File 'lib/kajiki/handler.rb', line 17

def pid_exists?(pid)
  Process.kill(0, pid)
  return true
rescue Errno::ESRCH
  return false
end

#pid_file_exists?Boolean

Check if PID file exists.

Returns:

  • (Boolean)


26
27
28
29
# File 'lib/kajiki/handler.rb', line 26

def pid_file_exists?
  return false unless @opts[:pid_given]
  File.exists?(@opts[:pid])
end

#read_pidFixnum?

Read PID from file.

Returns:

  • (Fixnum, nil)

    PID; if ‘0`, it should be ignored.



38
39
40
# File 'lib/kajiki/handler.rb', line 38

def read_pid
  IO.read(@opts[:pid]).to_i if @opts[:pid_given]
end

#redirect_outputsObject

Redirect outputs.



59
60
61
62
63
64
65
66
67
68
# File 'lib/kajiki/handler.rb', line 59

def redirect_outputs
  if @opts[:error_given]
    $stderr.reopen(@opts[:error], 'a') 
    $stderr.sync = true
  end
  if @opts[:log_given]
    $stdout.reopen(@opts[:log], 'a') 
    $stdout.sync = true
  end
end

#trap_default_signalsObject

Trap common signals as default.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/kajiki/handler.rb', line 71

def trap_default_signals
  Signal.trap('INT') do
    puts 'Interrupted. Terminating process...'
    exit
  end
  Signal.trap('HUP') do
    puts 'SIGHUP - Terminating process...'
    exit
  end
  Signal.trap('TERM') do
    puts 'SIGTERM - Terminating process...'
    exit
  end
end

#write_pidObject

Write PID to file.



32
33
34
# File 'lib/kajiki/handler.rb', line 32

def write_pid
  IO.write(@opts[:pid], Process.pid) if @opts[:pid_given]
end