我正在尝试为mosquitto创建一个运行状况检查脚本(供docker使用)。
if [ -z "$USERNAME" ]; then
mosquitto_sub -t '$SYS/#' -C 1 | grep -v Error || exit 1
else
mosquitto_sub -t '$SYS/#' -C 1 -u $USERNAME -P $PASSWRD | grep -v Error || exit 1
fi
我遇到的问题是,如果给了不正确的密码,mosquitto_sub只会不断输出
Connection Refused: not authorised.
,而docker中的超时内容似乎是flakey,所以它永远不会结束。看起来mosquitto并没有提供更好的失败方法。我认为我可能需要将其作为可以杀死的后台进程执行,但是我的bash并不是那么好,所以有人有更好的主意吗?
[编辑-根据BMitch的建议进行了更新]
我已将脚本修改为如下所示:
#!/bin/sh
if [ -z "$USERNAME" ]; then
(sleep 10; kill $$) & exec mosquitto_sub -t '$SYS/#' -C 1 | grep -v Error || exit 1 "$@"
else
(sleep 10; kill $$) & exec mosquitto_sub -t '$SYS/#' -u $USERNAME -P $PASSWORD -C 1 | grep -v Error || exit 1 "$@"
fi
但是运行它只会得到以下输出:
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Terminated
root@e30e9cadd8fc:/# Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
最佳答案
关于如何使正在运行的脚本超时,有一个bash FAQ。尝试将mosquitto_sub替换为包含以下内容的mosquitto_sub_timeout.sh:
#!/bin/bash
(sleep 10; kill $$) & exec mosquitto_sub "$@"
然后,您的运行状况检查脚本将如下所示:
if [ -z "$USERNAME" ]; then
mosquitto_sub_timeout.sh -t '$SYS/#' -C 1 | grep -v Error || exit 1
else
mosquitto_sub_timeout.sh -t '$SYS/#' -C 1 -u $USERNAME -P $PASSWRD | grep -v Error || exit 1
fi
正如bash FAQ中提到的那样,最后一次更新,只要安装在您的容器中,timeout命令可能是所有它们的最佳解决方案:
if [ -z "$USERNAME" ]; then
timeout --foreground 10 mosquitto_sub -t '$SYS/#' -C 1 | grep -v Error || exit 1
else
timeout --foreground 10 mosquitto_sub -t '$SYS/#' -C 1 -u $USERNAME -P $PASSWRD | grep -v Error || exit 1
fi
关于bash - 检查蚊子健康的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275666/