linux - 从 cron 作业的 shell 脚本启动服务( Upstart )

标签 linux shell cron centos upstart

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

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

什么有效: 1) 我可以以 ec2-user 身份运行脚本 (healthcheck.sh) 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

最佳答案

将启动/停止命令的路径添加到您的脚本:

#!/bin/bash

PATH=$PATH:/sbin/

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

/sbin/stop api

您可以使用 whereis 检查它们的路径:

$ whereis start
/sbin/start

关于linux - 从 cron 作业的 shell 脚本启动服务( Upstart ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521774/

相关文章:

ruby - Bash I/O 重定向可以在 Ruby 脚本中工作吗?

Linux:如何列出有关文件或目录的信息(大小,权限,按类型划分的文件数?)

PHP Cronjob 与 CPanel

php - 如何用 MySQL 重新索引 Sphinx

python - 将 URL 分配给 python 脚本以在 Google Cloud 上运行 cron 作业?

php - 特定网页启动偶尔会导致500内部错误

linux - Perl 脚本在我的电脑上运行良好,但在远程服务器上运行不正常

macos - 如何使用 bash 创建具有随机数据的多个文件

linux - 是否可以更改目录模式以使任何人都无法在其中创建新文件?

c++ - SmartGit (git) 幽灵修改