SIGTERM未被AWS ECS docker容器捕获



我有以下ECS容器定义

ContainerDefinitions:
- Name: myfluentd
Essential: true
Image: !Ref DockerImage
MountPoints:
- SourceVolume: efs-volume
ContainerPath: '/fluentd/buffers'
ReadOnly: false
PortMappings:
- ContainerPort: 24224
HostPort: 24224
Protocol: tcp
EntryPoint:
- "/var/lib/twistlock/defender.sh"
- "defender"
- "entrypoint"
- "tini"
- "--"
- "/bin/entrypoint.sh"
Command:
- fluentd
VolumesFrom:
- ReadOnly: false
SourceContainer: "TwistlockDefender"

ENTRYPOINT

["/var/lib/twistlock/fargate/fargate_defender.sh","fargate","entrypoint","tini","--","/bin/entrypoint.sh"]

entrypoint.sh的内容

#!/bin/sh
#source vars if file exists
DEFAULT=/etc/default/fluentd
if [ -r $DEFAULT ]; then
set -o allexport
. $DEFAULT
set +o allexport
fi
# If the user has supplied only arguments append them to `fluentd` command
if [ "${1#-}" != "$1" ]; then
set -- fluentd "$@"
fi
# If user does not supply config file or plugins, use the default
if [ "$1" = "fluentd" ]; then
if ! echo $@ | grep ' -c' ; then
set -- "$@" -c /fluentd/etc/${FLUENTD_CONF}
fi
if ! echo $@ | grep ' -p' ; then
set -- "$@" -p /fluentd/plugins
fi
fi
. /bin/env.sh
task_cleanup() {
echo "Deleting files"
rm -rf /tmp/*
exit
}
trap task_cleanup SIGTERM SIGINT
exec "$@"

当我停止ECS任务时,它会向容器发出SIGTERM,我希望它执行task_cleanup(),但信号没有被捕获。

我登录到容器以检查进程

PID   USER     TIME  COMMAND
1 fluent    0:00 sh /var/lib/twistlock/defender.sh defender entrypoint tini -- /bin/entrypoint.sh fluentd
7 fluent    0:00 /var/lib/twistlock/defender defender entrypoint tini -- /bin/entrypoint.sh fluentd
16 root      0:00 /managed-agents/execute-command/amazon-ssm-agent
22 fluent    0:00 /sbin/tini -- /bin/entrypoint.sh fluentd
29 fluent    0:02 {fluentd} /usr/bin/ruby /usr/bin/fluentd -c /fluentd/etc/fluent.conf -p /fluentd/plugins
72 root      0:00 /managed-agents/execute-command/ssm-agent-worker
90 fluent    1:06 /usr/bin/ruby -Eascii-8bit:ascii-8bit /usr/bin/fluentd -c /fluentd/etc/fluent.conf -p /fluentd/plugins --under-supervisor
546 root      0:00 /managed-agents/execute-command/ssm-session-worker ecs-execute-command-03931001c6df08625
556 root      0:00 /bin/bash
870 root      0:00 ps aux 

我错过了什么?为什么信号没有被捕获?

更新:ENTRYPOINT启动了两个容器,我认为信号只发送到第一个容器——当我移除第一个容器时,我能够看到清理工作正在进行。有什么想法吗?

根据exec(粗体矿(的POSIX文档:

如果exec是用command指定的,它将command替换shell,而不创建新进程。。。

调用exec "$@"后,您的shell进程和使用trap创建的信号处理程序将不存在。

这可能会达到你想要的效果,但它完全没有经过测试,我还没有分析你构建的字符串"$@"

.
.
.
task_cleanup() {
echo "Deleting files"
rm -rf /tmp/*
}
trap task_cleanup SIGTERM SIGINT
# background the task
"$@" &
pid=$!
wait $pid
kill $pid
exit

这将把命令作为shell的子进程运行,而不是用"$@"中的命令替换shell。

test.sh中保存以下脚本

#!/usr/bin/env bash

task_cleanup() {
echo "Deleting files"
}
trap task_cleanup SIGTERM
"$@"

并使用运行

bash test.sh sleep 60

现在运行ps -ef|grep "bash test.sh sleep 60"(在另一个bash会话中(获取PID,然后运行

kill -TERM PID

进程将捕获信号TERM,但仅在sleep 60完成后运行task_cleanup

相关内容

  • 没有找到相关文章

最新更新