如何为&&分隔的多个命令创建PID陷阱

时间:2015-11-27 15:49:49

标签: bash docker signals stardog

我在Ubuntu 15.04容器中运行Stardog 4.0,打开jdk8运行正常。我想使用陷阱来处理gracefully shutting down stardog

要在容器中执行stardog以便继续运行,我一直在使用以下哪个效果很好

$SBIN/bin/stardog-admin server start && (tail -f /storage/stardog.log &) && while (pidof java > /dev/null); do sleep 1; done

如果没有以下内容,容器将运行几秒钟并停止

&& (tail -f /storage/stardog.log &) && while (pidof java > /dev/null); do sleep 1; done

然而,这导致容器内的多个PID

root         1  0.0  0.0  18384  3236 ?        Ss   14:04   0:02 /bin/bash /stardog_binaries/startup.sh
root        45  0.1  4.9 4619052 406940 ?      Sl   14:04   0:10 java -Xms2g -Xmx2g -XX:MaxDirectMemorySize=4g -XX:SoftRefLRUPolicyMSPerMB=1 -XX:+UseParallelOldGC -XX:+UseCompressedOops -Djavax.xml.datatype.DatatypeFactory=org.apache.xerc
root        97  0.0  0.0   4412   740 ?        S    14:04   0:00 tail -f /storage/stardog.log
root     12108  0.2  0.0  18184  3100 ?        Ss   15:44   0:00 bash
root     12122  0.0  0.0   4376   784 ?        S    15:44   0:00 sleep 1

当容器关闭时,以下陷阱无法关闭stardog

trap 'kill -TERM $PID' TERM INT
$SBIN/bin/stardog-admin server start && (tail -f /storage/stardog.log &) && while (pidof java > /dev/null); do sleep 1; done
PID=$!
wait $PID
trap - TERM INT
wait $PID
EXIT_STATUS=$?

所以我的问题是如何正确捕获$ SBIN / bin / stardog-admin服务器启动,这样当容器关闭时,stardog会正常退出。

此致 康特

2 个答案:

答案 0 :(得分:1)

您可以使用专门用于处理此类问题的图片,例如phusion/baseimage-docker

请参阅" PID 1 zombie reaping issue":declaring your script as a daemon,您将确保图像正确处理关机信号。

答案 1 :(得分:1)

最后,我在容器中创建了一个runstardog.sh脚本。

set -e
function shutdown() {        
 $STARDOG_BINARIES/bin/stardog-admin server stop  -p xxx -u admin    
}

$STARDOG_BINARIES/bin/stardog-admin server start && (tail -f /storage/stardog.log &) && while (pidof java > /dev/null); do sleep 1; done

trap "{ shutdown }" EXIT
exit 0

由包含以下陷阱的startup.sh脚本执行

trap 'kill -TERM $PID' TERM INT
$STARDOG_BINARIES/runstardog.sh &
PID=$!
wait $PID
trap - TERM INT
wait $PID
EXIT_STATUS=$?

然后当我想要停止服务器时,我在托管容器的服务器上调用stop.sh,该容器标识stardog容器的CID,使用docker exec关闭stardog并停止并删除容器。

replace="\1"
find="([a-z0-9]{12})\s+platform_stardog.*"
CID=$( docker ps | tail --lines=+2 | sed "/platform_stardog/!d"  | perl -lpe  "s@$find@$replace@g"  )

if [ -z "$CID" ]; 
then
    echo "No existing container named platform_stardog was found"
else
    echo "docker exec  /stardog_binaries/stopstardog.sh in platform_stardog Container $CID:"
    docker exec ${CID} /stardog_binaries/stopstardog.sh
    echo "stop and delete docker container."
    /usr/local/bin/docker-compose -p platform -f docker-compose.yml stop -t 30 stardog && /usr/local/bin/docker-compose -p platform -f docker-compose.yml rm --force -v stardog
fi

我得到确认,这是因为stardog的输出' Stardog服务器成功收到关机请求'并且关机过程不需要很长时间。它曾经通过docker compose stop -t 30指定挂起30秒

谢谢@VonC我接下来会尝试这种方法。