ruby-on-rails – 如何使用monit监控nginx乘客

我有nginx乘客部署的几个rails应用程序.我希望使用monit监视这些应用程序.如何使用monit监控这些应用程序?我也应该监控nginx吗?解决方法:这就是我解决这个问题的方法.首先,我添加到application.rb:# Monit suppor...

我有nginx乘客部署的几个rails应用程序.我希望使用monit监视这些应用程序.如何使用monit监控这些应用程序?我也应该监控nginx吗?

解决方法:

这就是我解决这个问题的方法.首先,我添加到application.rb:


# Monit support
if defined?(PhusionPassenger)
  require 'pidfile_manager'
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    if forked
      # We're in smart spawning mode.
      PidfileManager.write_pid_file
    else
      # We're in conservative spawning mode. We don't need to do anything.
    end
  end

  PhusionPassenger.on_event(:stopping_worker_process) do
    PidfileManager.remove_pid_file
  end
end

然后我实现了PidfileManager:


module PidfileManager
  extend self

  BASENAME = '/var/tmp/rack.*.pid'

  def write_pid_file
    pid = Process.pid
    count = 1
    pidfile = nil
    go_over_pid_files do |file, saved_pid|
      file_id = file[/(\d+)/,1].to_i
      # Increase counter only if we met the same file id
      count += 1 if file_id == count
      # We're already there
      return if saved_pid == pid
      # Check if the process is alive
      res = begin
        Process.kill(0, saved_pid)
      rescue Errno::ESRCH
        nil
      end
      # It's dead, reuse
      unless res
        pidfile = file
        break
      end
    end
    pidfile ||= BASENAME.sub('*', count.to_s)
    File.open(pidfile, 'w') {|f| f.write(pid.to_s)}
  end

  def remove_pid_file
    pid = Process.pid
    go_over_pid_files do |file, saved_pid|
      if pid == saved_pid
        File.unlink(file)
        break
      end
    end
  end

  private
  def go_over_pid_files
    Dir[BASENAME].each do |file|
      saved_pid = File.read(file).to_i
      yield file, saved_pid
    end
  end

end

然后你只需告诉monit使用/var/tmp/rack.X.pid监视每个实例作为pidfile.

本文标题为:ruby-on-rails – 如何使用monit监控nginx乘客

基础教程推荐