【问题标题】:Use Monit monitor a python program使用Monit监控一个python程序
【发布时间】:2014-05-04 08:55:32
【问题描述】:

我正在使用 Monit 来监控系统。我有一个我希望监控的 python 文件,我知道我需要创建一个包装脚本,因为 python 不会生成 pid 文件。我按照site 上的说明进行操作,但是我无法启动脚本。我以前从未创建过包装脚本,所以我认为我的脚本中有错误。 monit 的日志显示“启动失败”

监控规则

check process scraper with pidfile /var/run/scraper.pid
   start = "/bin/scraper start"
   stop = "/bin/scraper stop"

包装脚本

#!/bin/bash

PIDFILE=/var/run/scraper.pid

case $1 in
   start)
      echo $$ > ${PIDFILE};
      source /home
      exec python /home/scraper.py 2>/dev/null
   ;;
   stop)
      kill `cat ${PIDFILE}` ;;
   *)
      echo "usage: scraper {start|stop}" ;;
esac
exit 0

【问题讨论】:

    标签: monit


    【解决方案1】:

    使用 exec 将用 exec'd 程序替换 shell,这不是你想要的,你希望你的包装脚本在返回之前启动程序并分离它,将它的 PID 写入一个文件,这样它可以稍后停止。

    这是一个固定版本:

    #!/bin/bash
    
    PIDFILE=/var/run/scraper.pid
    
    case $1 in
       start)
           source /home
           # Launch your program as a detached process
           python /home/scraper.py 2>/dev/null &
           # Get its PID and store it
           echo $! > ${PIDFILE} 
       ;;
       stop)
          kill `cat ${PIDFILE}`
          # Now that it's killed, don't forget to remove the PID file
          rm ${PIDFILE}
       ;;
       *)
          echo "usage: scraper {start|stop}" ;;
    esac
    exit 0
    

    【讨论】:

    • 我并不真正理解为什么使用源,因为问题中的链接现在转到 404。可以对此发表评论吗?另外,这两个文件叫什么,它们在哪里?谢谢:)
    【解决方案2】:

    您还可以通过添加一个在脚本中写入 pidfile 的小函数来完全绕过整个包装器。比如:

    import os
    
    def writePidFile():
        pid = str(os.getpid())
        currentFile = open(‘/var/run/myPIDFile.pid’, ‘w’)
        currentFile.write(pid)
        currentFile.close()
    

    我发现自己使用了这种方法,因为它是一种更直接的方法,并且它是自包含在脚本中的。

    【讨论】:

    • 你如何处理启动/停止动作?
    • 按照教程网站上的说明进行操作。 PID 文件只不过是进程 ID,以便可以启动/停止程序/脚本。您仍然必须按照此处的说明定义它们:digitalocean.com/community/tutorials/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多