从shell脚本启动服务(upstart),从cron作业启动

时间:2012-11-23 00:32:36

标签: linux shell cron centos upstart

我正在尝试使用cron作业调用我编写的健康检查脚本来检查我写过的web应用程序(api)的状态(url调用不足以测试完整功能,因此自定义健康检查)。 healthcheck应用程序有几个端点,从shell脚本调用(见下文),这个脚本重新启动我们正在检查的更大的Web应用程序。当然,我遇到了麻烦。

工作原理: 1)cron作业每60秒运行一次 2)healthcheck脚本由cron作业运行 3)healthcheck脚本检查url,如果url返回非200响应,则停止并启动服务

什么有效: 1)我可以运行脚本(healthcheck.sh)作为ec2用户 2)我可以以root身份运行脚本 3)cron作业调用脚本并运行,但它不会停止/启动服务(我可以通过观察/tmp/crontest.txt和ps aux看到这一点。)

这看起来像是一个权限问题或一些我不了解的非常基本的linux事件。


以root用户身份运行的日志或ec2-user(/tmp/crontest.txt):

Fri Nov 23 00:28:54 UTC 2012
healthcheck.sh: api not running, restarting service!
api start/running, process 1939 <--- it restarts the service properly!

cron作业运行时的日志:

Fri Nov 23 00:27:01 UTC 2012
healthcheck.sh: api not running, restarting service! <--- no restart

Cron文件(在/etc/cron.d中):

# Call the healthcheck every 60s
* * * * * root /srv/checkout/healthcheck/healthcheck.sh >> /tmp/crontest.txt

Upstart脚本(/etc/init/healthcheck.conf) - 这是针对healthcheck应用程序的,它提供了我们从shell脚本healthcheck.sh调用的端点:

#/etc/init/healthcheck.conf
description "healthcheck"
author "me"

env USER=ec2-user

start on started network
stop on stopping network

script
    # We run our process as a non-root user
    # Upstart user guide, 11.43.2 (http://upstart.ubuntu.com/cookbook/#run-a-job-as-a-different-user)
    exec su -s /bin/sh -c "NODE_ENV=production /usr/local/bin/node /srv/checkout/healthcheck/app.js" $USER
end script

Shell脚本权限:

-rwxr-xr-x 1 ec2-user ec2-user 529 Nov 23 00:16 /srv/checkout/healthcheck/healthcheck.sh

Shell脚本(healthcheck.sh):

#!/bin/bash

API_URL="http://localhost:4567/api"

echo `date`

status_code=`curl -s -o /dev/null -I -w "%{http_code}" $API_URL`
if [ 200 -ne $status_code ]; then
  echo "healthcheck.sh: api not running, restarting service!"
  stop api
  start api
fi

2 个答案:

答案 0 :(得分:4)

为脚本添加启动/停止命令的路径:

#!/bin/bash

PATH=$PATH:/sbin/

或启动和停止命令的完整路径:

/sbin/stop api

你可以使用whereis检查他们的路径:

$ whereis start
/sbin/start

答案 1 :(得分:3)

another question中的答案!

基本上cron作业在有限的环境中运行,所以在'start [service]'中,找不到启动命令!

修改脚本使其正常工作:

#!/bin/bash
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/opt/usr/bin:/opt/usr/sbin:/usr/local/bin:/usr/local/sbin"
...
相关问题