Class: God::Process

Inherits:
Object
  • Object
show all
Defined in:
lib/god/process.rb

Constant Summary collapse

WRITES_PID =
[:start, :restart].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeProcess

Returns a new instance of Process.



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/god/process.rb', line 11

def initialize
  self.log = '/dev/null'

  @pid_file = nil
  @tracking_pid = true
  @user_log = false
  @pid = nil
  @unix_socket = nil
  @log_cmd = nil
  @stop_timeout = God::STOP_TIMEOUT_DEFAULT
  @stop_signal = God::STOP_SIGNAL_DEFAULT
end

Instance Attribute Details

#chrootObject

Returns the value of attribute chroot.



7
8
9
# File 'lib/god/process.rb', line 7

def chroot
  @chroot
end

#dirObject

Returns the value of attribute dir.



7
8
9
# File 'lib/god/process.rb', line 7

def dir
  @dir
end

#envObject

Returns the value of attribute env.



7
8
9
# File 'lib/god/process.rb', line 7

def env
  @env
end

#err_logObject

Returns the value of attribute err_log.



7
8
9
# File 'lib/god/process.rb', line 7

def err_log
  @err_log
end

#err_log_cmdObject

Returns the value of attribute err_log_cmd.



7
8
9
# File 'lib/god/process.rb', line 7

def err_log_cmd
  @err_log_cmd
end

#gidObject

Returns the value of attribute gid.



7
8
9
# File 'lib/god/process.rb', line 7

def gid
  @gid
end

#logObject

Returns the value of attribute log.



7
8
9
# File 'lib/god/process.rb', line 7

def log
  @log
end

#log_cmdObject

Returns the value of attribute log_cmd.



7
8
9
# File 'lib/god/process.rb', line 7

def log_cmd
  @log_cmd
end

#nameObject

Returns the value of attribute name.



7
8
9
# File 'lib/god/process.rb', line 7

def name
  @name
end

#restartObject

Returns the value of attribute restart.



7
8
9
# File 'lib/god/process.rb', line 7

def restart
  @restart
end

#startObject

Returns the value of attribute start.



7
8
9
# File 'lib/god/process.rb', line 7

def start
  @start
end

#stopObject

Returns the value of attribute stop.



7
8
9
# File 'lib/god/process.rb', line 7

def stop
  @stop
end

#stop_signalObject

Returns the value of attribute stop_signal.



7
8
9
# File 'lib/god/process.rb', line 7

def stop_signal
  @stop_signal
end

#stop_timeoutObject

Returns the value of attribute stop_timeout.



7
8
9
# File 'lib/god/process.rb', line 7

def stop_timeout
  @stop_timeout
end

#uidObject

Returns the value of attribute uid.



7
8
9
# File 'lib/god/process.rb', line 7

def uid
  @uid
end

#umaskObject

Returns the value of attribute umask.



7
8
9
# File 'lib/god/process.rb', line 7

def umask
  @umask
end

#unix_socketObject

Returns the value of attribute unix_socket.



7
8
9
# File 'lib/god/process.rb', line 7

def unix_socket
  @unix_socket
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
# File 'lib/god/process.rb', line 24

def alive?
  if pid
    System::Process.new(pid).exists?
  else
    false
  end
end

#call_action(action) ⇒ Object



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
# File 'lib/god/process.rb', line 210

def call_action(action)
  command = send(action)

  if action == :stop && command.nil?
    pid = self.pid
    command = lambda do
      applog(self, :info, "#{name} stop: default lambda killer")

      ::Process.kill(@stop_signal, pid) rescue nil
      applog(self, :info, "#{name} sent SIG#{@stop_signal}")

      # Poll to see if it's dead
      pid_not_found = false
      @stop_timeout.times do
        if pid
          begin
            ::Process.kill(0, pid)
          rescue Errno::ESRCH
            # It died. Good.
            applog(self, :info, "#{name} process stopped")
            return
          end
        else
          applog(self, :warn, "#{name} pid not found in #{pid_file}") unless pid_not_found
          pid_not_found = true
        end

        sleep 1
      end

      ::Process.kill('KILL', pid) rescue nil
      applog(self, :warn, "#{name} still alive after #{@stop_timeout}s; sent SIGKILL")
    end
  end

  case command
  when String
    if [:start, :restart].include?(action) && @tracking_pid
      # double fork god-daemonized processes
      # we don't want to wait for them to finish
      r, w = IO.pipe
      begin
        opid = fork do
          $stdout.reopen(w)
          r.close
          pid = self.spawn(command)
          puts pid # send pid back to forker
          exit!(0)
        end

        ::Process.waitpid(opid, 0)
        w.close
        pid = r.gets.chomp
      ensure
        # make sure the file descriptors get closed no matter what
        r.close rescue nil
        w.close rescue nil
      end
    else
      # single fork self-daemonizing processes
      # we want to wait for them to finish
      pid = self.spawn(command)
      status = ::Process.waitpid2(pid, 0)
      exit_code = status[1] >> 8

      applog(self, :warn, "#{name} #{action} command exited with non-zero code = #{exit_code}") if exit_code != 0

      ensure_stop if action == :stop
    end

    if @tracking_pid || (@pid_file.nil? && WRITES_PID.include?(action))
      File.write(default_pid_file, pid)

      @tracking_pid = true
      @pid_file = default_pid_file
    end
  when Proc
    # lambda command
    command.call
  else
    raise NotImplementedError
  end
