bash - 检查蚊子健康的脚本

标签 bash docker mosquitto

我正在尝试为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/

相关文章:

java - 如何在 Android 中部署 Moquette 代理?

java - messageArrived 方法出现异常时 MQTT 重试

mysql - 在bash的单个 session 中执行多个mysql语句

linux - bash 脚本中的日期变量

Dockerfile、sbt- assembly - 是否可以在 dockerfile 中使用 sbt- assembly ?

docker - docker run "--memory"选项期望什么单位?

regex - 删除换行符 (\n) 但排除具有特定正则表达式的行?

bash - 在 bash 中,退出脚本而不退出 shell 或从子 shell 中导出/设置变量

postgresql - 无法通过 Play 框架服务器连接到 postgresql docker 容器

mqtt - 泛美卫生组织客户端如何知道网桥连接的状态?