使用monit来杀死正确的进程,知道它是PID

我正在尝试使用monit来查找运行时间过长的surefire进程并杀死它们。

机器正在并行运行,因此可以同时运行多个surefire进程,但是这些进程没有PID文件。

我的监视configuration如下所示:

check process surefire matching "surefire/surefirebooter" if uptime > 4 hours then alert if uptime > 4 hours then stop 

警报已发送,但停止不起作用。

我不能使用killall,因为这个过程是由java运行的,还有几个其他的java进程正在运行。

我所需要的就是检测该过程的正确PID,以便我可以杀死正确的PID。

MONIT_PROCESS_PID环境variables被传播到由exec命令执行的程序的上下文中。

if uptime > 4 hours then stop

应该被replace

if uptime > 4 hours then exec "/usr/bin/monit-kill-process.sh"

和/usr/bin/monit-kill-process.sh应该看起来像

 #!/bin/bash # script run from monit instance # this will find long-running surefire process and kill it kill -9 $MONIT_PROCESS_PID 

唯一的问题是monit对于这个工作来说不是正确的工具,因为它希望每次执行检查时都会find与检查模式相匹配的进程,否则会尝试使用检查定义的开始部分来启动进程不完全是我们想要做的)。

所以我find并修改了这个我通过cron运行的ps / grep / perl / xargs oneliner。 它能够通过命令行子串查找进程,select长时间运行的进程并对待它们。

 #!/bin/bash # script run from monit instance # this will find long-running surefire process and kill it readonly PROCESS_STRING="surefireboot" /bin/ps -e -o pid,time,command \ | /bin/grep $PROCESS_STRING \ | /usr/bin/perl -ne 'print "$1 " if /^\s*([0-9]+) ([-0-9]+:[0-9]+:[0-9]+)/ && $2 gt "04:00:00"' \ | /usr/bin/xargs kill 

Monit可能不是正确的工具。 模式匹配只使用第一个匹配。

这可以用monit procmatch <pattern>来testing

我build议使用唯一标识符来标记您的构build,并在模式匹配序列中使用它…或者完全用monit来pipe理守护进程。

你也不需要使用killall。 也许一些围绕pkill或pgrep的逻辑。

另请参阅: monit:检查没有pidfile的进程