end

#default_pid_fileObject



206
207
208
# File 'lib/god/process.rb', line 206

def default_pid_file
  File.join(God.pid_file_directory, "#{name}.pid")
end

#ensure_stopObject

Ensure that a stop command actually stops the process. Force kill if necessary.

Returns nothing



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/god/process.rb', line 345

def ensure_stop
  applog(self, :warn, "#{name} ensuring stop...")

  unless pid
    applog(self, :warn, "#{name} stop called but pid is uknown")
    return
  end

  # Poll to see if it's dead
  @stop_timeout.times do
    begin
      ::Process.kill(0, pid)
    rescue Errno::ESRCH
      # It died. Good.
      return
    end

    sleep 1
  end

  # last resort
  ::Process.kill('KILL', pid) rescue nil
  applog(self, :warn, "#{name} still alive after #{@stop_timeout}s; sent SIGKILL")
end

#file_writable?(file) ⇒ Boolean

Returns:

  • (Boolean)


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
# File 'lib/god/process.rb', line 32

def file_writable?(file)
  pid = fork do
    begin
      if uid
        user_method = uid.is_a?(Integer) ? :getpwuid : :getpwnam
        uid_num = Etc.send(user_method, uid).uid
        gid_num = Etc.send(user_method, uid).gid
      end
      if gid
        group_method = gid.is_a?(Integer) ? :getgrgid : :getgrnam
        gid_num = Etc.send(group_method, gid).gid
      end

      ::Dir.chroot(chroot) if chroot
      ::Process.groups = [gid_num] if gid_num
      ::Process.initgroups(uid, gid_num) if uid && gid_num
      ::Process::Sys.setgid(gid_num) if gid_num
      ::Process::Sys.setuid(uid_num) if uid
    rescue ArgumentError, Errno::EPERM, Errno::ENOENT
      exit(1)
    end

    File.writable?(file_in_chroot(file)) ? exit!(0) : exit!(1)
  end

  _wpid, status = ::Process.waitpid2(pid)
  status.exitstatus == 0
end

#pidObject

Fetch the PID from pid_file. If the pid_file does not exist, then use the PID from the last time it was read. If it has never been read, then return nil.

Returns Integer(pid) or nil



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/god/process.rb', line 173

def pid
  contents = File.read(pid_file).strip rescue ''
  real_pid = /^\d+$/.match?(contents) ? contents.to_i : nil

  if real_pid
    @pid = real_pid
    real_pid
  else
    @pid
  end
end

#pid_fileObject



164
165
166
# File 'lib/god/process.rb', line 164

def pid_file
  @pid_file ||= default_pid_file
end

#pid_file=(value) ⇒ Object

DON’T USE THIS INTERNALLY. Use the instance variable. – Kev No really, trust me. Use the instance variable.



153
154
155
156
157
158
159
160
161
162
# File 'lib/god/process.rb', line 153

def pid_file=(value)
  # if value is nil, do the right thing
  @tracking_pid = if value
                    false
                  else
                    true
                  end

  @pid_file = value
end

#restart!Object



202
203
204
# File 'lib/god/process.rb', line 202

def restart!
  call_action(:restart)
end

#signal(sig) ⇒ Object

Send the given signal to this process.

Returns nothing



188
189
190
191
192
# File 'lib/god/process.rb', line 188

def signal(sig)
  sig = sig.to_i if sig.to_i != 0
  applog(self, :info, "#{name} sending signal '#{sig}' to pid #{pid}")
  ::Process.kill(sig, pid) rescue nil
