使用Monit监控Python程序

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

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
2个回答

7

使用exec会用 exec 替换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

1
我不太明白为什么要使用源代码,因为问题中的链接现在已经失效了。能否加上注释?另外,这两个文件叫什么名字,它们位于哪里?谢谢 :) - Aaron
我认为这将停止脚本。 - Braconnot_P

2
您也可以通过在脚本中添加一个小函数来完全绕过整个包装器的问题。例如,像这样写入 pidfile 的函数:
import os

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

我发现自己使用这种方法,因为它更加直接简单,并且在脚本中可以独立存在。

你如何处理开始/停止操作? - EnemyBagJones
请按照教程网站上的说明进行操作。PID文件仅仅是进程ID,以便程序/脚本可以启动/停止。您仍然需要根据此处的说明进行定义: https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-monit - Markov Chained

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接