end

#spawn(command) ⇒ Object

Fork/exec the given command, returns immediately

+command+ is the String containing the shell command

Returns nothing



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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/god/process.rb', line 298

def spawn(command)
  fork do
    File.umask umask if umask
    uid_num = Etc.getpwnam(uid).uid if uid
    gid_num = Etc.getgrnam(gid).gid if gid
    gid_num = Etc.getpwnam(uid).gid if gid.nil? && uid

    ::Dir.chroot(chroot) if chroot
    ::Process.setsid
    ::Process.groups = [gid_num] if gid_num
    ::Process.initgroups(uid, gid_num) if uid && gid_num
    ::Process::Sys.setgid(gid_num) if gid_num
    ::Process::Sys.setuid(uid_num) if uid
    self.dir ||= '/'
    Dir.chdir self.dir
    $0 = command
    $stdin.reopen '/dev/null'
    if log_cmd
      $stdout.reopen IO.popen(log_cmd, 'a')
    else
      $stdout.reopen file_in_chroot(log), 'a'
    end
    if err_log_cmd
      $stderr.reopen IO.popen(err_log_cmd, 'a')
    elsif err_log && (log_cmd || err_log != log)
      $stderr.reopen file_in_chroot(err_log), 'a'
    else
      $stderr.reopen $stdout
    end

    # close any other file descriptors
    3.upto(256) { |fd| IO.new(fd).close rescue nil }

    if env.is_a?(Hash)
      env.each do |(key, value)|
        ENV[key] = value.to_s
      end
    end

    exec command unless command.empty?
  end
end

#start!Object



194
195
196
# File 'lib/god/process.rb', line 194

def start!
  call_action(:start)
end

#stop!Object



198
199
200
# File 'lib/god/process.rb', line 198

def stop!
  call_action(:stop)
end

#valid?Boolean

Returns:

  • (Boolean)


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
# File 'lib/god/process.rb', line 61

def valid?
  # determine if we're tracking pid or not
  pid_file

  valid = true

  # a start command must be specified
  if start.nil?
    valid = false
    applog(self, :error, 'No start command was specified')
  end

  # uid must exist if specified
  if uid
    begin
      Etc.getpwnam(uid)
    rescue ArgumentError
      valid = false
      applog(self, :error, "UID for '#{uid}' does not exist")
    end
  end

  # gid must exist if specified
  if gid
    begin
      Etc.getgrnam(gid)
    rescue ArgumentError
      valid = false
      applog(self, :error, "GID for '#{gid}' does not exist")
    end
  end

  # dir must exist and be a directory if specified
  if dir
    if !File.exist?(dir)
      valid = false
      applog(self, :error, "Specified directory '#{dir}' does not exist")
    elsif !File.directory?(dir)
      valid = false
      applog(self, :error, "Specified directory '#{dir}' is not a directory")
    end
  end

  # pid dir must exist if specified
  if !@tracking_pid && !File.exist?(File.dirname(pid_file))
    valid = false
    applog(self, :error, "PID file directory '#{File.dirname(pid_file)}' does not exist")
  end

  # pid dir must be writable if specified
  if !@tracking_pid && File.exist?(File.dirname(pid_file)) && !file_writable?(File.dirname(pid_file))
    valid = false
    applog(self, :error, "PID file directory '#{File.dirname(pid_file)}' is not writable by #{uid || Etc.getlogin}")
  end

  # log dir must exist
  unless File.exist?(File.dirname(log))
    valid = false
    applog(self, :error, "Log directory '#{File.dirname(log)}' does not exist")
  end

  # log file or dir must be writable
  if File.exist?(log)
    unless file_writable?(log)
      valid = false
      applog(self, :error, "Log file '#{log}' exists but is not writable by #{uid || Etc.getlogin}")
    end
  else
    unless file_writable?(File.dirname(log))
      valid = false
      applog(self, :error, "Log directory '#{File.dirname(log)}' is not writable by #{uid || Etc.getlogin}")
    end
  end

  # chroot directory must exist and have /dev/null in it
  if chroot
    unless File.directory?(chroot)
      valid = false
      applog(self, :error, "CHROOT directory '#{chroot}' does not exist")
    end

    unless File.exist?(File.join(chroot, '/dev/null'))
      valid = false
      applog(self, :error, "CHROOT directory '#{chroot}' does not contain '/dev/null'")
    end
  end

  valid
end